name: Release

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      tag:
        description: 'Tag to release (e.g., v6.3.55)'
        required: true
        type: string
      skip_tests:
        description: 'Skip tests (not recommended)'
        required: false
        default: 'false'
        type: boolean

permissions:
  contents: write
  id-token: write

jobs:
  release:
    runs-on: ubuntu-latest
    timeout-minutes: 15

    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.inputs.tag || github.ref }}
          fetch-depth: 100

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 22
          registry-url: 'https://registry.npmjs.org'
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Run tests
        if: github.event.inputs.skip_tests != 'true'
        run: npm test
        continue-on-error: false

      - name: Build
        run: npm run build

      - name: Run prepublish checks
        run: node ccw/scripts/prepublish-clean.mjs

      - name: Dry run publish
        run: npm publish --dry-run

      - name: Publish to npm
        run: npm publish --provenance --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Create GitHub Release Notes
        if: github.event_name == 'workflow_dispatch'
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ github.event.inputs.tag }}
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Summary
        run: |
          VERSION=${{ github.event.inputs.tag || github.ref_name }}
          echo "### 🚀 Release Published" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "- **Version**: \`${VERSION}\`" >> $GITHUB_STEP_SUMMARY
          echo "- **Registry**: npm (latest)" >> $GITHUB_STEP_SUMMARY
          echo "- **Install**: \`npm install claude-code-workflow@latest\`" >> $GITHUB_STEP_SUMMARY
