name: CI

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

concurrency:
  group: ci-${{ github.ref }}
  cancel-in-progress: true

jobs:
  verify:
    name: Test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm run test:ci

  pack:
    name: Verify Package
    needs: [verify]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm pack --dry-run
      - name: Verify pi fields
        run: |
          node -e "
            const pkg = require('./package.json');
            if (!pkg.pi) throw new Error('Missing pi field');
            if (!pkg.keywords.includes('pi-package')) throw new Error('Missing pi-package keyword');
            console.log('✅ pi fields valid');
          "

  publish:
    name: Publish to npm
    needs: [pack]
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
          registry-url: https://registry.npmjs.org
      - run: npm ci
      - name: Determine npm tag
        id: tag
        run: |
          VERSION="${GITHUB_REF#refs/tags/v}"
          if [[ "$VERSION" == *"-"* ]]; then TAG="next"
          elif [[ "$VERSION" == *"rc"* ]]; then TAG="rc"
          else TAG="latest"
          fi
          echo "tag=$TAG" >> "$GITHUB_OUTPUT"
          echo "📌 Publishing v${VERSION} as @${TAG}"
      - name: Verify version consistency
        run: |
          PKG_VER=$(node -p "require('./package.json').version")
          TAG_VER="${GITHUB_REF#refs/tags/v}"
          [ "$PKG_VER" = "$TAG_VER" ] || (echo "❌ Version mismatch" && exit 1)
      - run: npm publish --provenance --access public --tag ${{ steps.tag.outputs.tag }}
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

  release:
    name: GitHub Release
    needs: [publish]
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: softprops/action-gh-release@v2
        with:
          generate_release_notes: true
