"""Bounded launch supervisor for the PF-002 C3 analytical report, version 1.

Virtual lab - simulated experiment tooling. It runs the report builder once, as
one child in its own process group. One global clock bounds everything the
supervisor does, from the first git check to the receipt, at 300 s. Stream caps
are enforced while the child runs: output is drained through pipes into shared
buffers that never exceed the cap, and the child group is killed at the cap. Waits after a kill are bounded. TERM, INT and
HUP are caught, and the group is killed and a receipt written on every path.

The report builder is stdlib only and spawns no process. Group cleanup covers the
child and any descendant left in its process group. A descendant that leaves the
group with setsid is outside this supervisor's ownership, which is stated rather
than claimed away; the ps scan would still report any member left in the group.

Two files are written in the fresh evidence directory: receipt.json, with hashes
and relative names only, and raw-launch.json, which holds the full executable
path and argv and stays in the ignored directory, never published.

Usage, from the repository root, only after root's release:
    python3 -I -B experiments/pf-001/pf002_c3_analytical_supervisor_v1.py --evidence NAME
NAME is a fresh directory under .cache/review-evidence/pf002-c3-analytical-v1/.
"""

import hashlib
import json
import os
import platform
import re
import selectors
import signal
import subprocess
import sys
import time

if __name__ == "__main__":
    # Reviewed entry bootstrap: add exactly this file's directory.
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import pf002_c3_analytical_guard_v1 as guard  # noqa: E402
import pf002_c3_analytical_report_v1 as report  # noqa: E402

DEADLINE_SECONDS = 300.0
CLEANUP_RESERVE_SECONDS = 30.0
COMMAND_SECONDS = 20.0
REAP_SECONDS = 10.0
STREAM_CAP = 65536
EVIDENCE_PARENT = (".cache", "review-evidence", "pf002-c3-analytical-v1")
NAME = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
RECEIPT_SCHEMA = "pf002-c3-analytical-v1-launch-receipt/1"
TRANSITIVE = ("pf002_c3_analytical_guard_v1.py", "pf002_c3_analytical_checker_v1.py",
              "pf002_c3_analytical_oracle_v1.py", "pf002_c3_analytical_report_v1.py",
              "pf002_c3_analytical_supervisor_v1.py", "test_pf002_c3_analytical_v1.py",
              "pf002-c3-analytical-v1-protocol.json", "PF002_C3_ANALYTICAL_V1.md",
              "PF002_C3_ANALYTICAL_V1_SOURCES.md", "PF002_C3_ANALYTICAL_V1_STAGE2.md",
              "PF002_C3_ANALYTICAL_V1_REPORT_PLAN.md")
CODE_FILES = TRANSITIVE[:6]
SIGNALS = (signal.SIGTERM, signal.SIGINT, signal.SIGHUP)


class SupervisorSignal(Exception):
    def __init__(self, signum):
        super().__init__(signum)
        self.signum = signum


def _on_signal(signum, frame):
    raise SupervisorSignal(signum)


class Clock:
    """One monotonic budget for the whole supervisor."""

    def __init__(self, deadline=DEADLINE_SECONDS):
        self.start = time.monotonic()
        self.deadline = deadline

    def elapsed(self):
        return time.monotonic()-self.start

    def remaining(self):
        return self.deadline-self.elapsed()

    def budget(self, limit):
        left = self.remaining()
        if left <= 0:
            raise TimeoutError("global deadline reached")
        return max(0.05, min(limit, left))


def utc():
    return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())


def sha_file(path):
    digest = hashlib.sha256()
    with open(path, "rb") as stream:
        for block in iter(lambda: stream.read(1 << 20), b""):
            digest.update(block)
    return digest.hexdigest()


def run(clock, args, cwd):
    return subprocess.run(args, cwd=cwd, capture_output=True, text=True,
                          timeout=clock.budget(COMMAND_SECONDS))


def git(clock, repo, *args):
    result = run(clock, ["git", *args], repo)
    if result.returncode != 0:
        raise RuntimeError("git command failed")
    return result.stdout.strip()


def repo_state(clock, repo):
    return {"head": git(clock, repo, "rev-parse", "HEAD"), "upstream": git(clock, repo, "rev-parse", "@{u}"),
            "porcelain_empty": git(clock, repo, "status", "--porcelain=v1") == "",
            "sources": {name: sha_file(guard.ROOT/name) for name in TRANSITIVE}}


def group_members(clock, pgid):
    """Independent survivor scan by ps; raises if ps is unavailable."""
    listing = run(clock, ["ps", "-A", "-o", "pid=,pgid="], "/")
    if listing.returncode != 0:
        raise RuntimeError("ps failed")
    members = []
    for line in listing.stdout.splitlines():
        parts = line.split()
        if len(parts) == 2 and parts[1] == str(pgid):
            members.append(int(parts[0]))
    return members


