name: Deploy and verify

# Public copy: https://proxyhawk.io/guard-ci/workflows/deploy.yml
# Docs: https://proxyhawk.io/docs/guard-ci-onboarding.html
#
# Canonical deploy reusable workflow. Exposes deployed_sha for guard-check jobs.
# deploy-wait.yml remains as a backward-compatible alias.

on:
  workflow_call:
    inputs:
      platform:
        description: "render | railway | deploy-hook | verify-only"
        required: true
        type: string
      expected_sha:
        description: Git commit SHA expected to be live
        required: true
        type: string
      api_url:
        description: Base URL of deployed API
        required: true
        type: string
      health_path:
        description: Health check path
        required: false
        type: string
        default: "/api/health"
      environment_label:
        description: staging | production
        required: false
        type: string
        default: ""
      railway_service:
        description: Railway service name
        required: false
        type: string
        default: ""
      skip_health_wait:
        description: "Skip polling health (trust deploy trigger only)"
        required: false
        type: boolean
        default: false
    secrets:
      DEPLOY_HOOK:
        required: false
      DEPLOY_API_KEY:
        required: false
      RAILWAY_TOKEN:
        required: false
    outputs:
      deployed_sha:
        description: "Commit SHA verified live (or expected_sha when verify-only / skip wait)"
        value: ${{ jobs.deploy-and-verify.outputs.deployed_sha }}

jobs:
  deploy-and-verify:
    runs-on: ubuntu-latest
    outputs:
      deployed_sha: ${{ steps.set_sha.outputs.deployed_sha }}
    steps:
      - uses: actions/checkout@v4

      - name: Deploy to Railway
        if: inputs.platform == 'railway'
        uses: bervProject/railway-deploy@main
        with:
          railway_token: ${{ secrets.RAILWAY_TOKEN }}
          service: ${{ inputs.railway_service }}

      - name: Trigger deploy (render / deploy-hook)
        if: inputs.platform == 'render' || inputs.platform == 'deploy-hook' || inputs.platform == 'webhook'
        env:
          DEPLOY_HOOK: ${{ secrets.DEPLOY_HOOK }}
          EXPECTED_SHA: ${{ inputs.expected_sha }}
        run: |
          if [ -z "$DEPLOY_HOOK" ]; then
            echo "DEPLOY_HOOK is required for render/deploy-hook"
            exit 1
          fi
          curl -fsSL -X POST "${DEPLOY_HOOK}&ref=${EXPECTED_SHA}" || \
          curl -fsSL -X POST -H "Content-Type: application/json" \
            -d "{\"ref\":\"${EXPECTED_SHA}\"}" "${DEPLOY_HOOK}"

      - name: Wait for live SHA
        if: inputs.skip_health_wait != true && inputs.platform != 'verify-only'
        env:
          API_URL: ${{ inputs.api_url }}
          EXPECTED_SHA: ${{ inputs.expected_sha }}
          HEALTH_PATH: ${{ inputs.health_path }}
        run: |
          API_URL="${API_URL%/}"
          if [ -z "$API_URL" ]; then
            echo "::error::API URL is empty."
            echo "Set STAGING_API_URL (or PRODUCTION_API_URL) as a GitHub Actions Variable:"
            echo "  Repo → Settings → Secrets and variables → Actions → Variables"
            exit 1
          fi
          echo "Polling ${API_URL}${HEALTH_PATH} for gitSha=${EXPECTED_SHA}"
          for i in $(seq 1 90); do
            body="$(curl -fsSL "${API_URL}${HEALTH_PATH}" 2>/dev/null || true)"
            if [ -z "$body" ]; then
              echo "Attempt ${i}/90: health check unreachable, retrying..."
              sleep 5
              continue
            fi
            sha="$(echo "$body" | python3 -c 'import sys,json; print(json.load(sys.stdin).get("gitSha",""))' 2>/dev/null || true)"
            if [ "$sha" = "$EXPECTED_SHA" ]; then
              echo "Live commit verified: $sha"
              exit 0
            fi
            echo "Attempt ${i}/90: live gitSha=${sha:-unknown}, waiting..."
            sleep 5
          done
          echo "Timed out waiting for live gitSha=${EXPECTED_SHA} at ${API_URL}${HEALTH_PATH}"
          echo "Ensure GET ${HEALTH_PATH} returns JSON with gitSha matching the deployed commit."
          exit 1

      - name: Set deployed SHA output
        id: set_sha
        run: echo "deployed_sha=${{ inputs.expected_sha }}" >> "$GITHUB_OUTPUT"
