"""Dormant launch supervisor for the PF-002 C3-S completion report.

Virtual lab - simulated experiment tooling. Concrete but disabled: it
builds the exact future launch plan (argv, runtime, source and transitive
hashes, clean-HEAD binding) and supervises child processes with an owned
group, descendant tracking, signal handling, bounded streams, durable
partial receipts and fail-closed cleanup, all inside one global clock.
`main` always refuses in version 1. Stub children only are exercised in
qualification; no report is dispatched. Stdlib plus this study's modules
for parsing and hashes; no old study is imported.
"""

import hashlib
import json
import os
import selectors
import signal
import subprocess
import sys
import tempfile
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

HERE = os.path.dirname(os.path.abspath(__file__))
STREAM_CAP = 65536
TOTAL_DEADLINE = 300.0


class SupervisorSignal(BaseException):  # not swallowable by except Exception
    def __init__(self, signum):
        super().__init__(f"signal_{signum}")
        self.signum = signum


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

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

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

    def timeout(self, cap, reserve=0.0):
        remaining = self.remaining() - reserve
        if remaining <= 0:
            raise TimeoutError("launch deadline exhausted")
        return min(cap, remaining)


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


def build_launch_plan(clock=None):
    """The exact future launch binding (built, never executed here)."""
    clock = clock if clock is not None else Clock(TOTAL_DEADLINE)
    clock.timeout(TOTAL_DEADLINE)
    import pf002_c3_completion_checker_v1 as checker
    files = ["pf002_c3_completion_checker_v1.py",
             "PF002_C3_COMPLETION_V1.md",
             "PF002_C3_COMPLETION_V1_SOURCES.md",
             "pf002-c3-completion-v1.svg",
             "pf002_c3_completion_oracle_v1.py",
             "pf002_c3_completion_report_v1.py",
             "pf002_c3_completion_supervisor_v1.py",
             "pf002-c3-completion-v1-protocol.json"]
    head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=HERE,
                          capture_output=True, text=True, timeout=clock.timeout(10))
    status = subprocess.run(["git", "status", "--porcelain"], cwd=HERE,
                            capture_output=True, text=True, timeout=clock.timeout(10))
    if head.returncode != 0 or status.returncode != 0:
        raise RuntimeError("git_provenance_failed")
    clock.timeout(TOTAL_DEADLINE)
    with open(os.path.join(HERE, "pf002-c3-completion-v1-protocol.json"),
              "rb") as _stream:
        twin = checker.parse_launch_protocol(
            _stream.read(131073))
    return {
        "argv": [sys.executable, "-B",
                 os.path.join(HERE, "pf002_c3_completion_report_v1.py")],
        "executable": sys.executable,
        "executable_sha256": sha_file(sys.executable, clock),
        "runtime": sys.version,
        "human_protocol": twin["human_protocol"],
        "source_ledger": twin["source_ledger"],
        "diagram": twin["diagram"],
        "deadline_seconds": TOTAL_DEADLINE,
        "git_head_before": head.stdout.strip(),
        "git_clean_before": status.stdout == "",
        "source_sha256": {name: sha_file(os.path.join(HERE, name), clock)
                          for name in files},
        "flags": {"execution_authorised": twin["execution_authorised"],
                  "fixture_verification_authorised": twin["fixture_verification_authorised"],
                  "authorised_modes": twin["authorised_modes"]},
        "enabled": False,
        "refusal": "report execution not authorised; flags false",
    }


def _ps_table(clock):
    """Process table via ps only. If that capability is denied, this
    raises and supervision fails closed; no alternative process-listing
    API is substituted for a denied capability."""
    if clock.remaining() <= 0:
        raise RuntimeError("deadline_no_scan_time")
    timeout = min(2.0, clock.remaining())
    listing = subprocess.run(["ps", "-A", "-o", "pid=,ppid=,pgid="],
                             capture_output=True, text=True,
                             timeout=timeout)
    if listing.returncode != 0:
        raise RuntimeError("ps_failed")
    rows = []
    for line in listing.stdout.splitlines():
        parts = line.split()
        if len(parts) == 3:
            rows.append(tuple(int(x) for x in parts))
    return rows


