name: chappe-pr-report
# Report the opening, merging and closing of Chappe PRs back to Chappe, to measure "event -> PR -> merge".
# Works for both paths: it only looks at the PR title prefix [Chappe and the first description line "Chappe track: `...` (state_version N)".
# details: the PR's changed files and added plus deleted lines; when the PR opens, also the agent, tests and issues of the
# "Chappe result: agent=... tests=... issues=..." line the Claude routine writes, keeping only known values.
# Note: PRs opened with GITHUB_TOKEN (the Codex path) do not trigger the opened event, so chappe-codex.yml reports that step itself; merges and closes are done by people and do trigger it.
on:
  pull_request:
    types: [opened, closed]

permissions:
  contents: read

jobs:
  report:
    if: startsWith(github.event.pull_request.title, '[Chappe')
    runs-on: ubuntu-latest
    steps:
      - name: Report PR status to Chappe
        env:
          CHAPPE_API_URL: ${{ vars.CHAPPE_API_URL }}
          CHAPPE_API_KEY: ${{ secrets.CHAPPE_API_KEY }}
          PROJECT_ID: ${{ vars.CHAPPE_PROJECT_ID }}
          PR_BODY: ${{ github.event.pull_request.body }}
          PR_URL: ${{ github.event.pull_request.html_url }}
          EVENT_ACTION: ${{ github.event.action }}
          MERGED: ${{ github.event.pull_request.merged }}
          CHANGED_FILES: ${{ github.event.pull_request.changed_files }}
          ADDITIONS: ${{ github.event.pull_request.additions }}
          DELETIONS: ${{ github.event.pull_request.deletions }}
        run: |
          LINE=$(printf '%s\n' "$PR_BODY" | grep -m1 -o 'Chappe track: `[^`]*` (state_version [0-9]*)' || true)
          if [ -z "$LINE" ]; then echo "no Chappe track line in PR body"; exit 0; fi
          TRACK_ID=$(printf '%s' "$LINE" | sed -E 's/^Chappe track: `([^`]*)`.*/\1/')
          STATE_VERSION=$(printf '%s' "$LINE" | sed -E 's/.*state_version ([0-9]+)\).*/\1/')
          if [ "$EVENT_ACTION" = "opened" ]; then ACTION=pr_opened
          elif [ "$MERGED" = "true" ]; then ACTION=pr_merged
          else ACTION=pr_closed_unmerged; fi
          RESULT_LINE=""
          if [ "$EVENT_ACTION" = "opened" ]; then
            RESULT_LINE=$(printf '%s\n' "$PR_BODY" | tr -d '\r' | grep -m1 '^Chappe result:' || true)
          fi
          DETAILS=$(jq -cn --arg line "$RESULT_LINE" --argjson f "${CHANGED_FILES:-0}" \
                           --argjson l "$(( ${ADDITIONS:-0} + ${DELETIONS:-0} ))" '
            ["step_unclear", "step_wrong", "extra_change_needed", "not_applicable",
             "tests_failed", "build_failed", "agent_error", "other"] as $known
            | ($line | [scan("([a-z_]+)=([^ ]*)") | {key: .[0], value: .[1]}] | from_entries) as $kv
            | {files_changed: ([$f, 10000] | min), lines_changed: ([$l, 1000000] | min)}
            + (if ($kv.agent // "" | IN("claude_code", "codex", "other")) then {agent: $kv.agent} else {} end)
            + (if ($kv.tests // "" | IN("passed", "failed", "not_run")) then {tests: $kv.tests} else {} end)
            + (if $line == "" then {} else
                 {issues: ([($kv.issues // "") | split(",")[] | select(IN($known[]))] | unique | .[:5])} end)')
          jq -n --arg p "$PROJECT_ID" --arg t "$TRACK_ID" --argjson v "$STATE_VERSION" --arg a "$ACTION" --arg u "$PR_URL" \
                --argjson d "$DETAILS" \
            '{project_id: $p, track_id: $t, state_version: $v, action: $a, result: "done", url: $u, details: $d}' \
          | curl -sS -X POST "$CHAPPE_API_URL/v1/reports" \
              -H "Authorization: Bearer $CHAPPE_API_KEY" -H "content-type: application/json" -d @-
