#!/usr/bin/env python3
"""gh-safe-issue-create — the ONLY sanctioned way for a round to file an issue.

A round files an issue in exactly one place: the Procyon tracker, for a matter its pull request
cannot resolve (a gap in a plan, a capability the shared EIC software lacks, a dataset, the
environment, a human-owned part of Procyon). Never in the plans repository, never in an upstream
project, never in the code repository.

    gh-safe-issue-create --title "[plan] <subject>" --body-file <file> [--new]

Before it runs `gh issue create`, it checks that

  - the body carries exactly one well-formed marker (the tracker's README defines it):
        <!--procyon-tracker:v1 {"class":"plan","analysis":"<Area>/<AnalysisName>","target":"T0.2","key":"<slug>"}-->
  - the title starts with the class in brackets, and the body has every section the tracker asks for;
  - no open issue is already filed for the same matter. An open issue with the same class,
    analysis, target and key is the same matter: its URL is printed and nothing is created. Open
    issues on the same class, analysis and target with another key are listed, and nothing is
    created unless --new says they were read and are a different matter.

Output: the issue's URL on stdout. Exit 0 = an issue for this matter exists (created now, or found);
3 = possible duplicates listed, read them and re-run with --new or comment on one; 1 = refused.

Inputs: PROCYON_TRACKER_REPO (default eic/ProcyonTracker). `--repo` is accepted only if it names it.
"""

import json
import os
import re
import subprocess
import sys

DEFAULT_REPO = "eic/ProcyonTracker"
CLASSES = ("plan", "stack", "input", "environment", "framework")
SECTIONS = (
    "Where it was met",
    "What cannot be resolved there",
    "Why the pull request cannot resolve it",
    "What has been seen",
    "Options",
    "Done when",
)
MARKER = re.compile(r"<!--procyon-tracker:v1 (\{[^}]*\})-->")
PLAN_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*")
TARGET = re.compile(r"T[0-9]+\.[0-9]+")
KEY = re.compile(r"[a-z0-9]+(-[a-z0-9]+)*")
KEY_LENGTH = 64
EXAMPLE = (
    '  <!--procyon-tracker:v1 {"class":"plan","analysis":"<Area>/<AnalysisName>",'
    '"target":"T<n>.<m>","key":"<words-joined-by-hyphens>"}-->'
)


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


def parse_marker(body: str) -> dict:
    """The one tracker marker of a body, validated. Exits with the reason when it is not there."""
    found = MARKER.findall(body)
    if len(found) != 1 or body.count("<!--procyon-tracker") != 1:
        die(f"the issue body must carry exactly one well-formed tracker marker, like:\n{EXAMPLE}")
    try:
        marker = json.loads(found[0])
    except json.JSONDecodeError:
        marker = None
    if not isinstance(marker, dict) or set(marker) != {"class", "analysis", "target", "key"}:
        die(f"the tracker marker must have exactly the keys class, analysis, target and key:\n{EXAMPLE}")
    if not all(isinstance(value, str) for value in marker.values()):
        die("every value of the tracker marker is a string")
    if marker["class"] not in CLASSES:
        die(f"class must be one of {', '.join(CLASSES)}")
    if marker["analysis"] != "none" and not PLAN_ID.fullmatch(marker["analysis"]):
        die("analysis must be the plan's id <Area>/<AnalysisName>, or none")
    if marker["target"] and not TARGET.fullmatch(marker["target"]):
        die('target must be a target id T<n>.<m>, or ""')
    if not KEY.fullmatch(marker["key"]) or len(marker["key"]) > KEY_LENGTH:
        die(f"key must be lowercase words joined by hyphens, at most {KEY_LENGTH} characters")
    return marker


def marker_of(body: object) -> dict | None:
    """The tracker marker of an existing issue, or None when it has none that parses."""
    found = MARKER.findall(body) if isinstance(body, str) else []
    try:
        marker = json.loads(found[0]) if len(found) == 1 else None
    except json.JSONDecodeError:
        return None
    return marker if isinstance(marker, dict) else None


def open_issues(repo: str) -> list[dict]:
    """The open issues of the tracker (not its pull requests). Exits when they cannot be read."""
    done = subprocess.run(
        ["gh", "api", f"repos/{repo}/issues?state=open&per_page=100"], capture_output=True, text=True, check=False
    )
    try:
        issues = json.loads(done.stdout) if done.returncode == 0 else None
    except json.JSONDecodeError:
        issues = None
    if not isinstance(issues, list):
        die(f"cannot read the open issues of {repo} — do NOT file; say so in your report")
    return [issue for issue in issues if isinstance(issue, dict) and "pull_request" not in issue]


def main(argv: list[str]) -> int:
    repo = os.environ.get("PROCYON_TRACKER_REPO", "").strip() or DEFAULT_REPO
    title = body_file = None
    new = False
    arguments = iter(argv)
    for argument in arguments:
        if argument == "--new":
            new = True
        elif argument in ("--title", "-t"):
            title = next(arguments, None)
        elif argument in ("--body-file", "-F"):
            body_file = next(arguments, None)
        elif argument in ("--repo", "-R"):
            if (next(arguments, "") or "").lower() != repo.lower():
                die(f"a round files issues only in {repo}")
        else:
            die(f"unknown argument {argument!r}; use --title, --body-file and, after reading the listed issues, --new")
    if not title or not body_file:
        die("give --title and --body-file")
    try:
        with open(body_file, encoding="utf-8") as stream:
            body = stream.read()
    except OSError as error:
        die(f"cannot read {body_file}: {error}")
    marker = parse_marker(body)
    if not title.startswith(f"[{marker['class']}] ") or len(title.strip()) <= len(marker["class"]) + 3:
        die(f"the title must start with [{marker['class']}] and then name the matter")
    missing = [name for name in SECTIONS if not re.search(rf"^#{{2,3}} {re.escape(name)}\s*$", body, re.M)]
    if missing:
        die("the body lacks the section(s): " + "; ".join(missing) + " (each a heading of its own, `## <name>`)")

    same_target = []
    for issue in open_issues(repo):
        other = marker_of(issue.get("body"))
        if other is None or any(other.get(k) != marker[k] for k in ("class", "analysis", "target")):
            continue
        if other.get("key") == marker["key"]:
            print("gh-safe-issue-create: already filed, nothing created — comment there instead", file=sys.stderr)
            print(issue.get("html_url"))
            return 0
        same_target.append(issue)
    if same_target and not new:
        print(
            "gh-safe-issue-create: open issues on the same class, analysis and target — read them. If one is the "
            "same matter, comment there and use its number; if yours is a different matter, re-run with --new:",
            file=sys.stderr,
        )
        for issue in same_target:
            print(f"  #{issue.get('number')} {issue.get('title')} — {issue.get('html_url')}", file=sys.stderr)
        return 3
    print(f"gh-safe-issue-create: gh issue create --repo {repo} --title {title!r}", file=sys.stderr)
    os.execvp("gh", ["gh", "issue", "create", "--repo", repo, "--title", title, "--body-file", body_file])
    return 1


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