_LIVE_HANDLES = {}


def live_handle(pid):
    """Retained Popen handle for an unreaped supervised child, or None."""
    return _LIVE_HANDLES.get(pid)


def scan_available():
    try:
        _ps_table(Clock(5.0))
        return True
    except Exception:
        return False


def _pid_start(pid, clock, reserve=0.0):
    try:
        out = subprocess.run(["ps", "-o", "lstart=", "-p", str(pid)],
                             capture_output=True, text=True,
                             timeout=clock.timeout(2.0, reserve))
        if out.returncode == 0 and out.stdout.strip():
            return out.stdout.strip()
    except Exception:
        pass
    return None


def _scan_snapshot(clock, reserve=0.0):
    """One ps invocation -> {pid: {ppid, pgid, start}}; fails closed."""
    listing = subprocess.run(
        ["ps", "-A", "-o", "pid=,ppid=,pgid=,lstart="],
        capture_output=True, text=True,
        timeout=clock.timeout(2.0, reserve))
    if listing.returncode != 0:
        raise RuntimeError("ps_failed")
    snap = {}
    for line in listing.stdout.splitlines():
        parts = line.split(None, 3)
        if len(parts) == 4 and parts[0].isdigit():
            snap[int(parts[0])] = {"ppid": int(parts[1]),
                                   "pgid": int(parts[2]),
                                   "start": parts[3].strip()}
    return snap


def _descendants(rows, root_pid):
    children = {}
    for pid, ppid, _ in rows:
        children.setdefault(ppid, []).append(pid)
    found, stack = set(), list(children.get(root_pid, []))
    while stack:
        pid = stack.pop()
        if pid not in found:
            found.add(pid)
            stack.extend(children.get(pid, []))
    return found


def _publish_receipt(out_dir, name, record):
    """Publish complete bytes atomically without replacing any artifact."""
    with tempfile.NamedTemporaryFile(dir=out_dir) as stream:
        stream.write((json.dumps(record, sort_keys=True, indent=1,
                                 allow_nan=False) + "\n").encode())
        stream.flush()
        os.fsync(stream.fileno())
        os.link(stream.name, os.path.join(out_dir, name))


def _retain_receipt(out_dir, record, clock):
    """A timely return can confirm a receipt. The receipt alone cannot."""
    candidate = record.pop("success")
    record["deadline_exceeded"] |= clock.remaining() <= 0
    record["receipt_retained"] = True
    record["receipt_state"] = ("provisional"
                               if candidate and not record["deadline_exceeded"]
                               else "failed")
    try:
        _publish_receipt(out_dir, "receipt.json", record)
    except Exception:
        record["receipt_retained"] = False
    expired = clock.remaining() <= 0
    if expired and not record["deadline_exceeded"]:
        record["receipt_deadline_exceeded"] = True
    record["deadline_exceeded"] |= expired
    record["success"] = bool(candidate and record["receipt_retained"]
                             and not record["deadline_exceeded"])


def _retain_publication_failure(out_dir, record):
    """If finalisation invalidates a provisional receipt, retain the cause."""
    failure = dict(record, receipt_state="failed", success=False)
    try:
        _publish_receipt(out_dir, "receipt-failure.json", failure)
    except Exception as error:
        record["failure_receipt_error"] = type(error).__name__


