name: Automated Release (Disabled)

# DISABLED: This workflow has never worked correctly due to self-triggering issues
# Use simple-release.yml instead for manual releases

on:
  workflow_dispatch:
    inputs:
      bump_version:
        description: 'Version bump type'
        required: true
        default: 'patch'
        type: choice
        options:
          - patch
          - minor
          - major

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1
  RUST_MIN_STACK: 8388608

defaults:
  run:
    shell: bash

jobs:
  # Phase 1: Test and determine if release is needed
  test-and-check:
    name: Test and Check
    runs-on: ubuntu-22.04
    outputs:
      should_release: ${{ steps.check.outputs.should_release }}
      current_version: ${{ steps.version.outputs.current_version }}
      new_version: ${{ steps.version.outputs.new_version }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}
      
      - name: Check if triggered by version bump
        id: check_skip
        run: |
          # Skip if this is a push event and the last commit is a version bump
          if [ "${{ github.event_name }}" = "push" ]; then
            LAST_COMMIT_MSG=$(git log -1 --pretty=%s)
            if echo "$LAST_COMMIT_MSG" | grep -q "^chore: bump version to\|^chore: release"; then
              echo "Skipping workflow - triggered by automated version bump"
              echo "skip=true" >> "$GITHUB_OUTPUT"
            else
              echo "skip=false" >> "$GITHUB_OUTPUT"
            fi
          else
            echo "skip=false" >> "$GITHUB_OUTPUT"
          fi
      
      
      - name: Install Rust
        if: steps.check_skip.outputs.skip != 'true'
        uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy
      
      - name: Install Deno
        if: steps.check_skip.outputs.skip != 'true'
        uses: denoland/setup-deno@v2
        with:
          deno-version: v2.x
      
      - name: Install cargo-llvm-cov
        if: steps.check_skip.outputs.skip != 'true'
        uses: taiki-e/install-action@cargo-llvm-cov
      
      - name: Install cargo-nextest
        if: steps.check_skip.outputs.skip != 'true'
        uses: taiki-e/install-action@cargo-nextest
      
      - name: Install shellcheck
        if: steps.check_skip.outputs.skip != 'true'
        run: |
          sudo apt-get update
          sudo apt-get install -y shellcheck
      
      - name: Run tests and checks
        if: steps.check_skip.outputs.skip != 'true'
        run: |
          make server-format server-lint server-check
          make test-fast  # Fast tests with nextest for better CI performance
      
      - name: Set default outputs when skipping
        if: steps.check_skip.outputs.skip == 'true'
        run: |
          echo "should_release=false" >> "$GITHUB_OUTPUT"
      
      - name: Check for release conditions
        id: check
        if: steps.check_skip.outputs.skip != 'true'
        run: |
          # Get current version from Cargo.toml
          CURRENT_VERSION=$(grep -m1 '^version = ' Cargo.toml | cut -d'"' -f2)
          
          # Check if a tag already exists for this version
          if git tag -l "v$CURRENT_VERSION" | grep -q .; then
            echo "Tag v$CURRENT_VERSION already exists, skipping release"
            echo "should_release=false" >> "$GITHUB_OUTPUT"
            exit 0
          fi
          
          # Get last tag
          LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
          
          # Check for changes since last tag
          if [ -z "$LAST_TAG" ]; then
            echo "No tags found, will create first release"
            echo "should_release=true" >> "$GITHUB_OUTPUT"
          else
            CHANGES=$(git log $LAST_TAG..HEAD --oneline | wc -l)
            if [ "$CHANGES" -gt 0 ] || [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
              echo "Found $CHANGES commits since $LAST_TAG"
              echo "should_release=true" >> "$GITHUB_OUTPUT"
            else
              echo "No changes since $LAST_TAG"
              echo "should_release=false" >> "$GITHUB_OUTPUT"
            fi
          fi
      
      - name: Determine version
        id: version
        if: steps.check.outputs.should_release == 'true'
        run: |
          # Get current version from Cargo.toml
          CURRENT_VERSION=$(grep -m1 '^version = ' Cargo.toml | cut -d'"' -f2)
          echo "current_version=$CURRENT_VERSION" >> "$GITHUB_OUTPUT"
          
          # Determine bump type
          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            BUMP_TYPE="${{ github.event.inputs.bump_version }}"
          else
            # Auto-detect bump type from commit messages
            if git log $LAST_TAG..HEAD --pretty=format:"%s" | grep -q "BREAKING CHANGE\|!:"; then
              BUMP_TYPE="major"
            elif git log $LAST_TAG..HEAD --pretty=format:"%s" | grep -q "feat:"; then
              BUMP_TYPE="minor"
            else
              BUMP_TYPE="patch"
            fi
          fi
          
          # Calculate new version
          IFS='.' read -r MAJOR MINOR PATCH <<< "$CURRENT_VERSION"
          case $BUMP_TYPE in
            major) MAJOR=$((MAJOR + 1)); MINOR=0; PATCH=0 ;;
            minor) MINOR=$((MINOR + 1)); PATCH=0 ;;
            patch) PATCH=$((PATCH + 1)) ;;
          esac
          NEW_VERSION="$MAJOR.$MINOR.$PATCH"
          echo "new_version=$NEW_VERSION" >> "$GITHUB_OUTPUT"

  # Phase 2: Update version and create tag BEFORE building binaries
  version-bump:
    name: Version Bump
    needs: test-and-check
    if: needs.test-and-check.outputs.should_release == 'true'
    runs-on: ubuntu-22.04
    outputs:
      tag_name: ${{ steps.tag.outputs.tag_name }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}
          
      - name: Install Deno
        uses: denoland/setup-deno@v2
        with:
          deno-version: v2.x
          
      - name: Update version in files
        run: |
          NEW_VERSION="${{ needs.test-and-check.outputs.new_version }}"
          deno run --allow-read --allow-write --allow-run ./scripts/update-version.ts "$NEW_VERSION"
          
      - name: Commit version updates and create tag
        id: tag
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          
          git add Cargo.toml server/Cargo.toml installer-macro/Cargo.toml assets/project-state.json
          git add -f Cargo.lock
          
          git commit -m "chore: bump version to ${{ needs.test-and-check.outputs.new_version }}"
          git push origin HEAD:master
          
          # Create and push tag
          TAG_NAME="v${{ needs.test-and-check.outputs.new_version }}"
          git tag -a "$TAG_NAME" -m "Release $TAG_NAME"
          git push origin "$TAG_NAME"
          echo "tag_name=$TAG_NAME" >> "$GITHUB_OUTPUT"

  # Phase 3: Build binaries from the tagged version
  build-binaries:
    name: Build ${{ matrix.target }}
    needs: version-bump
    if: needs.test-and-check.outputs.should_release == 'true'
    strategy:
      matrix:
        include:
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-22.04
          - target: aarch64-unknown-linux-gnu
            os: ubuntu-22.04
          - target: x86_64-apple-darwin
            os: macos-latest
          - target: aarch64-apple-darwin
            os: macos-latest
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ needs.version-bump.outputs.tag_name }}
      
      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}
      
      - name: Install cross-compilation tools
        if: matrix.target == 'aarch64-unknown-linux-gnu'
        run: |
          sudo apt-get update
          sudo apt-get install -y gcc-aarch64-linux-gnu
      
      - name: Build binary
        run: |
          if [ "${{ matrix.target }}" = "aarch64-unknown-linux-gnu" ]; then
            export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc
          fi
          cargo build --release --target ${{ matrix.target }} --manifest-path server/Cargo.toml
      
      - name: Verify binary version
        run: |
          # Check if binary version matches what we expect
          BINARY_PATH="target/${{ matrix.target }}/release/pmat"
          if [ -x "$BINARY_PATH" ]; then
            BINARY_VERSION=$("$BINARY_PATH" --version | cut -d' ' -f2)
            EXPECTED_VERSION=$(grep -m1 '^version = ' server/Cargo.toml | cut -d'"' -f2)
            echo "Binary version: $BINARY_VERSION"
            echo "Expected version: $EXPECTED_VERSION"
            if [ "$BINARY_VERSION" != "$EXPECTED_VERSION" ]; then
              echo "WARNING: Binary version mismatch! Binary has $BINARY_VERSION but Cargo.toml has $EXPECTED_VERSION"
              echo "This indicates the release process has a critical bug."
              # Don't fail for now, just warn
            fi
          fi
      
      - name: Create archive
        run: |
          cd target/${{ matrix.target }}/release
          tar -czf pmat-${{ matrix.target }}.tar.gz pmat
          
          # Use sha256sum on Linux, shasum on macOS
          if command -v sha256sum >/dev/null 2>&1; then
            sha256sum pmat-${{ matrix.target }}.tar.gz > pmat-${{ matrix.target }}.tar.gz.sha256
          else
            shasum -a 256 pmat-${{ matrix.target }}.tar.gz > pmat-${{ matrix.target }}.tar.gz.sha256
          fi
      
      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: binary-${{ matrix.target }}
          path: |
            target/${{ matrix.target }}/release/pmat-${{ matrix.target }}.tar.gz
            target/${{ matrix.target }}/release/pmat-${{ matrix.target }}.tar.gz.sha256

  # Create GitHub release
  create-release:
    name: Create Release
    needs: [test-and-check, build-binaries]
    if: needs.test-and-check.outputs.should_release == 'true'
    runs-on: ubuntu-22.04
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}
      
      - name: Install Deno
        uses: denoland/setup-deno@v2
        with:
          deno-version: v2.x
      
      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
      
      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts
      
      - name: Prepare release files
        run: |
          mkdir release-files
          find artifacts -name "*.tar.gz*" -exec cp {} release-files/ \;
          ls -la release-files/
      
      - name: Copy installer script
        run: |
          cp scripts/install.sh release-files/
      
      - name: Generate changelog
        id: changelog
        run: |
          # Get commit messages since last tag
          LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
          if [ -z "$LAST_TAG" ]; then
            COMMITS=$(git log --pretty=format:"- %s" | head -20)
          else
            COMMITS=$(git log $LAST_TAG..HEAD --pretty=format:"- %s")
          fi
          
          # Create changelog
          cat > CHANGELOG.md << EOF
          ## What's Changed
          
          $COMMITS
          
          ## Installation
          
          ### Using curl (recommended)
          \`\`\`bash
          curl -sSfL https://raw.githubusercontent.com/paiml/paiml-mcp-agent-toolkit/v${{ needs.test-and-check.outputs.new_version }}/scripts/install.sh | sh
          \`\`\`
          
          ### Manual installation
          Download the appropriate binary for your platform from the assets below.
          
          **Full Changelog**: https://github.com/paiml/paiml-mcp-agent-toolkit/compare/$LAST_TAG...v${{ needs.test-and-check.outputs.new_version }}
          EOF
          
          echo "changelog<<EOF" >> "$GITHUB_OUTPUT"
          cat CHANGELOG.md >> "$GITHUB_OUTPUT"
          echo "EOF" >> "$GITHUB_OUTPUT"
      
      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: v${{ needs.test-and-check.outputs.new_version }}
          name: v${{ needs.test-and-check.outputs.new_version }}
          body: ${{ steps.changelog.outputs.changelog }}
          draft: false
          prerelease: false
          files: release-files/*
          token: ${{ secrets.GITHUB_TOKEN }}

  # Update installer script in main branch
  update-installer:
    name: Update Installer Script
    needs: create-release
    runs-on: ubuntu-22.04
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
        with:
          ref: master
          token: ${{ secrets.GITHUB_TOKEN }}
      
      - name: Install Deno
        uses: denoland/setup-deno@v2
        with:
          deno-version: v2.x
      
      - name: Pull latest changes
        run: git pull
      
      - name: Verify installer works
        run: |
          # Test the installer script
          bash scripts/install.sh --help || true
          
      - name: Create PR if installer needs updates
        run: |
          # Check if installer references the correct URLs
          if ! grep -q "paiml/paiml-mcp-agent-toolkit" scripts/install.sh; then
            echo "Installer script needs updating"
            # Create a branch and PR for manual review
            git checkout -b update-installer-urls
            # ... make changes ...
            git push origin update-installer-urls
            gh pr create --title "Update installer URLs" --body "Automated update of installer script URLs"
          fi
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}