#!/usr/bin/env python3
"""gh-safe-pr-blocked-on — record in a pull request's description that it waits on a tracker issue.

    gh-safe-pr-blocked-on <pr-number> <issue-number>

Appends, on a line of its own, the marker the tracker's README defines:

    <!--procyon-blocked-on:v1 {"issue":"eic/ProcyonTracker#<n>"}-->

It lifts no finding: the pull request still cannot merge. It tells the worker that the open
findings wait on that issue, so that no further fix round is spent on them while every open finding
needs someone other than the author. The issue must be an open issue of the tracker; the rest of
the description is kept as it is, and a marker that is already there is not added twice.

Inputs: PROCYON_REPO (default eic/Procyon), PROCYON_TRACKER_REPO (default eic/ProcyonTracker).
"""

import json
import os
import subprocess
import sys
import tempfile


def die(message: str) -> None:
    print(f"gh-safe-pr-blocked-on: {message}", file=sys.stderr)
    sys.exit(1)


def api(path: str) -> dict:
    done = subprocess.run(["gh", "api", path], capture_output=True, text=True, check=False)
    try:
        answer = json.loads(done.stdout) if done.returncode == 0 else None
    except json.JSONDecodeError:
        answer = None
    if not isinstance(answer, dict):
        die(f"cannot read {path} — nothing changed")
    return answer


def main(argv: list[str]) -> int:
    if len(argv) != 2 or not all(argument.isdigit() and int(argument) > 0 for argument in argv):
        die("usage: gh-safe-pr-blocked-on <pr-number> <issue-number>")
    pr, number = argv
    repo = os.environ.get("PROCYON_REPO", "").strip() or "eic/Procyon"
    tracker = os.environ.get("PROCYON_TRACKER_REPO", "").strip() or "eic/ProcyonTracker"
    issue = api(f"repos/{tracker}/issues/{number}")
    if "pull_request" in issue or issue.get("state") != "open":
        die(f"{tracker}#{number} is not an open issue — nothing changed")
    marker = f'<!--procyon-blocked-on:v1 {{"issue":"{tracker}#{number}"}}-->'
    body = api(f"repos/{repo}/pulls/{pr}").get("body") or ""
    if marker in body:
        print(f"gh-safe-pr-blocked-on: #{pr} already carries the marker", file=sys.stderr)
        return 0
    with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding="utf-8") as stream:
        stream.write(body.rstrip("\n") + "\n\n" + marker + "\n")
    print(f"gh-safe-pr-blocked-on: gh pr edit {pr} --repo {repo} (adds {marker})", file=sys.stderr)
    os.execvp("gh", ["gh", "pr", "edit", pr, "--repo", repo, "--body-file", stream.name])
    return 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
