name: Build and Release

on:
  push:
    branches:
      - main

jobs:
  build-and-release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Check if version already released
        id: version-check
        env:
          GITEA_TOKEN: ${{ secrets.DEST_GITEA_TOKEN }}
        run: |
          VERSION=$(grep '"version"' package.json | head -1 | sed 's/.*"version": *"\([^"]*\)".*/\1/')
          TAG="v$VERSION"
          echo "VERSION=$VERSION" >> "$GITHUB_OUTPUT"
          echo "TAG=$TAG" >> "$GITHUB_OUTPUT"

          STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
            "https://gitea.crjlab.net/api/v1/repos/bigjakk/krunker-civilian-client/releases/tags/$TAG" \
            -H "Authorization: token $GITEA_TOKEN")

          if [ "$STATUS" = "200" ]; then
            echo "Release $TAG already exists, skipping build"
            echo "SKIP=true" >> "$GITHUB_OUTPUT"
          else
            echo "No release for $TAG, proceeding with build"
            echo "SKIP=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Setup Node.js
        if: steps.version-check.outputs.SKIP == 'false'
        uses: actions/setup-node@v4
        with:
          node-version: '22'

      - name: Install system dependencies
        if: steps.version-check.outputs.SKIP == 'false'
        run: |
          dpkg --add-architecture i386
          apt-get update -qq
          apt-get install -y --no-install-recommends \
            wine wine32 wine64 \
            libnss3 libatk1.0-0 libatk-bridge2.0-0 libcups2t64 \
            libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 \
            libxfixes3 libxrandr2 libgbm1 libpango-1.0-0 \
            libcairo2 libasound2t64 libgtk-3-0
          WINEDEBUG=-all wine wineboot --init || true

      - name: Install dependencies
        if: steps.version-check.outputs.SKIP == 'false'
        run: npm ci

      - name: Build source
        if: steps.version-check.outputs.SKIP == 'false'
        run: npm run build

      - name: Build Windows distributables
        if: steps.version-check.outputs.SKIP == 'false'
        env:
          WINEDEBUG: "-all"
        run: npx electron-builder --win -c.electronDist=node_modules/electron/dist-win --publish never

      - name: Build Linux distributables
        if: steps.version-check.outputs.SKIP == 'false'
        run: npx electron-builder --linux --publish never

      - name: Report build sizes
        if: steps.version-check.outputs.SKIP == 'false'
        run: |
          echo "=== Build output sizes ==="
          ls -lh out/*.exe out/*.AppImage out/*.deb 2>/dev/null || true
          echo "=== Electron dist-win (patched Windows) ==="
          du -sh node_modules/electron/dist-win/ 2>/dev/null || true
          echo "=== Electron dist (stock Linux) ==="
          du -sh node_modules/electron/dist/ 2>/dev/null || true
          echo "=== Unpacked Windows build ==="
          du -sh out/win-unpacked/ 2>/dev/null || true
          du -sh out/win-unpacked/resources/ 2>/dev/null || true
          du -sh out/win-unpacked/locales/ 2>/dev/null || true

      - name: Create release and upload assets
        if: steps.version-check.outputs.SKIP == 'false'
        env:
          GITEA_TOKEN: ${{ secrets.DEST_GITEA_TOKEN }}
          TAG: ${{ steps.version-check.outputs.TAG }}
        run: |
          GITEA_BASE="https://gitea.crjlab.net"
          REPO="bigjakk/krunker-civilian-client"

          # Create tag
          curl -s -X POST "$GITEA_BASE/api/v1/repos/$REPO/tags" \
            -H "Authorization: token $GITEA_TOKEN" \
            -H "Content-Type: application/json" \
            -d "{\"tag_name\": \"$TAG\", \"message\": \"$TAG\", \"target\": \"$GITHUB_SHA\"}"

          # Create release
          RESPONSE=$(curl -s -X POST "$GITEA_BASE/api/v1/repos/$REPO/releases" \
            -H "Authorization: token $GITEA_TOKEN" \
            -H "Content-Type: application/json" \
            -d "{
              \"tag_name\": \"$TAG\",
              \"name\": \"$TAG\",
              \"body\": \"Automated build for $TAG\",
              \"draft\": false,
              \"prerelease\": false
            }")

          RELEASE_ID=$(echo "$RESPONSE" | jq -r '.id')
          echo "Created release ID: $RELEASE_ID"

          if [ "$RELEASE_ID" = "null" ] || [ -z "$RELEASE_ID" ]; then
            echo "Failed to create release:"
            echo "$RESPONSE"
            exit 1
          fi

          # Upload all built artifacts
          for file in out/*.exe out/*.AppImage out/*.deb; do
            [ -f "$file" ] || continue
            FILENAME=$(basename "$file")
            SAFE_NAME=$(echo "$FILENAME" | tr ' ' '_')
            echo "Uploading: $SAFE_NAME ($(du -h "$file" | cut -f1))"

            curl -s -X POST \
              "$GITEA_BASE/api/v1/repos/$REPO/releases/$RELEASE_ID/assets?name=$SAFE_NAME" \
              -H "Authorization: token $GITEA_TOKEN" \
              -F "attachment=@$file" \
              | jq -r '"  -> \(.name) (\(.size) bytes)"'
          done

          echo "All assets uploaded"