def supervise(argv, cwd, out_dir, record, clock, reserve=2.0,
              cap=STREAM_CAP, postflight=None):
    """Supervise one child; cleanup and receipts are unconditional."""
    record["success"] = False
    record["deadline_exceeded"] = False
    record["supervisor_pid"] = os.getpid()
    record["supervisor_ppid"] = os.getppid()
    buffers = {"stdout": bytearray(), "stderr": bytearray()}
    exceeded, tracked = set(), set()
    tracked_identities = {}
    child = None
    previous_handlers = {}
    finalizing = False
    termination = None

    def _handler(signum, _frame):
        nonlocal termination
        if finalizing:
            if termination is None:
                termination = signum
            return
        raise SupervisorSignal(signum)

    can_signal = hasattr(signal, "SIGTERM")
    if can_signal:
        for sig in (signal.SIGTERM, signal.SIGINT,
                    getattr(signal, "SIGHUP", signal.SIGTERM)):
            try:
                previous_handlers[sig] = signal.signal(sig, _handler)
            except (ValueError, OSError):
                pass
    try:
        if clock.remaining() <= reserve:
            record["stop_reason"] = "deadline"
            return record
        try:
            child = subprocess.Popen(
                argv, cwd=cwd, stdout=subprocess.PIPE,
                stderr=subprocess.PIPE, stdin=subprocess.DEVNULL,
                start_new_session=True)
        except Exception as error:
            record["stop_reason"] = "launch_exception"
            record["launch_exception"] = type(error).__name__
            return record
        _LIVE_HANDLES[child.pid] = child
        record["child_pid"] = child.pid
        record["child_pgid"] = os.getpgid(child.pid)
        record["child_start_identity"] = _pid_start(child.pid, clock, reserve)
        record["child_start_utc"] = time.strftime(
            "%Y-%m-%dT%H:%M:%SZ", time.gmtime())
        selector = selectors.DefaultSelector()
        selector.register(child.stdout, selectors.EVENT_READ, "stdout")
        selector.register(child.stderr, selectors.EVENT_READ, "stderr")
        record["stop_reason"] = "interrupted"
        try:
            while selector.get_map():
                left = clock.remaining() - reserve
                if left <= 0:
                    record["stop_reason"] = "deadline"
                    break
                events = selector.select(timeout=min(left, 0.1))
                try:
                    snap = _scan_snapshot(clock, reserve)
                    rows = [(pid, v["ppid"], v["pgid"])
                            for pid, v in snap.items()]
                    found = _descendants(rows, child.pid)
                    for pid in found:
                        if pid not in tracked_identities:
                            tracked_identities[pid] = snap[pid]["start"]
                    tracked |= found
                except (TimeoutError, subprocess.TimeoutExpired):
                    record["stop_reason"] = "deadline"
                    break
                except Exception:
                    record["scan_error"] = True
                if clock.remaining() <= reserve:
                    record["stop_reason"] = "deadline"
                    break
                for key, _ in events:
                    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)
                        record["stop_reason"] = "stream_cap"
                if record["stop_reason"] == "stream_cap":
                    break
            else:
                record["stop_reason"] = "eof"
        finally:
            selector.close()
        if record.get("stop_reason") == "eof":
            try:
                child.wait(timeout=clock.timeout(TOTAL_DEADLINE, reserve))
            except (TimeoutError, subprocess.TimeoutExpired):
                record["stop_reason"] = "deadline"
        return record
    except SupervisorSignal as error:
        record.update(stop_reason="signal", signal=error.signum)
        raise
    finally:
        # Keep cleanup non-interruptible at the Python level, while
        # recording termination delivered during cleanup or postflight.
        finalizing = True
        try:
            record["tracked_descendants"] = sorted(tracked)
            record["tracked_identities"] = {
                str(k): v for k, v in sorted(tracked_identities.items())}
            cleanup_errors = []
            if record.get("scan_error"):
                cleanup_errors.append("scan_drain")
            if child is not None:
                for pid in sorted(tracked):
                    identity = tracked_identities.get(pid)
                    if identity is None or _pid_start(pid, clock) != identity:
                        cleanup_errors.append(f"tracked_unverified:{pid}")
                        continue
                    try:
                        os.kill(pid, signal.SIGKILL)
                    except ProcessLookupError:
                        pass  # verified absence of that tracked pid
                    except PermissionError as error:
                        cleanup_errors.append(
                            f"descendant_denial:{type(error).__name__}")
                # Kill the group only while the leader is alive or a
                # scan shows live members of its group; after the leader
                # is reaped the PGID may have been reused, so an absent
                # leader with no scanned members is verified absence.
                scan_failed = False
                members = []
                snap = {}
                try:
                    snap = _scan_snapshot(clock)
                    members = [pid for pid, v in snap.items()
                               if v["pgid"] == child.pid
                               and pid != child.pid]
                except Exception:
                    scan_failed = True
                    cleanup_errors.append("scan_cleanup")
                leader_alive = child.poll() is None
                # membership and start identity from the same snapshot
                verified_members = [
                    pid for pid in members
                    if tracked_identities.get(pid) is not None
                    and snap[pid]["start"] == tracked_identities[pid]]
                if leader_alive:
                    # our unreaped direct child: its PID is still ours
                    should_kill_group = True
                elif verified_members:
                    should_kill_group = True
                elif members:
                    should_kill_group = False
                    cleanup_errors.append("group_ownership_uncertain")
                else:
                    should_kill_group = False  # verified absence
                if should_kill_group:
                    try:
                        os.killpg(child.pid, signal.SIGKILL)
                    except ProcessLookupError:
                        if leader_alive:
                            cleanup_errors.append(
                                "group_absence_unverified")
                    except PermissionError as error:
                        cleanup_errors.append(
                            f"group_denial:{type(error).__name__}")
                try:
                    child.wait(timeout=max(0.0, min(5.0,
                                                     clock.remaining())))
                    record["reaped"] = True
                    _LIVE_HANDLES.pop(child.pid, None)
                except subprocess.TimeoutExpired:
                    record["reaped"] = False
                    record["child_handle_retained"] = True
                    cleanup_errors.append("reap_timeout")
                for stream in (child.stdout, child.stderr):
                    if stream:
                        stream.close()
                record["exit"] = child.returncode
            try:
                rows = _ps_table(clock)
                live = _descendants(rows, child.pid) if child else set()
                live |= {pid for pid, _, pgid in rows
                         if child and pgid == child.pid
                         and pid != child.pid}
                for pid in list(tracked):
                    try:
                        os.kill(pid, 0)
                        live.add(pid)
                    except ProcessLookupError:
                        pass
                    except PermissionError:
                        live.add(pid)  # exists but not signalable
                live -= {os.getpid()}
                record["survivors_by_ps"] = "none_found" if not live \
                    else f"survivors_found:{sorted(live)}"
                if live:
                    cleanup_errors.append("survivors")
            except Exception:
                record["survivors_by_ps"] = "unavailable"
                cleanup_errors.append("scan")
            record["cleanup_errors"] = cleanup_errors
            record["cleanup_ok"] = not cleanup_errors
            record["child_end_utc"] = time.strftime(
                "%Y-%m-%dT%H:%M:%SZ", time.gmtime())
            log_ok = True
            for name in ("stdout", "stderr"):
                data = bytes(buffers[name])
                try:
                    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}
                except Exception as error:
                    record[name] = {"error": type(error).__name__}
                    log_ok = False
            record["child_success"] = bool(
                child is not None and record.get("stop_reason") == "eof"
                and record.get("exit") == 0 and record.get("reaped")
                and record["cleanup_ok"] and log_ok and not exceeded
                and record["survivors_by_ps"] == "none_found")
            if postflight is not None and "signal" not in record and termination is None:
                try:
                    clock.timeout(TOTAL_DEADLINE)
                    record["after"] = postflight(clock)
                    clock.timeout(TOTAL_DEADLINE)
                    if not record["after"]["before_after_match"]:
                        record["postflight_error"] = "postflight_drift"
                except SupervisorSignal as error:
                    termination = error.signum
                except (TimeoutError, subprocess.TimeoutExpired):
                    record["postflight_error"] = "postflight_deadline"
                except Exception as error:
                    record["postflight_error"] = type(error).__name__
            if termination is not None:
                record.update(stop_reason="signal", signal=termination)
            record["deadline_exceeded"] = clock.remaining() <= 0
            record["success"] = bool(
                record["child_success"] and not record["deadline_exceeded"]
                and not record.get("postflight_error") and "signal" not in record)
            signal_at_publication = record.get("signal")
            _retain_receipt(out_dir, record, clock)
        finally:
            for sig, handler in previous_handlers.items():
                try:
                    signal.signal(sig, handler)
                except (ValueError, OSError):
                    pass
        if termination is not None:
            record.update(stop_reason="signal", signal=termination, success=False)
        record["deadline_exceeded"] |= clock.remaining() <= 0
        if record["deadline_exceeded"]:
            record["success"] = False
        if record["receipt_retained"] and (
                record.get("receipt_deadline_exceeded")
                or record.get("signal") != signal_at_publication
                or (record["receipt_state"] == "provisional" and not record["success"])):
            _retain_publication_failure(out_dir, record)
        if termination is not None:
            raise SupervisorSignal(termination)