def _drain(child, clock, reserve, cap, buffers, exceeded):
    """Fill the shared buffers until EOF, the cap or the child budget. Returns the stop reason.

    Bytes land in the caller's buffers as they arrive, so a signal or exception
    keeps everything already read. No buffer ever holds more than cap bytes.
    """
    selector = selectors.DefaultSelector()
    selector.register(child.stdout, selectors.EVENT_READ, "stdout")
    selector.register(child.stderr, selectors.EVENT_READ, "stderr")
    try:
        while selector.get_map():
            left = clock.remaining()-reserve
            if left <= 0:
                return "deadline"
            for key, _ in selector.select(timeout=min(left, 1.0)):
                chunk = os.read(key.fileobj.fileno(), 65536)
                if not chunk:
                    selector.unregister(key.fileobj)
                    continue
                room = cap-len(buffers[key.data])
                buffers[key.data] += chunk[:room]
                if len(chunk) > room:
                    exceeded.add(key.data)
                    return "stream_cap"
        return "eof"
    finally:
        selector.close()


def supervise(argv, cwd, out_dir, record, clock, reserve=CLEANUP_RESERVE_SECONDS, cap=STREAM_CAP):
    """Run one child in its own group; always kill the group; record facts as they happen."""
    buffers = {"stdout": bytearray(), "stderr": bytearray()}
    exceeded = set()
    record["child_start_utc"] = utc()
    child = subprocess.Popen(argv, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             stdin=subprocess.DEVNULL, start_new_session=True)
    record["child_pid"] = child.pid
    record["stop_reason"] = "interrupted"
    try:
        reason = _drain(child, clock, reserve, cap, buffers, exceeded)
        if reason == "eof":
            try:
                child.wait(timeout=max(0.05, clock.remaining()-reserve))
            except subprocess.TimeoutExpired:
                reason = "deadline"
        record["stop_reason"] = reason
    finally:
        try:
            os.killpg(child.pid, signal.SIGKILL)
        except ProcessLookupError:
            pass
        try:
            child.wait(timeout=min(REAP_SECONDS, max(0.05, clock.remaining())))
            record["reaped"] = True
        except subprocess.TimeoutExpired:
            record["reaped"] = False
        for stream in (child.stdout, child.stderr):
            stream.close()
        record["exit"] = child.returncode
        record["child_end_utc"] = utc()
        for name in ("stdout", "stderr"):
            data = bytes(buffers[name])
            with open(os.path.join(out_dir, f"{name}.log"), "xb") as stream:
                stream.write(data)
            record[name] = {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest(),
                            "exceeded_cap": name in exceeded, "within_cap": name not in exceeded}
        try:
            os.killpg(child.pid, 0)
            record["survivors_by_signal"] = "survivors_found"
        except ProcessLookupError:
            record["survivors_by_signal"] = "none_found"
        except PermissionError:
            record["survivors_by_signal"] = "unavailable"
        try:
            record["survivors_by_ps"] = "none_found" if not group_members(clock, child.pid) else "survivors_found"
        except (OSError, subprocess.SubprocessError, RuntimeError, TimeoutError):
            record["survivors_by_ps"] = "unavailable"
    return record


def failures_for(record, before, after, report_info, clock):
    failures = []
    if record.get("exit") != 0:
        failures.append("child_exit_nonzero")
    if record.get("stop_reason") != "eof":
        failures.append(f"child_stopped_{record.get('stop_reason')}")
    if not record.get("reaped"):
        failures.append("child_not_reaped")
    if record.get("survivors_by_signal") != "none_found" or record.get("survivors_by_ps") != "none_found":
        failures.append("survivor_check_not_clean")
    for name in ("stdout", "stderr"):
        if not record.get(name, {}).get("within_cap"):
            failures.append(f"{name}_cap")
    if after is None:
        failures.append("after_state_missing")
    else:
        for key in ("head", "upstream", "sources"):
            if before[key] != after[key]:
                failures.append(f"{key}_changed")
        if not after["porcelain_empty"]:
            failures.append("tree_not_clean_after")
    if report_info.get("error"):
        failures.append(report_info["error"])
    if clock.elapsed() > clock.deadline:
        failures.append("global_deadline")
    return failures


def check_report(path, protocol, before):
    """Validate the written report and bind it to the launch state."""
    try:
        with open(path, "rb") as stream:
            data = stream.read(report.MAX_REPORT_BYTES+1)
    except FileNotFoundError:
        return {"error": "report_missing"}
    try:
        parsed = report.validate_bytes(data, protocol)
    except report.ReportRefusal as error:
        return {"error": "report_invalid", "reason": str(error)}
    expected = {name: "sha256:"+before["sources"][name] for name in report.IMPLEMENTATION_FILES}
    expected_inputs = {name: "sha256:"+before["sources"][name] for name in report.INPUT_FILES}
    if parsed["implementation"] != expected or parsed["inputs"] != expected_inputs:
        return {"error": "report_provenance_mismatch"}
    if parsed["source"]["commit"] != before["head"]:
        return {"error": "report_commit_mismatch"}
    return {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest(), "valid": True,
            "summary": parsed["summary"]}


