name: Release (PyPI & Docker)
on:
  workflow_dispatch:
    inputs:
      version:
        type: choice
        required: true
        description: "Version bump type for PyPI package & Git tag"
        options:
          - patch
          - minor
          - major
      skip_security_checks:
        type: boolean
        required: false
        description: "Skip security checks"
        default: false
      skip_rc_check:
        type: boolean
        required: false
        description: "Skip RC verification (emergency releases only)"
        default: false

permissions:
  id-token: write
  checks: write
  contents: write
  packages: write
  pull-requests: read

jobs:
  # Verify the current version has passed RC testing
  verify-rc:
    name: Verify RC Status
    if: ${{ github.event.inputs.skip_rc_check != 'true' }}
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5.0.1
        with:
          fetch-depth: 0 # Need enough history to find last non-skip-ci commit

      - name: Find Last RC-Tested Commit
        id: find-commit
        run: |
          echo "Finding the last commit that triggered RC tests..."

          # Find the most recent commit without [skip ci] or [ci skip]
          COMMIT_SHA=$(git log --invert-grep --grep='\[skip ci\]' --grep='\[ci skip\]' -i -1 --format='%H')

          if [ -z "$COMMIT_SHA" ]; then
            echo "::error::Could not find a non-skip-ci commit"
            exit 1
          fi

          echo "Found RC-tested commit: $COMMIT_SHA"
          echo "  Message: $(git log -1 --format='%s' $COMMIT_SHA)"
          echo "commit_sha=$COMMIT_SHA" >> $GITHUB_OUTPUT

      - name: Configure AWS Credentials
        uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.3.1
        with:
          aws-access-key-id: ${{ secrets.MANIFEST_READ_ONLY_AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.MANIFEST_READ_ONLY_AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ secrets.AWS_DEFAULT_REGION }}

      - name: Get RC SHA from DynamoDB
        id: get-rc-sha
        uses: SolaceDev/solace-public-workflows/.github/actions/cicd-helper@main
        with:
          rc_step: get_item_value_from_dynamodb
          ddb_query_json: '{"squad": "ai", "repository": "solace-agent-mesh"}'
          ddb_table_name: solace-cloud-manifest
          ddb_partition_key: squad
          ddb_field_path: rc.sha
          ddb_output_name: RC_SHA

      - name: Verify RC SHA
        run: |
          EXPECTED_SHA="${{ steps.find-commit.outputs.commit_sha }}"
          RC_SHA="${{ steps.get-rc-sha.outputs.RC_SHA }}"

          echo "Expected SHA (last RC-tested commit): $EXPECTED_SHA"
          echo "RC SHA from DynamoDB: $RC_SHA"

          if [ "$RC_SHA" = "NOT_FOUND" ] || [ "$RC_SHA" = "FIELD_NOT_FOUND" ]; then
            echo "::error::No RC entry found in DynamoDB for solace-agent-mesh"
            echo "Please run the RC pipeline first by pushing to main."
            exit 1
          fi

          if [ "$RC_SHA" != "$EXPECTED_SHA" ]; then
            echo "::error::RC SHA mismatch!"
            echo "  Expected: $EXPECTED_SHA"
            echo "  Found in DynamoDB: $RC_SHA"
            echo ""
            echo "The commit that passed RC testing does not match the expected release commit."
            echo "This could mean new commits were added without running RC tests."
            exit 1
          fi

          echo "✅ RC verification passed - SHA matches: $RC_SHA"

  # Run security checks first via reusable workflow (conditionally)
  security-checks:
    needs: verify-rc
    if: |
      always() &&
      (needs.verify-rc.result == 'success' || needs.verify-rc.result == 'skipped') &&
      github.event.inputs.skip_security_checks != 'true'
    uses: SolaceDev/solace-public-workflows/.github/workflows/hatch_release_security_checks.yml@main
    with:
      whitesource_project_name: "solace-agent-mesh"
      whitesource_product_name: "solaceai"
      prisma_check: true
      sonarqube_hotspot_check: true
      fossa_check: true
    secrets:
      PRISMA_DOCKER_IMAGE_TO_CHECK: ${{ secrets.DOCKER_IMAGE_TO_CHECK }}
      PRISMA_ACCESS_KEY: ${{ secrets.PRISMA_ACCESS_KEY_ID }}
      PRISMA_ACCESS_KEY_SECRET: ${{ secrets.PRISMA_SECRET_ACCESS_KEY }}
      FOSSA_API_KEY: ${{ secrets.FOSSA_API_KEY }}
      SONARQUBE_PROJECT_KEY: ${{ secrets.SONARQUBE_PROJECT_KEY }}
      SONARQUBE_PROJECT_MAIN_BRANCH: "main"
      SONARQUBE_QUERY_TOKEN: ${{ secrets.SONARQUBE_TOKEN }}
      SONARQUBE_HOTSPOTS_API_URL: ${{ secrets.SONARQUBE_HOTSPOTS_API_URL }}
      WHITESOURCE_API_KEY: ${{ secrets.WHITESOURCE_API_KEY }}
      MANIFEST_AWS_ACCESS_KEY_ID: ${{ secrets.MANIFEST_READ_ONLY_AWS_ACCESS_KEY_ID }}
      MANIFEST_AWS_SECRET_ACCESS_KEY: ${{ secrets.MANIFEST_READ_ONLY_AWS_SECRET_ACCESS_KEY }}
      MANIFEST_AWS_REGION: ${{ secrets.AWS_DEFAULT_REGION }}

  # Release to PyPI using Trusted Publishing
  release:
    name: Release to PyPI
    # We need always() here because when security-checks or verify-rc is skipped,
    # GitHub Actions would by default skip ALL dependent jobs. The always() forces evaluation of our
    # condition, allowing the release to proceed when checks were either successful OR skipped.
    # This enables emergency releases when checks need to be bypassed.
    needs: [verify-rc, security-checks]
    if: |
      always() && 
      (needs.verify-rc.result == 'success' || needs.verify-rc.result == 'skipped') &&
      (needs.security-checks.result == 'success' || needs.security-checks.result == 'skipped')
    runs-on: ubuntu-latest
    timeout-minutes: 20
    environment: pypi
    outputs:
      new_version: ${{ steps.prep.outputs.new_version }}
      commit_hash: ${{ steps.prep.outputs.commit_hash }}
    steps:
      - name: Checkout
        uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5.0.1
        with:
          fetch-depth: 0
          ssh-key: ${{ secrets.COMMIT_KEY }}

      - name: Setup Node.js
        uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
        with:
          node-version: "20"
          cache: "npm"
          cache-dependency-path: client/webui/frontend/package-lock.json

      - name: Install and Build Frontend
        run: |
          cd client/webui/frontend
          npm ci
          npm run build

      - name: Prepare Release
        id: prep
        uses: SolaceDev/solace-public-workflows/.github/actions/hatch-release-prep@main
        with:
          version: ${{ github.event.inputs.version }}

      # Publish using Trusted Publishing - must be directly in workflow, not in composite action
      # See: https://docs.pypi.org/trusted-publishers/using-a-publisher/
      - name: Publish package distributions to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          verbose: true

      - name: Finalize Release
        uses: SolaceDev/solace-public-workflows/.github/actions/hatch-release-post@main
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          new_version: ${{ steps.prep.outputs.new_version }}
          current_version: ${{ steps.prep.outputs.current_version }}
          skip_bump: ${{ steps.prep.outputs.skip_bump }}

  build_and_push_docker:
    name: Build and Push to DockerHub
    needs: release
    uses: SolaceLabs/solace-agent-mesh/.github/workflows/build-push-dockerhub.yml@main
    with:
      version: ${{ needs.release.outputs.new_version }}
      commit_hash: ${{ needs.release.outputs.commit_hash }}
      push_latest: true
    secrets:
      DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
      DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
      SAM_AWS_ACCESS_KEY_ID: ${{ secrets.SAM_AWS_ACCESS_KEY_ID }}
      SAM_AWS_SECRET_ACCESS_KEY: ${{ secrets.SAM_AWS_SECRET_ACCESS_KEY }}
      AWS_DEFAULT_REGION: ${{ secrets.AWS_DEFAULT_REGION }}
      SAM_AWS_ECR_REGISTRY: ${{ secrets.SAM_AWS_ECR_REGISTRY }}
