name: Deploy — Chrome Web Store

on:
  push:
    tags:
      - 'v*.*.*'
  workflow_dispatch:
    inputs:
      publish:
        description: 'Publish after upload? (yes/no)'
        required: false
        default: 'yes'

jobs:
  deploy:
    name: Build & Deploy to Chrome Web Store
    runs-on: ubuntu-latest
    timeout-minutes: 20
    container:
      image: node:22-bookworm

    steps:
      - name: Install deps
        run: apt-get update -qq && apt-get install -y zip curl

      - name: Checkout
        run: |
          git clone ${{ gitea.server_url }}/${{ gitea.repository }}.git .
          git checkout ${{ gitea.sha }}

      - name: Install dependencies
        run: npm ci

      # Same gates as CI — a release must never check less than a push.
      - name: Prepare WXT types
        run: npx wxt prepare

      - name: Type check
        run: npm run typecheck

      - name: Run tests
        run: npm test -- --run

      - name: Build extension
        run: npm run build

      - name: Package as ZIP
        run: |
          VERSION=${{ gitea.ref_name || 'manual' }}
          ZIPFILE="$(pwd)/lexai-chrome-mv3-${VERSION}.zip"
          # Verify manifest exists and check version
          node -e "console.log('Manifest version:', require('./.output/chrome-mv3/manifest.json').version)"
          # Zip from inside the chrome-mv3 dir so manifest.json is at root
          cd .output/chrome-mv3 && zip -r "$ZIPFILE" . && cd -
          echo "ZIP_FILE=${ZIPFILE}" >> $GITHUB_ENV
          echo "VERSION=${VERSION}" >> $GITHUB_ENV
          echo "✅ Packaged: lexai-chrome-mv3-${VERSION}.zip"


      - name: Get Chrome Web Store OAuth2 Token
        run: |
          TOKEN_RESPONSE=$(curl -s -X POST "https://oauth2.googleapis.com/token" \
            -d "client_id=${{ secrets.CWS_CLIENT_ID }}" \
            -d "client_secret=${{ secrets.CWS_CLIENT_SECRET }}" \
            -d "refresh_token=${{ secrets.CWS_REFRESH_TOKEN }}" \
            -d "grant_type=refresh_token")
          ACCESS_TOKEN=$(echo "$TOKEN_RESPONSE" | node -e "let s='';process.stdin.on('data',d=>s+=d);process.stdin.on('end',()=>{let d;try{d=JSON.parse(s)}catch(e){console.error('Invalid JSON token response:',s);process.exit(1)};if(!d.access_token){console.error('No access_token in response:',s);process.exit(1)};console.log(d.access_token)})")
          if [ -z "$ACCESS_TOKEN" ]; then
            echo "❌ Failed to get access token. Response: $TOKEN_RESPONSE"
            exit 1
          fi
          echo "CWS_ACCESS_TOKEN=${ACCESS_TOKEN}" >> $GITHUB_ENV
          echo "✅ OAuth2 token obtained"

      - name: Upload to Chrome Web Store
        run: |
          UPLOAD_BODY=$(curl -s -X PUT \
            "https://www.googleapis.com/upload/chromewebstore/v1.1/items/${{ secrets.CWS_EXTENSION_ID }}" \
            -H "Authorization: Bearer ${{ env.CWS_ACCESS_TOKEN }}" \
            -H "x-goog-api-version: 2" \
            -T "${{ env.ZIP_FILE }}")
          echo "Upload Response: $UPLOAD_BODY"
          UPLOAD_STATE=$(echo "$UPLOAD_BODY" | node -e "let s='';process.stdin.on('data',d=>s+=d);process.stdin.on('end',()=>{let d;try{d=JSON.parse(s)}catch(e){console.error('Invalid JSON upload response:',s);process.exit(1)};console.log(d.uploadState||'')})")
          echo "Upload state: $UPLOAD_STATE"
          if [ "$UPLOAD_STATE" != "SUCCESS" ]; then
            echo "❌ Upload failed — state: $UPLOAD_STATE"
            exit 1
          fi
          echo "✅ Uploaded to Chrome Web Store"

      - name: Publish to Chrome Web Store
        if: ${{ gitea.event_name == 'push' || github.event.inputs.publish == 'yes' }}
        run: |
          PUBLISH_RESPONSE=$(curl -s -w "\n%{http_code}" -X POST \
            "https://www.googleapis.com/chromewebstore/v1.1/items/${{ secrets.CWS_EXTENSION_ID }}/publish" \
            -H "Authorization: Bearer ${{ env.CWS_ACCESS_TOKEN }}" \
            -H "x-goog-api-version: 2" \
            -H "Content-Length: 0")
          HTTP_CODE=$(echo "$PUBLISH_RESPONSE" | tail -n 1)
          BODY=$(echo "$PUBLISH_RESPONSE" | sed '$d')
          echo "Publish HTTP: $HTTP_CODE"
          echo "Publish Response: $BODY"
          STATUS=$(echo "$BODY" | grep -o '"status":\["[^"]*"\]' | head -1)
          echo "Publish status: $STATUS"
          if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 300 ]; then
            echo "✅ Published to Chrome Web Store!"
          else
            echo "❌ Publish failed: HTTP $HTTP_CODE"
            exit 1
          fi

      - name: Notify Success
        if: success()
        run: |
          VERSION=${{ env.VERSION }}
          curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendMessage" \
            -d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" \
            -d "text=🚀 LexAI ${VERSION} deployed to Chrome Web Store!%0A%0A✅ Built%0A✅ Packaged%0A✅ Uploaded%0A✅ Published%0A%0Ahttps://chromewebstore.google.com/detail/${{ secrets.CWS_EXTENSION_ID }}"

      - name: Notify Failure
        if: failure()
        run: |
          VERSION=${{ env.VERSION }}
          curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendMessage" \
            -d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" \
            -d "text=❌ LexAI CWS Deploy FAILED%0A%0AVersion: ${VERSION}%0A%0ACheck: https://git.juankibin.space/kibin/LexAI/actions"
