name: Run CultRoll scraper target

on:
  workflow_dispatch:
    inputs:
      target:
        description: Source target ID or pipeline adapter ID
        required: true
        default: grand-cinemas-lb
      kind:
        description: Whether to run a source target or pipeline adapter
        required: true
        type: choice
        options:
          - source
          - pipeline
        default: source
      sync:
        description: Run inline instead of enqueueing
        required: true
        type: boolean
        default: true
      payload:
        description: JSON body to send with the trigger request
        required: false
        default: "{}"

permissions:
  contents: read

jobs:
  trigger:
    runs-on: ubuntu-latest
    env:
      CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
      CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
      SCRAPER_ADMIN_TOKEN: ${{ secrets.SCRAPER_ADMIN_TOKEN }}
    steps:
      - name: Validate inputs and secrets
        env:
          TARGET: ${{ inputs.target }}
          KIND: ${{ inputs.kind }}
          PAYLOAD: ${{ inputs.payload }}
        run: |
          set -euo pipefail
          for var in CLOUDFLARE_API_TOKEN CLOUDFLARE_ACCOUNT_ID SCRAPER_ADMIN_TOKEN TARGET KIND PAYLOAD; do
            if [ -z "${!var:-}" ]; then
              echo "::error::${var} is required"
              exit 1
            fi
          done
          echo "$PAYLOAD" | jq -e . >/dev/null

      - name: Resolve scraper worker URL
        run: |
          set -euo pipefail
          ACCOUNT_SUBDOMAIN=$(curl -fsS \
            "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/workers/subdomain" \
            -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" | jq -r '.result.subdomain // empty')
          if [ -n "$ACCOUNT_SUBDOMAIN" ]; then
            echo "SCRAPER_URL=https://cultroll-scraper.${ACCOUNT_SUBDOMAIN}.workers.dev" >> "$GITHUB_ENV"
          else
            echo "SCRAPER_URL=https://cultroll-scraper.workers.dev" >> "$GITHUB_ENV"
          fi

      - name: Trigger scraper target
        env:
          TARGET: ${{ inputs.target }}
          KIND: ${{ inputs.kind }}
          SYNC: ${{ inputs.sync }}
          PAYLOAD: ${{ inputs.payload }}
        run: |
          set -euo pipefail
          encoded_target=$(jq -rn --arg value "$TARGET" '$value | @uri')
          encoded_kind=$(jq -rn --arg value "$KIND" '$value | @uri')
          request_url="${SCRAPER_URL}/run?target=${encoded_target}&kind=${encoded_kind}"
          if [ "$SYNC" = "true" ] || [ "$SYNC" = "1" ]; then
            request_url="${request_url}&sync=1"
          fi

          tmpdir="${TMPDIR:-${RUNNER_TEMP:-$HOME/.tmp}}"
          mkdir -p "$tmpdir"
          response_path="$tmpdir/cultroll-trigger-response.json"

          echo "POST ${request_url}"
          curl -fsS \
            -X POST "${request_url}" \
            -H "Authorization: Bearer ${SCRAPER_ADMIN_TOKEN}" \
            -H "Content-Type: application/json" \
            -d "$PAYLOAD" \
            > "$response_path"

          jq . "$response_path"

      - name: Snapshot Beirut Grand coverage
        if: ${{ inputs.target == 'grand-cinemas-lb' && inputs.kind == 'source' }}
        run: |
          set -euo pipefail
          for base_url in https://cultroll.com https://cultroll-web.pages.dev; do
            echo "=== ${base_url} ==="
            curl -fsS "${base_url}/api/showtimes?city=beirut&limit=500" | jq '{
              total: .total,
              grand_count: ([.showtimes[] | select(.cinema_id | startswith("grand-"))] | length),
              grand_cinemas: ([.showtimes[] | select(.cinema_id | startswith("grand-")) | .cinema_name_en] | unique)
            }'
          done
