name: Build Windows

on:
  workflow_dispatch:
    inputs:
      version:
        description: "Version to build (e.g. 0.9.0)"
        required: true

permissions:
  contents: write

jobs:
  frontend:
    name: Build frontend
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
        with: { version: 10 }
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: pnpm
      - run: pnpm install --frozen-lockfile
      - run: pnpm build:static
      - uses: actions/upload-artifact@v4
        with: { name: frontend-dist-windows, path: dist/, retention-days: 1 }

  tauri:
    name: Tauri (Windows x64)
    needs: frontend
    runs-on: windows-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/download-artifact@v4
        with: { name: frontend-dist-windows, path: dist/ }

      - name: Read versions
        shell: bash
        run: |
          source .github/read_versions.sh
          echo "SUWA_VERSION=$SUWA_VERSION"     >> $GITHUB_ENV
          echo "SUWA_HASH=$SUWA_HASH_WINDOWS"   >> $GITHUB_ENV

      - uses: dtolnay/rust-toolchain@stable
        with: { targets: x86_64-pc-windows-msvc }

      - uses: Swatinem/rust-cache@v2
        with: { workspaces: src-tauri }

      - uses: pnpm/action-setup@v4
        with: { version: 10 }
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: pnpm
      - run: pnpm install --frozen-lockfile

      - name: Download Suwayomi (Windows x64)
        shell: bash
        run: |
          curl -fsSL \
            "https://github.com/Suwayomi/Suwayomi-Server-preview/releases/download/v${SUWA_VERSION}/Suwayomi-Server-v${SUWA_VERSION}-windows-x64.zip" \
            -o suwayomi-windows.zip
          echo "${SUWA_HASH}  suwayomi-windows.zip" | sha256sum -c -
          unzip -q suwayomi-windows.zip -d suwayomi-raw

      - name: Stage Suwayomi bundle
        shell: bash
        run: |
          mkdir -p suwayomi-extracted
          TOP_DIRS=$(find suwayomi-raw -mindepth 1 -maxdepth 1 -type d | wc -l)
          TOP_FILES=$(find suwayomi-raw -mindepth 1 -maxdepth 1 -type f | wc -l)
          if [ "$TOP_DIRS" -eq 1 ] && [ "$TOP_FILES" -eq 0 ]; then
            cp -r "$(find suwayomi-raw -mindepth 1 -maxdepth 1 -type d | head -1)"/. suwayomi-extracted/
          else
            cp -r suwayomi-raw/. suwayomi-extracted/
          fi
          mkdir -p src-tauri/binaries
          find suwayomi-extracted -path "*/jre/bin/java.exe" | grep -q . \
            || { echo "ERROR: java.exe not found"; find suwayomi-extracted -type f | head -50; exit 1; }
          find suwayomi-extracted -name "Suwayomi-Server.jar" | grep -q . \
            || { echo "ERROR: Suwayomi-Server.jar not found"; find suwayomi-extracted -type f | head -50; exit 1; }
          cp -r suwayomi-extracted src-tauri/binaries/suwayomi-bundle

      - name: Patch tauri.conf.json for CI
        shell: bash
        run: |
          python3 -c "
          import json, pathlib
          p = pathlib.Path('src-tauri/tauri.conf.json')
          c = json.loads(p.read_text())
          c.setdefault('build', {})['beforeBuildCommand'] = ''
          p.write_text(json.dumps(c, indent=2))
          "

      - name: Delete existing draft release
        shell: bash
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          RELEASE_ID=$(curl -s -H "Authorization: Bearer $GITHUB_TOKEN" \
            "https://api.github.com/repos/moku-project/Moku/releases" \
            | jq -r '.[] | select(.tag_name == "v${{ github.event.inputs.version }}" and .draft == true) | .id')
          if [ -n "$RELEASE_ID" ]; then
            curl -s -X DELETE -H "Authorization: Bearer $GITHUB_TOKEN" \
              "https://api.github.com/repos/moku-project/Moku/releases/$RELEASE_ID"
            curl -s -X DELETE -H "Authorization: Bearer $GITHUB_TOKEN" \
              "https://api.github.com/repos/moku-project/Moku/git/refs/tags/v${{ github.event.inputs.version }}"
          fi

      - name: Build Tauri app + create draft release
        uses: tauri-apps/tauri-action@v0
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tagName: v${{ github.event.inputs.version }}
          releaseName: Moku v${{ github.event.inputs.version }}
          releaseBody: |
            Moku v${{ github.event.inputs.version }}

            **Windows:** `Moku_${{ github.event.inputs.version }}_x64-setup.exe`
            **macOS arm64:** `moku-macos-arm64-${{ github.event.inputs.version }}.dmg`
            **macOS x64:** `moku-macos-x64-${{ github.event.inputs.version }}.dmg`
            **Linux:** `moku.flatpak`
          releaseDraft: true
          prerelease: false
          args: --target x86_64-pc-windows-msvc --config src-tauri/tauri.windows.conf.json
