name: CI — Test & Build

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  test-and-build:
    name: Test & Build
    runs-on: ubuntu-latest
    timeout-minutes: 15
    container:
      image: node:22-bookworm

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

      - name: Clone repository (triggering ref)
        run: |
          git clone ${{ gitea.server_url }}/${{ gitea.repository }}.git /tmp/lexai
          cd /tmp/lexai
          if [ "${{ gitea.event_name }}" = "pull_request" ]; then
            git fetch origin pull/${{ gitea.event.pull_request.number }}/head:pr
            git checkout pr
          else
            git checkout ${{ gitea.sha }}
          fi

      - name: Install dependencies
        run: npm ci --prefer-offline --no-audit --no-fund
        working-directory: /tmp/lexai

      # Generates .wxt/types (ImportMeta.env etc.) required by typecheck.
      # Also runs via the postinstall hook — kept explicit so a future
      # --ignore-scripts install can't silently break the typecheck step.
      - name: Prepare WXT types
        run: npx wxt prepare
        working-directory: /tmp/lexai

      - name: Type check
        run: npm run typecheck
        working-directory: /tmp/lexai

      - name: Run unit tests
        run: npm test -- --run
        working-directory: /tmp/lexai

      - name: Build extension
        run: npm run build
        working-directory: /tmp/lexai

      - name: Verify build output
        run: ls -la .output/chrome-mv3/
        working-directory: /tmp/lexai

      - name: Package as ZIP
        run: |
          SHA=$(echo "${{ gitea.sha }}" | cut -c1-7)
          TS=$(date +%Y%m%d%H%M%S)
          VERSION=$(node -p "require('./package.json').version")-${SHA}-${TS}
          zip -r /tmp/lexai-chrome-mv3-${VERSION}.zip .output/chrome-mv3/
          echo "PACKAGE_VERSION=${VERSION}" >> $GITHUB_ENV
          echo "✅ Packaged: lexai-chrome-mv3-${VERSION}.zip"
        working-directory: /tmp/lexai

      - name: Publish to Gitea Package Registry
        if: gitea.event_name == 'push'
        run: |
          RESPONSE=$(curl -s -w "\n%{http_code}" -X PUT \
            "${{ gitea.server_url }}/api/packages/kibin/generic/lexai-extension/${PACKAGE_VERSION}/lexai-chrome-mv3-${PACKAGE_VERSION}.zip" \
            -H "Authorization: token ${{ secrets.GITEATOKEN }}" \
            -T "/tmp/lexai-chrome-mv3-${PACKAGE_VERSION}.zip")
          HTTP_CODE=$(echo "$RESPONSE" | tail -n 1)
          BODY=$(echo "$RESPONSE" | sed '$d')
          echo "HTTP: $HTTP_CODE | Response: $BODY"
          if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 300 ]; then
            echo "✅ Published: https://git.juankibin.space/kibin/-/packages"
          else
            echo "⚠️ Package publish returned $HTTP_CODE: $BODY"
            exit 1
          fi
        env:
          PACKAGE_VERSION: ${{ env.PACKAGE_VERSION }}

      - name: Notify Success
        if: success()
        run: |
          SHA=$(echo "${{ gitea.sha }}" | cut -c1-7)
          curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendMessage" \
            -d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" \
            -d "text=✅ LexAI CI Passed%0A%0ABranch: ${{ gitea.ref_name }}%0ACommit: ${SHA}%0A%0AAll steps green — new build published to packages."

      - name: Notify Failure
        if: failure()
        run: |
          SHA=$(echo "${{ gitea.sha }}" | cut -c1-7)
          curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendMessage" \
            -d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" \
            -d "text=❌ LexAI CI FAILED%0A%0ABranch: ${{ gitea.ref_name }}%0ACommit: ${SHA}%0A%0ACheck: https://git.juankibin.space/kibin/LexAI/actions"
