name: Release

# Trigger on version tags (e.g., v2.1.0, v2.1.1, v3.0.0)
on:
  push:
    tags:
      - 'v*.*.*'

permissions:
  contents: write
  pull-requests: write
  issues: write  # For post-release announcement

jobs:
  # Step 1: Pre-release validation with quality gates
  validate:
    name: Pre-release Validation
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          cache: 'pip'  # Cache pip dependencies

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -e ".[dev]"

      - name: Check version consistency
        run: |
          python3 scripts/check_version_consistency.py

      - name: Run tests
        run: |
          pytest test_claude_system.py -v --override-ini="addopts=" -p no:cov

      - name: Run security checks
        run: |
          pip install bandit safety
          bandit -r claude_force/ -ll || true
          safety check || true

      - name: Check code formatting
        run: |
          pip install black
          black --check claude_force/ || true

      - name: Verify package can be built
        run: |
          pip install build
          python -m build
          rm -rf dist/  # Clean up test build

  # Step 2: Build package
  build:
    name: Build Package
    needs: validate
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          cache: 'pip'

      - name: Install build tools
        run: |
          python -m pip install --upgrade pip
          pip install build twine

      - name: Build package
        run: |
          python -m build

      - name: Check package integrity
        run: |
          twine check --strict dist/*

      - name: Upload build artifacts
        uses: actions/upload-artifact@v4
        with:
          name: python-package-distributions
          path: dist/
          retention-days: 7

  # Step 3: Publish to PyPI
  publish-pypi:
    name: Publish to PyPI
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Download build artifacts
        uses: actions/download-artifact@v4
        with:
          name: python-package-distributions
          path: dist/

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Install twine
        run: pip install twine

      - name: Publish to PyPI with twine
        env:
          TWINE_USERNAME: __token__
          TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
        run: |
          python -m twine upload --non-interactive --skip-existing dist/*

  # Step 4: Generate and commit changelog
  changelog:
    name: Generate Changelog
    needs: publish-pypi
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: main  # Checkout main branch for changelog update

      - name: Fetch all tags
        run: |
          git fetch --force --tags

      - name: Extract version from tag
        id: version
        run: |
          VERSION=${GITHUB_REF#refs/tags/v}
          echo "version=${VERSION}" >> $GITHUB_OUTPUT

      - name: Install git-cliff
        run: |
          curl -LO https://github.com/orhun/git-cliff/releases/download/v2.4.0/git-cliff-2.4.0-x86_64-unknown-linux-gnu.tar.gz
          tar -xzf git-cliff-2.4.0-x86_64-unknown-linux-gnu.tar.gz
          sudo mv git-cliff-2.4.0/git-cliff /usr/local/bin/
          chmod +x /usr/local/bin/git-cliff

      - name: Generate changelog with git-cliff
        run: |
          git-cliff --config cliff.toml --latest --output CHANGELOG.md

      - name: Commit changelog
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add CHANGELOG.md
          if git diff --staged --quiet; then
            echo "No changes to CHANGELOG.md"
          else
            git commit -m "docs: update changelog for v${{ steps.version.outputs.version }}"
            git push origin main
          fi

      - name: Upload changelog artifact
        uses: actions/upload-artifact@v4
        with:
          name: changelog
          path: CHANGELOG.md
          retention-days: 7

  # Step 5: Create GitHub Release
  github-release:
    name: Create GitHub Release
    needs: [publish-pypi, changelog]
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Download build artifacts
        uses: actions/download-artifact@v4
        with:
          name: python-package-distributions
          path: dist/

      - name: Download changelog
        uses: actions/download-artifact@v4
        with:
          name: changelog
          path: .

      - name: Extract version
        id: version
        run: |
          VERSION=${GITHUB_REF#refs/tags/v}
          echo "version=${VERSION}" >> $GITHUB_OUTPUT
          echo "major=$(echo $VERSION | cut -d. -f1)" >> $GITHUB_OUTPUT
          echo "minor=$(echo $VERSION | cut -d. -f2)" >> $GITHUB_OUTPUT
          echo "patch=$(echo $VERSION | cut -d. -f3)" >> $GITHUB_OUTPUT

      - name: Extract latest changelog section
        id: changelog
        run: |
          # Extract the latest version section from CHANGELOG.md
          if [ -f CHANGELOG.md ]; then
            # Get content between first two version headers
            CHANGELOG_CONTENT=$(awk '/## \[/{if(++count==2) exit} count==1' CHANGELOG.md || echo "See CHANGELOG.md for details")
            # Save to file for use in release body
            echo "$CHANGELOG_CONTENT" > release_notes.md
            cat release_notes.md
          else
            echo "See commits for changes" > release_notes.md
          fi

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          files: dist/*
          draft: false
          prerelease: ${{ contains(github.ref, 'alpha') || contains(github.ref, 'beta') || contains(github.ref, 'rc') }}
          name: Release v${{ steps.version.outputs.version }}
          body_path: release_notes.md
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  # Step 6: Post-release tasks
  post-release:
    name: Post-release Tasks
    needs: github-release
    runs-on: ubuntu-latest
    if: success()
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Extract version
        id: version
        run: |
          VERSION=${GITHUB_REF#refs/tags/v}
          echo "version=${VERSION}" >> $GITHUB_OUTPUT

      - name: Create announcement issue
        uses: actions/github-script@v7
        with:
          script: |
            const version = '${{ steps.version.outputs.version }}';
            const tagName = 'v' + version;

            await github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: `📢 Released v${version}`,
              body: `🎉 **claude-force v${version}** has been released!\n\n` +
                    `## Installation\n\n` +
                    `\`\`\`bash\npip install claude-force==${version}\n\`\`\`\n\n` +
                    `## Links\n\n` +
                    `- 📦 [PyPI Package](https://pypi.org/project/claude-force/${version}/)\n` +
                    `- 📝 [Release Notes](https://github.com/${context.repo.owner}/${context.repo.repo}/releases/tag/${tagName})\n` +
                    `- 📚 [Documentation](https://github.com/${context.repo.owner}/${context.repo.repo}/blob/main/README.md)\n` +
                    `- 📋 [Changelog](https://github.com/${context.repo.owner}/${context.repo.repo}/blob/main/CHANGELOG.md)\n\n` +
                    `## Upgrade\n\n` +
                    `\`\`\`bash\npip install --upgrade claude-force\n\`\`\`\n\n` +
                    `Thank you for using claude-force! 🚀`,
              labels: ['release', 'announcement']
            });

      - name: Notify on successful release
        run: |
          echo "✅ Release v${{ steps.version.outputs.version }} completed successfully!"
          echo "📦 PyPI: https://pypi.org/project/claude-force/${{ steps.version.outputs.version }}/"
          echo "📝 GitHub: https://github.com/${{ github.repository }}/releases/tag/v${{ steps.version.outputs.version }}"
