name: Publish CLI

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

permissions:
  contents: read
  id-token: write

jobs:
  npm:
    runs-on: ubuntu-latest
    concurrency:
      group: publish-cli-${{ github.ref }}
      cancel-in-progress: false
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: pnpm/action-setup@v4
        with:
          version: 10.33.0

      - uses: actions/setup-node@v4
        with:
          node-version: "24"
          cache: "pnpm"

      - name: Verify release environment
        run: |
          node --version
          npm --version
          node -e "const [major, minor] = process.versions.node.split('.').map(Number); if (major < 22 || (major === 22 && minor < 14)) throw new Error('npm trusted publishing requires Node 22.14.0 or newer')"
          node -e "const { execSync } = require('node:child_process'); const [major, minor, patch] = execSync('npm --version', { encoding: 'utf8' }).trim().split('.').map(Number); if (major < 11 || (major === 11 && (minor < 5 || (minor === 5 && patch < 1)))) throw new Error('npm trusted publishing requires npm 11.5.1 or newer')"

      - run: pnpm install --frozen-lockfile

      - name: Verify tag commit is on main
        run: git merge-base --is-ancestor "$GITHUB_SHA" origin/main

      - name: Verify tag matches CLI package version
        run: |
          version="$(node -p "require('./apps/cli/package.json').version")"
          node -e "const version = process.argv[1]; if (!/^\\d+\\.\\d+\\.\\d+$/.test(version)) throw new Error('Official CLI releases must use a stable semver version')" "$version"
          test "v${version}" = "${GITHUB_REF_NAME}"
          echo "CLI_VERSION=${version}" >> "$GITHUB_ENV"

      - name: Verify version is not already published
        run: |
          if npm view "@markdown-ai/cli@${CLI_VERSION}" version --registry https://registry.npmjs.org >/dev/null 2>&1; then
            echo "@markdown-ai/cli@${CLI_VERSION} is already published"
            exit 1
          fi

      - run: pnpm cli:test

      - run: pnpm -C apps/cli smoke:package

      - run: npm pack --dry-run --json
        working-directory: apps/cli

      - name: Diagnose OIDC environment
        run: |
          echo "GITHUB_ACTIONS=$GITHUB_ACTIONS"
          echo "ACTIONS_ID_TOKEN_REQUEST_URL present: $([ -n "${ACTIONS_ID_TOKEN_REQUEST_URL:-}" ] && echo yes || echo no)"
          echo "ACTIONS_ID_TOKEN_REQUEST_TOKEN present: $([ -n "${ACTIONS_ID_TOKEN_REQUEST_TOKEN:-}" ] && echo yes || echo no)"
          echo "--- npm config (filtered) ---"
          npm config list -l 2>/dev/null | grep -iE "registry|auth|provenance|sigstore|trust|oidc" || true
          echo "--- npm whoami probe ---"
          npm whoami --registry https://registry.npmjs.org || echo "(whoami returned non-zero — expected if OIDC not yet exchanged)"

      - run: npm publish --provenance --access public --loglevel=verbose
        working-directory: apps/cli
