#!/usr/bin/env bash
# gh-safe-pr-create — the ONLY sanctioned way to open a Procyon PR (authoring path).
#
# Verifies the author target claim is still held (fail closed if another agent took the target), then
# runs `gh pr create` with the given args. The branch must already have been pushed via git-safe-push
# (which create-only-pushes it, so two agents can't both create the same branch). It also checks the
# PR body carries the machine-readable target marker the dup-sweeper relies on (coordination contract §4),
# and the standalone `Analysis:` attribution line the code repository requires of every PR.
#
# Inputs:
#   PROCYON_AUTHOR_CLAIM_KEY   the author/<Area>/<AnalysisName>/<target-id> claim acquired in shell before the agent ran
#   PROCYON_TARGET_MARKER      the exact <!--procyon-target:v1 {...}--> string the PR body must contain
#   PROCYON_CLAIM_SH           path to claim.sh (default: alongside this script)
# All `gh pr create` flags pass through unchanged.
set -uo pipefail

CLAIM_KEY="${PROCYON_AUTHOR_CLAIM_KEY:-}"
MARKER="${PROCYON_TARGET_MARKER:-}"
REQUIRE_MARKER="${PROCYON_REQUIRE_TARGET_MARKER:-}"   # 1 ⇒ body must carry SOME well-formed <!--procyon-target--> marker
CLAIM_SH="${PROCYON_CLAIM_SH:-$(cd "$(dirname "$0")" && pwd)/claim.sh}"

die() { echo "gh-safe-pr-create: $*" >&2; exit 1; }

# extract the PR body from the passed `gh pr create` flags (--body/-b <s>, --body-file/-F <f>).
pr_body_from_args() {
    local b="" prev=""
    for a in "$@"; do
        case "$prev" in
            --body|-b) b="$a";;
            --body-file|-F) [[ -f "$a" ]] && b="$(cat "$a")";;
        esac
        prev="$a"
    done
    printf '%s' "$b"
}

# 1) Author claim must still be ours (else another agent is authoring this target — abandon).
if [[ -n "$CLAIM_KEY" && -x "$CLAIM_SH" ]]; then
    "$CLAIM_SH" holds "$CLAIM_KEY"; rc=$?
    [[ $rc -eq 2 ]] && die "cannot check author lease '$CLAIM_KEY' (claim.sh error above) — do NOT create the PR"
    [[ $rc -eq 0 ]] \
        || die "author lease '$CLAIM_KEY' lost (another agent took the target) — do NOT create the PR"
fi

# 2) The PR body must carry the target marker so the conservative dup-sweeper can match it.
#    Either an EXACT marker is mandated (PROCYON_TARGET_MARKER, when the shell pre-picked the target),
#    or just SOME well-formed marker is required (PROCYON_REQUIRE_TARGET_MARKER, agent-picked target).
if [[ -n "$MARKER" ]]; then
    body="$(pr_body_from_args "$@")"
    [[ "$body" == *"$MARKER"* ]] \
        || die "PR body is missing the required target marker:
  $MARKER
Add it to the PR body (it lets other agents and the dup-sweeper recognize this target)."
elif [[ "$REQUIRE_MARKER" == "1" ]]; then
    body="$(pr_body_from_args "$@")"
    # Well-formed (coordination contract §4): `analysis` is a plan id <Area>/<AnalysisName> and `id` a
    # target id, both verbatim from the plan's analysis.yaml. The keys may come in either order, so
    # each marker is tested for both. (No `grep -q` in the pipeline: with pipefail, a reader that
    # exits early turns a match into a SIGPIPE failure.)
    grep -oE '<!--procyon-target:v1 \{[^}]*\}-->' <<<"$body" \
        | grep -E '"analysis"[[:space:]]*:[[:space:]]*"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*"' \
        | grep -E '"id"[[:space:]]*:[[:space:]]*"[^"]+"' >/dev/null \
        || die "PR body is missing a well-formed target marker. Add one line per target the PR implements, like:
  <!--procyon-target:v1 {\"analysis\":\"<Area>/<AnalysisName>\",\"id\":\"T<n>.<m>\"}-->
with the plan's id and the target's id, both verbatim from the plan's analysis.yaml. It lets other
agents and the dup-sweeper recognize which plan target this PR implements."
fi

# 2b) A stack-gap marker is optional: only a PR that adds or changes a stand-in for something the
#     shared EIC software lacks carries one (coordination contract §4). One that is there must be
#     well-formed, because a human looks PRs up by it: `id` is the id the stand-in is declared under
#     in procyon/stack_gaps.yaml, lowercase words joined by hyphens.
body="$(pr_body_from_args "$@")"
gap_markers="$(grep -oF '<!--procyon-stack-gap' <<<"$body" | wc -l || true)"
gap_wellformed="$(grep -oE '<!--procyon-stack-gap:v1 \{[[:space:]]*"id"[[:space:]]*:[[:space:]]*"[a-z0-9]+(-[a-z0-9]+)*"[[:space:]]*\}-->' <<<"$body" | wc -l || true)"
[[ "$gap_markers" -eq "$gap_wellformed" ]] \
    || die "PR body has a malformed stack-gap marker. Write one line per declared stand-in, like:
  <!--procyon-stack-gap:v1 {\"id\":\"<gap-id>\"}-->
with the id it is declared under in procyon/stack_gaps.yaml. The marker requests nothing: asking an
upstream project for the shared version is a human's decision and a human's act."

# 3) Every PR description carries one standalone attribution line (AGENTS.md of the code repository):
#    `Analysis: <Area>/<AnalysisName>`, or `Analysis: none`. The worker reads a PR's area from it.
body="$(pr_body_from_args "$@")"
grep -E '^[[:space:]]*Analysis:[[:space:]]*(none|[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*)[[:space:]]*$' \
    <<<"$body" >/dev/null \
    || die "PR body is missing the attribution line. Add, on a line of its own, either
  Analysis: <Area>/<AnalysisName>
with the plan's id, or
  Analysis: none
for work that serves no single plan."

echo "gh-safe-pr-create: gh pr create $*" >&2
exec gh pr create "$@"
