name: Release

on:
  push:
    tags:
      - 'v*'  # Trigger on version tags (v1.0.0, v2.1.3, etc.)
  workflow_dispatch:
    inputs:
      version:
        description: 'Version to release (e.g., 1.2.3)'
        required: true
        type: string

permissions:
  contents: write
  packages: write

jobs:
  validate-version:
    name: Validate Version
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.version.outputs.version }}
    steps:
      - uses: actions/checkout@v4

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

      - name: Extract version
        id: version
        run: |
          if [[ "${{ github.event_name }}" == "push" ]]; then
            # Extract version from tag
            VERSION=${GITHUB_REF#refs/tags/v}
          else
            # Use manually provided version
            VERSION="${{ github.event.inputs.version }}"
          fi
          echo "version=${VERSION}" >> $GITHUB_OUTPUT
          echo "Version: ${VERSION}"

      - name: Validate version format
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          if ! [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            echo "Error: Invalid version format: $VERSION"
            echo "Expected format: X.Y.Z (e.g., 1.2.3)"
            exit 1
          fi

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

  build:
    name: Build Distribution
    needs: validate-version
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Install build dependencies
        run: |
          python -m pip install --upgrade pip
          pip install build wheel setuptools

      - name: Build package
        run: |
          python -m build
          ls -la dist/

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: dist
          path: dist/

  test:
    name: Test Package
    needs: build
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
        python-version: ['3.10', '3.11', '3.12']
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}

      - name: Download artifacts
        uses: actions/download-artifact@v4
        with:
          name: dist
          path: dist/

      - name: Install package
        run: |
          pip install dist/*.whl

      - name: Test import
        run: |
          python -c "import mcp_browser; print(f'Version: {mcp_browser.__version__}')"

      - name: Test CLI
        run: |
          mcp-browser --help

  release:
    name: Create GitHub Release
    needs: [validate-version, build, test]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Download artifacts
        uses: actions/download-artifact@v4
        with:
          name: dist
          path: dist/

      - name: Extract changelog
        id: changelog
        run: |
          VERSION="${{ needs.validate-version.outputs.version }}"

          # Try to extract changelog for this version
          if [ -f "CHANGELOG.md" ]; then
            # Extract section for this version
            awk "/## \[${VERSION}\]/{flag=1; next} /^## \[/{flag=0} flag" CHANGELOG.md > release_notes.md

            if [ -s release_notes.md ]; then
              echo "Found changelog for version ${VERSION}"
            else
              echo "No specific changelog found for ${VERSION}, using default"
              echo "Release ${VERSION}" > release_notes.md
            fi
          else
            echo "Release ${VERSION}" > release_notes.md
          fi

          echo "RELEASE_NOTES<<EOF" >> $GITHUB_OUTPUT
          cat release_notes.md >> $GITHUB_OUTPUT
          echo "EOF" >> $GITHUB_OUTPUT

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: v${{ needs.validate-version.outputs.version }}
          name: Release v${{ needs.validate-version.outputs.version }}
          body: ${{ steps.changelog.outputs.RELEASE_NOTES }}
          files: dist/*
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  publish-pypi:
    name: Publish to PyPI
    needs: [release]
    runs-on: ubuntu-latest
    environment:
      name: pypi
      url: https://pypi.org/project/mcp-browser/
    steps:
      - uses: actions/checkout@v4

      - name: Download artifacts
        uses: actions/download-artifact@v4
        with:
          name: dist
          path: dist/

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          password: ${{ secrets.PYPI_API_TOKEN }}
          skip-existing: true

  publish-test-pypi:
    name: Publish to Test PyPI
    needs: [build, test]
    runs-on: ubuntu-latest
    if: github.event_name == 'workflow_dispatch'
    environment:
      name: test-pypi
      url: https://test.pypi.org/project/mcp-browser/
    steps:
      - uses: actions/checkout@v4

      - name: Download artifacts
        uses: actions/download-artifact@v4
        with:
          name: dist
          path: dist/

      - name: Publish to Test PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          password: ${{ secrets.TEST_PYPI_API_TOKEN }}
          repository-url: https://test.pypi.org/legacy/
          skip-existing: true

  docker:
    name: Build and Push Docker Image
    needs: [validate-version, test]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: |
            ${{ secrets.DOCKER_USERNAME }}/mcp-browser:${{ needs.validate-version.outputs.version }}
            ${{ secrets.DOCKER_USERNAME }}/mcp-browser:latest
            ghcr.io/${{ github.repository }}:${{ needs.validate-version.outputs.version }}
            ghcr.io/${{ github.repository }}:latest
          cache-from: type=gha
          cache-to: type=gha,mode=max