def verify_launch_state(plan, clock):
    """Recompute source/HEAD state and compare with the plan (after)."""
    after = build_launch_plan(clock)
    match = (after["source_sha256"] == plan["source_sha256"]
             and after["git_head_before"] == plan["git_head_before"]
             and after["git_clean_before"] and plan["git_clean_before"]
             and after["executable_sha256"] == plan["executable_sha256"])
    return {"git_head_after": after["git_head_before"],
            "source_sha256_after": after["source_sha256"],
            "git_clean_after": after["git_clean_before"],
            "before_after_match": match}


def execute_dormant_stub(out_dir, stub_argv=None):
    """Dormant fixture path under one shared clock.

    Preflight runs before any spawn and refuses a dirty tree. The stub is
    supervised inside the same clock, and postflight cleanliness is
    reported directly from the after-status, not from snapshot equality.
    """
    clock = Clock(60.0)
    result = {"dispatched_stub": False, "dispatched_report": False,
              "success": False}
    try:
        plan = build_launch_plan(clock)
    except (TimeoutError, subprocess.TimeoutExpired):
        return dict(result, refusal="preflight_deadline")
    result.update(plan=plan, clean_before=plan["git_clean_before"])
    if not result["clean_before"]:
        return dict(result, refusal="dirty_preflight")
    reserve = 4.0
    if clock.remaining() <= reserve:
        return dict(result, refusal="insufficient_stub_time")
    record = {"plan": plan}
    supervise(stub_argv or [sys.executable, "-c", "pass"], HERE, out_dir,
              record, clock, reserve=reserve, cap=STREAM_CAP,
              postflight=lambda shared_clock: verify_launch_state(plan, shared_clock))
    result.update(stub=record, dispatched_stub="child_pid" in record,
                  success=record["success"])
    if "after" in record:
        result.update(after=record["after"],
                      clean_after=record["after"]["git_clean_after"])
    if record.get("postflight_error"):
        result["refusal"] = record["postflight_error"]
    if result["success"] and clock.remaining() <= 0:
        record.update(success=False, deadline_exceeded=True)
        result.update(success=False, refusal="receipt_deadline")
        _retain_publication_failure(out_dir, record)
    return result


def execute_dormant():
    """Integrated dormant path: plan, refuse, verify before/after."""
    clock = Clock(TOTAL_DEADLINE)
    plan = build_launch_plan(clock)
    after = verify_launch_state(plan, clock)
    return {"plan": plan, "dispatched": False,
            "refusal": plan["refusal"], "after": after,
            "success": bool(after["before_after_match"]
                            and not plan["enabled"])}


def main(argv):
    sys.stderr.write("refused: report launch disabled; execution is not "
                     "authorised and both launch flags are false\n")
    return 2


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