name: Release — Package & Publish

on:
  push:
    tags:
      - 'v*.*.*'

jobs:
  release:
    name: Build & Package Release
    runs-on: ubuntu-latest
    container:
      image: node:22-bookworm

    steps:
      - name: Install zip
        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

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

      - name: Build extension
        run: npm run build

      - name: Package as ZIP
        run: |
          VERSION=${{ gitea.ref_name }}
          zip -r lexai-chrome-mv3-${VERSION}.zip .output/chrome-mv3/
          echo "ZIP_FILE=lexai-chrome-mv3-${VERSION}.zip" >> $GITHUB_ENV

      - name: Create Release
        run: |
          VERSION=${{ gitea.ref_name }}
          curl -s -X POST "${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}/releases" \
            -H "Authorization: token ${{ secrets.GITEATOKEN }}" \
            -H "Content-Type: application/json" \
            -d "{
              \"tag_name\": \"${VERSION}\",
              \"name\": \"LexAI ${VERSION}\",
              \"body\": \"## LexAI ${VERSION}\n\n### Installation\n1. Download ZIP below\n2. Extract it\n3. Open Chrome → chrome://extensions\n4. Enable Developer Mode\n5. Click Load unpacked → select the extracted folder\",
              \"draft\": false,
              \"prerelease\": false
            }" > release.json
          cat release.json
          RELEASE_ID=$(node -e "const r=require('./release.json'); if(!r.id) { console.error('No release id in response:', JSON.stringify(r)); process.exit(1); } console.log(r.id)")
          echo "RELEASE_ID=${RELEASE_ID}" >> $GITHUB_ENV

      - name: Upload ZIP to Release
        run: |
          VERSION=${{ gitea.ref_name }}
          RELEASE_ID=${{ env.RELEASE_ID }}
          curl -s -X POST "${{ gitea.server_url }}/api/v1/repos/${{ gitea.repository }}/releases/${RELEASE_ID}/assets" \
            -H "Authorization: token ${{ secrets.GITEATOKEN }}" \
            -F "attachment=@lexai-chrome-mv3-${VERSION}.zip"
          echo "✅ Release ${VERSION} published!"

      - name: Publish to Gitea Package Registry
        run: |
          VERSION=${{ gitea.ref_name }}
          curl -s -X PUT "https://git.juankibin.space/api/packages/kibin/generic/lexai-extension/${VERSION}/lexai-chrome-mv3-${VERSION}.zip" \
            -H "Authorization: token ${{ secrets.GITEATOKEN }}" \
            -T lexai-chrome-mv3-${VERSION}.zip
          echo "✅ Published lexai-chrome-mv3-${VERSION}.zip to package registry"
          echo "📦 Download: https://git.juankibin.space/kibin/LexAI/packages"