def _write(path, payload):
    with open(path, "x", encoding="utf-8") as stream:
        json.dump(payload, stream, indent=1, sort_keys=True)
        stream.write("\n")


def main(argv):
    clock = Clock()
    for signum in SIGNALS:
        signal.signal(signum, _on_signal)
    if len(argv) != 3 or argv[1] != "--evidence" or not NAME.match(argv[2]):
        sys.stderr.write("refused: usage --evidence NAME\n")
        return 2
    protocol = guard.load_protocol()
    if protocol["lifecycle"] != "report":
        sys.stderr.write("refused: retained analytic report not authorised\n")
        return 2
    repo = str(guard.ROOT.parent.parent)
    before = repo_state(clock, repo)
    if not before["porcelain_empty"] or before["head"] != before["upstream"]:
        sys.stderr.write("refused: tree not clean or HEAD not equal to upstream\n")
        return 2
    release = protocol["twin"]["stage_3_report_release"]
    code = [f"experiments/pf-001/{name}" for name in CODE_FILES]
    if run(clock, ["git", "merge-base", "--is-ancestor", release, "HEAD"], repo).returncode != 0 or \
            run(clock, ["git", "diff", "--quiet", release, "HEAD", "--", *code], repo).returncode != 0:
        sys.stderr.write("refused: released commit is not an ancestor or code changed since it\n")
        return 2
    parent = os.path.join(repo, *EVIDENCE_PARENT)
    os.makedirs(parent, exist_ok=True)
    out_dir = os.path.join(parent, argv[2])
    os.mkdir(out_dir)
    report_path = os.path.join(out_dir, "report.json")
    child_argv = [sys.executable, "-I", "-B", str(guard.ROOT/"pf002_c3_analytical_report_v1.py"),
                  "--report", report_path, "--source-commit", before["head"]]
    raw = {"note": "contains local paths; ignored evidence only, never published",
           "executable": sys.executable, "executable_realpath": os.path.realpath(sys.executable),
           "supervisor_argv": list(sys.argv), "child_argv": child_argv, "child_cwd": str(guard.ROOT)}
    receipt = {"schema": RECEIPT_SCHEMA, "supervisor_pid": os.getpid(), "parent_pid": os.getppid(),
               "supervisor_start_utc": None, "evidence_name": argv[2], "released_commit": release,
               "before": before, "deadline_seconds": DEADLINE_SECONDS,
               "cleanup_reserve_seconds": CLEANUP_RESERVE_SECONDS, "stream_cap_bytes": STREAM_CAP,
               "runtime": {"python": platform.python_version(), "interpreter": platform.python_implementation(),
                           "executable_sha256": sha_file(os.path.realpath(sys.executable))},
               "supervisor_argv_redacted": ["PYTHON", "-I", "-B",
                                            "experiments/pf-001/pf002_c3_analytical_supervisor_v1.py",
                                            "--evidence", argv[2]],
               "child_argv_redacted": ["PYTHON", "-I", "-B", "experiments/pf-001/pf002_c3_analytical_report_v1.py",
                                       "--report", "EVIDENCE/report.json", "--source-commit", before["head"]],
               "raw_launch_sha256": None}
    receipt["supervisor_start_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time()-clock.elapsed()))
    record, after, report_info, failures = {}, None, {}, []
    try:
        supervise(child_argv, str(guard.ROOT), out_dir, record, clock)
        report_info = check_report(report_path, protocol, before)
        after = repo_state(clock, repo)
    except SupervisorSignal as stop:
        failures.append(f"signal_{stop.signum}")
    except Exception as error:  # fail closed, keep only the type
        failures.append(f"supervisor_exception_{type(error).__name__}")
    finally:
        for signum in SIGNALS:
            signal.signal(signum, signal.SIG_IGN)
        if "child_pid" in record and "survivors_by_ps" not in record:
            try:
                os.killpg(record["child_pid"], signal.SIGKILL)
            except (ProcessLookupError, PermissionError):
                pass
        receipt.update(record)
        receipt["after"] = after
        receipt["report"] = report_info
        failures = failures+failures_for(record, before, after, report_info, clock)
        receipt["failures"] = failures
        receipt["outcome"] = "completed" if not failures else "failed"
        receipt["elapsed_seconds"] = round(clock.elapsed(), 3)
        receipt["end_utc"] = utc()
        raw_path = os.path.join(out_dir, "raw-launch.json")
        _write(raw_path, raw)
        receipt["raw_launch_sha256"] = sha_file(raw_path)
        _write(os.path.join(out_dir, "receipt.json"), receipt)
    sys.stdout.write(json.dumps({"outcome": receipt["outcome"], "failures": failures}) + "\n")
    return 0 if not failures else 1


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