name: Build macOS

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, path: dist/, retention-days: 1 }

  tauri:
    name: Tauri (macOS)
    needs: frontend
    runs-on: macos-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Read versions
        run: |
          source .github/read_versions.sh
          echo "SUWA_VERSION=$SUWA_VERSION"             >> $GITHUB_ENV
          echo "SUWA_HASH_ARM64=$SUWA_HASH_MACOS_ARM64" >> $GITHUB_ENV
          echo "SUWA_HASH_X64=$SUWA_HASH_MACOS_X64"     >> $GITHUB_ENV

      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: "aarch64-apple-darwin,x86_64-apple-darwin"

      - 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 binaries
        run: |
          dl() {
            local asset="$1" sha="$2" outdir="$3"
            curl -fsSL \
              "https://github.com/Suwayomi/Suwayomi-Server-preview/releases/download/v${SUWA_VERSION}/${asset}" \
              -o "${outdir}.tar.gz"
            echo "${sha}  ${outdir}.tar.gz" | shasum -a 256 -c -
            mkdir -p "${outdir}"
            tar -xzf "${outdir}.tar.gz" -C "${outdir}" --strip-components=1
          }
          dl "Suwayomi-Server-v${SUWA_VERSION}-macOS-arm64.tar.gz" "$SUWA_HASH_ARM64" suwayomi-arm64
          dl "Suwayomi-Server-v${SUWA_VERSION}-macOS-x64.tar.gz"   "$SUWA_HASH_X64"   suwayomi-x64

      - name: Stage Suwayomi sidecars
        run: |
          mkdir -p src-tauri/binaries
          stage() {
            local srcdir="$1" arch="$2"
            JAR=$(find "$srcdir" -name "Suwayomi-Server.jar" | head -1)
            JAVA=$(find "$srcdir" -path "*/jre/bin/java" | head -1)
            [ -z "$JAR"  ] && { echo "ERROR: jar not found in $srcdir";  find "$srcdir" -type f | head -30; exit 1; }
            [ -z "$JAVA" ] && { echo "ERROR: java not found in $srcdir"; find "$srcdir" -type f | head -30; exit 1; }
            cp -r "$srcdir" "src-tauri/binaries/suwayomi-bundle-${arch}"
            cp src-tauri/binaries/suwayomi-launcher.sh "src-tauri/binaries/suwayomi-server-${arch}"
            chmod +x "src-tauri/binaries/suwayomi-server-${arch}"
          }
          stage suwayomi-arm64 aarch64-apple-darwin
          stage suwayomi-x64   x86_64-apple-darwin

      - name: Patch tauri.conf.json for CI
        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: Build Tauri app (aarch64)
        run: |
          rm -rf src-tauri/binaries/suwayomi-bundle
          cp -r src-tauri/binaries/suwayomi-bundle-aarch64-apple-darwin src-tauri/binaries/suwayomi-bundle
          pnpm tauri build --target aarch64-apple-darwin --config src-tauri/tauri.macos.conf.json
        env:
          APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY || '-' }}

      - name: Build Tauri app (x86_64)
        run: |
          rm -rf src-tauri/binaries/suwayomi-bundle
          cp -r src-tauri/binaries/suwayomi-bundle-x86_64-apple-darwin src-tauri/binaries/suwayomi-bundle
          pnpm tauri build --target x86_64-apple-darwin --config src-tauri/tauri.macos.conf.json
        env:
          APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY || '-' }}

      - name: Upload macOS artifacts to release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          for i in $(seq 1 12); do
            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 }}") | .id' | head -1)
            [ -n "$RELEASE_ID" ] && break
            echo "Waiting for release... attempt $i"; sleep 15
          done
          [ -z "$RELEASE_ID" ] && { echo "ERROR: release not found"; exit 1; }

          upload() {
            curl -s -X POST \
              -H "Authorization: Bearer $GITHUB_TOKEN" \
              -H "Content-Type: application/octet-stream" \
              --data-binary @"$1" \
              "https://uploads.github.com/repos/moku-project/Moku/releases/$RELEASE_ID/assets?name=$2"
          }

          ARM64=$(find src-tauri/target/aarch64-apple-darwin/release/bundle/dmg -name "*.dmg" | head -1)
          X64=$(find src-tauri/target/x86_64-apple-darwin/release/bundle/dmg -name "*.dmg" | head -1)
          [ -n "$ARM64" ] && upload "$ARM64" "moku-macos-arm64-${{ github.event.inputs.version }}.dmg"
          [ -n "$X64"   ] && upload "$X64"   "moku-macos-x64-${{ github.event.inputs.version }}.dmg"
