name: chappe-codex
on:
  repository_dispatch:
    types: [chappe_event]

permissions:
  contents: write
  pull-requests: write

concurrency:
  group: chappe-${{ github.event.client_payload.event.branch }}
  cancel-in-progress: false

jobs:
  migrate:
    if: >-
      github.event.client_payload.event.recommended_actions[0].type == 'open_draft_pr' &&
      github.event.client_payload.event.recommended_actions[0].suggested_mode == 'auto' &&
      github.event.client_payload.event.project.relevance == 'affected'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5

      - name: Save event for Codex
        env:
          EVENT_JSON: ${{ toJSON(github.event.client_payload.event) }}
        run: |
          mkdir -p .chappe
          printf '%s' "$EVENT_JSON" > .chappe/event.json

      - name: Run Codex
        uses: openai/codex-action@v1
        with:
          openai-api-key: ${{ secrets.OPENAI_API_KEY }}
          prompt-file: .github/codex/chappe-migrate.md
          permission-profile: ":workspace"

      - name: Collect result for Chappe
        id: result
        if: always()
        run: |
          # What Codex wrote to .chappe/result.json, keeping only known values; file and line counts come from git,
          # not from the agent. New files count once marked with --intent-to-add.
          R='{}'
          if [ -f .chappe/result.json ]; then
            R=$(jq -c 'if type == "object" then . else {} end' .chappe/result.json 2>/dev/null || echo '{}')
          fi
          git add -A --intent-to-add -- . ':(exclude).chappe'
          read -r FILES LINES < <(git diff HEAD --numstat -- . ':(exclude).chappe' \
            | awk '{f++; if ($1 != "-") l += $1 + $2} END {print f + 0, l + 0}')
          git reset -q
          DETAILS=$(jq -cn --argjson r "$R" --argjson f "$FILES" --argjson l "$LINES" '
            ["step_unclear", "step_wrong", "extra_change_needed", "not_applicable",
             "tests_failed", "build_failed", "agent_error", "other"] as $known
            | {agent: "codex", files_changed: ([$f, 10000] | min), lines_changed: ([$l, 1000000] | min)}
            + (if ($r.tests | type) == "string" and ($r.tests | IN("passed", "failed", "not_run"))
               then {tests: $r.tests} else {} end)
            + {issues: ([($r.issues | if type == "array" then .[] else empty end)
                         | select(type == "string" and IN($known[]))] | unique | .[:5])}
            + (if ($r.note | type) == "string" and ($r.note | length) > 0 then {note: $r.note[:500]} else {} end)')
          echo "details=$DETAILS" >> "$GITHUB_OUTPUT"

      - name: Remove event file
        run: rm -rf .chappe

      - name: Open or update draft PR
        id: cpr
        uses: peter-evans/create-pull-request@v7
        with:
          branch: ${{ github.event.client_payload.event.branch }}
          draft: true
          labels: chappe
          commit-message: "chappe: ${{ github.event.client_payload.event.track.title }}"
          title: "${{ github.event.client_payload.event.synthetic && '[Chappe TEST]' || '[Chappe]' }} ${{ github.event.client_payload.event.track.title }}"
          body: |
            Chappe track: `${{ github.event.client_payload.event.track_id }}` (state_version ${{ github.event.client_payload.event.state_version }})
            Deadline: ${{ github.event.client_payload.event.track.deadline.at || 'not announced' }}
            Evidence: ${{ github.event.client_payload.event.track.evidence[0].url }}

            Generated by Codex from a Chappe event. Review before merging.

      - name: Report to Chappe
        if: always()
        env:
          CHAPPE_API_URL: ${{ vars.CHAPPE_API_URL }}
          CHAPPE_API_KEY: ${{ secrets.CHAPPE_API_KEY }}
          PROJECT_ID: ${{ github.event.client_payload.event.project.id }}
          TRACK_ID: ${{ github.event.client_payload.event.track_id }}
          STATE_VERSION: ${{ github.event.client_payload.event.state_version }}
          PR_URL: ${{ steps.cpr.outputs.pull-request-url }}
          PR_OP: ${{ steps.cpr.outputs.pull-request-operation }}
          JOB_STATUS: ${{ job.status }}
          DETAILS: ${{ steps.result.outputs.details }}
        run: |
          DETAILS=${DETAILS:-'{"agent": "codex"}'}
          if [ "$PR_OP" = "created" ]; then ACTION=pr_opened; RESULT=done
          elif [ "$PR_OP" = "updated" ]; then ACTION=pr_updated; RESULT=done
          elif [ "$JOB_STATUS" = "failure" ]; then ACTION=agent_run; RESULT=failed
          else ACTION=agent_run; RESULT=skipped; fi
          jq -n --arg p "$PROJECT_ID" --arg t "$TRACK_ID" --argjson v "$STATE_VERSION" \
                --arg a "$ACTION" --arg r "$RESULT" --arg u "$PR_URL" --argjson d "$DETAILS" \
            '{project_id: $p, track_id: $t, state_version: $v, action: $a, result: $r,
              url: (if $u == "" then null else $u end), details: $d}' \
          | curl -sS -X POST "$CHAPPE_API_URL/v1/reports" \
              -H "Authorization: Bearer $CHAPPE_API_KEY" -H "content-type: application/json" -d @-

  close-on-retraction:
    if: github.event.client_payload.event.recommended_actions[0].type == 'close_pr'
    runs-on: ubuntu-latest
    steps:
      - name: Close the PR for this track
        env:
          GH_TOKEN: ${{ github.token }}
          BRANCH: ${{ github.event.client_payload.event.branch }}
          REPO: ${{ github.repository }}
        run: |
          gh pr close "$BRANCH" --repo "$REPO" --delete-branch \
            --comment "Chappe: the vendor retracted this change, closing this PR." || echo "no open PR for $BRANCH"
