name: Beta Release

on:
  push:
    branches: [develop]

jobs:
  beta:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.24'

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: '22'

      - name: Cache Go modules
        uses: actions/cache@v4
        with:
          path: |
            /root/go/pkg/mod
            /home/runner/go/pkg/mod
          key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
          restore-keys: |
            ${{ runner.os }}-go-

      - name: Cache Node modules (web)
        uses: actions/cache@v4
        with:
          path: web/node_modules
          key: ${{ runner.os }}-node-web-${{ hashFiles('web/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-web-

      - name: Download Go dependencies
        run: go mod download

      - name: Build frontend
        run: |
          cd web
          npm ci
          npm run build

      - name: Build extension
        run: |
          cd extension
          npm ci
          npx wxt zip
          mkdir -p ../dist
          mv .output/muyue-extension-*.zip ../dist/

      - name: Vet
        run: go vet ./...

      - name: Test
        run: go test ./... -v -race -timeout 60s

      - name: Determine version
        id: version
        run: |
          BASE_VERSION=$(grep 'Version =' internal/version/version.go | cut -d'"' -f2)
          COMMIT_COUNT=$(git rev-list --count $(git tag -l 'v*.beta.*' --sort=-v:refname | head -1)..HEAD 2>/dev/null || git rev-list --count HEAD)
          BETA_NUM=$(git tag -l "v${BASE_VERSION}-beta.*" --sort=-v:refname | head -1 | grep -o 'beta\.[0-9]*' | grep -o '[0-9]*' || echo "0")
          BETA_NUM=$((BETA_NUM + 1))
          VERSION="v${BASE_VERSION}-beta.${BETA_NUM}"
          echo "version=${VERSION}" >> $GITHUB_OUTPUT
          echo "base=${BASE_VERSION}" >> $GITHUB_OUTPUT
          echo "beta_num=${BETA_NUM}" >> $GITHUB_OUTPUT
          echo "Building beta release: ${VERSION}"

      - name: Generate Windows resource (icon)
        run: |
          go install github.com/akavel/rsrc@latest
          RSRC="$(go env GOPATH)/bin/rsrc"
          $RSRC -ico assets/muyue.ico -arch amd64 -o cmd/muyue/rsrc_windows_amd64.syso
          $RSRC -ico assets/muyue.ico -arch arm64 -o cmd/muyue/rsrc_windows_arm64.syso

      - name: Build (all platforms)
        run: |
          mkdir -p dist
          VERSION=${{ steps.version.outputs.version }}
          LDFLAGS="-s -w -X github.com/muyue/muyue/internal/version.Prerelease=${VERSION#v}"
          WIN_LDFLAGS="$LDFLAGS -H=windowsgui"
          CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags="$LDFLAGS" -o dist/muyue-linux-amd64 ./cmd/muyue/
          CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="$LDFLAGS" -o dist/muyue-linux-arm64 ./cmd/muyue/
          CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -ldflags="$LDFLAGS" -o dist/muyue-darwin-amd64 ./cmd/muyue/
          CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags="$LDFLAGS" -o dist/muyue-darwin-arm64 ./cmd/muyue/
          CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="$WIN_LDFLAGS" -o dist/muyue-windows-amd64.exe ./cmd/muyue/
          CGO_ENABLED=0 GOOS=windows GOARCH=arm64 go build -ldflags="$WIN_LDFLAGS" -o dist/muyue-windows-arm64.exe ./cmd/muyue/

      - name: Package archives
        run: |
          cd dist
          sha256sum * > checksums.txt
          tar czf muyue-linux-amd64.tar.gz muyue-linux-amd64
          tar czf muyue-linux-arm64.tar.gz muyue-linux-arm64
          tar czf muyue-darwin-amd64.tar.gz muyue-darwin-amd64
          tar czf muyue-darwin-arm64.tar.gz muyue-darwin-arm64
          zip muyue-windows-amd64.zip muyue-windows-amd64.exe
          zip muyue-windows-arm64.zip muyue-windows-arm64.exe
          rm -f muyue-linux-amd64 muyue-linux-arm64 muyue-darwin-amd64 muyue-darwin-arm64 muyue-windows-amd64.exe muyue-windows-arm64.exe

      - name: Generate changelog
        id: changelog
        run: |
          LAST_STABLE=$(git tag -l 'v[0-9]*.[0-9]*.[0-9]*' --sort=-v:refname | grep -v '-' | head -1 || echo "")
          if [ -n "$LAST_STABLE" ]; then
            RANGE="${LAST_STABLE}..HEAD"
          else
            RANGE="HEAD~20..HEAD"
          fi
          echo "Generating changelog from ${RANGE}"
          {
            echo "## ${{ steps.version.outputs.version }} (Beta)"
            echo ""
            echo "### Commits since ${LAST_STABLE:-start}"
            echo ""
            git log ${RANGE} --pretty=format:"- %s (%h)" --no-merges
            echo ""
            echo ""
            echo "> This is a **beta** release. Use at your own risk."
          } > /tmp/beta_changelog.md
          echo "path=/tmp/beta_changelog.md" >> $GITHUB_OUTPUT

      - name: Create release
        env:
          GITEA_TOKEN: ${{ secrets.GITEATOKEN }}
        run: |
          if [ -z "$GITEA_TOKEN" ]; then
            echo "Warning: GITEATOKEN not set, skipping release"
            exit 0
          fi
          VERSION=${{ steps.version.outputs.version }}
          API="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases"
          BODY=$(cat /tmp/beta_changelog.md)
          RESPONSE=$(curl -s -X POST "${API}" \
            -H "Authorization: token ${GITEA_TOKEN}" \
            -H "Content-Type: application/json" \
            -d "{
              \"tag_name\":\"${VERSION}\",
              \"target_commitish\":\"develop\",
              \"name\":\"muyue ${VERSION} (Beta)\",
              \"body\":$(echo "$BODY" | jq -Rs .),
              \"draft\":false,
              \"prerelease\":true
            }")
          RELEASE_ID=$(echo "$RESPONSE" | grep -o '"id":[0-9]*' | head -1 | grep -o '[0-9]*')
          if [ -z "$RELEASE_ID" ]; then
            echo "Failed to create release:"
            echo "$RESPONSE"
            exit 1
          fi
          echo "Release ID: ${RELEASE_ID}"
          UPLOAD_URL="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases/${RELEASE_ID}/assets"
          for file in dist/*.tar.gz dist/muyue-windows-*.zip dist/checksums.txt dist/muyue-extension-*.zip; do
            filename=$(basename "$file")
            echo "Uploading ${filename}..."
            curl -s -X POST "${UPLOAD_URL}" \
              -H "Authorization: token ${GITEA_TOKEN}" \
              -F "attachment=@${file};filename=${filename}" > /dev/null
          done
          echo "Beta release ${VERSION} published!"
