"""Launch identity and stub supervision for PF-002 C3-S M1.

The real launch is disabled and fails before spawn or calculation.
`run_stub` exists only for synthetic fixture qualification: bounded
stream acquisition, a shared deadline including cleanup reserve,
owned group/descendant verification, checked git state before/after,
and no-clobber receipts. Stdlib only.
"""

import hashlib
import json
import os
import platform
import shutil
import signal
import subprocess
import sys
import threading
import time

HERE = os.path.dirname(os.path.abspath(__file__))
TRANSITIVE_FILES = (
    "pf002-c3s-m1-nominal-protocol.json",
    "PF002_C3S_M1_NOMINAL.md",
    "PF002_C3S_M1_NOMINAL_SOURCES.md",
    "pf002_c3s_m1_nominal_checker.py",
    "pf002_c3s_m1_nominal_oracle.py",
    "pf002_c3s_m1_nominal_report.py",
    "pf002_c3s_m1_nominal_supervisor.py",
)
STREAM_CAP = 65536
RUN_SECONDS_MAX = 60
CLEANUP_RESERVE_SECONDS = 2.0


class LaunchDisabled(Exception):
    pass


class StubSpawnError(Exception):
    """Typed spawn/setup failure; handlers are restored before it raises."""

    def __init__(self, reason, original=None):
        super().__init__(reason)
        self.reason = reason
        self.original = original


class ReceiptLateError(ValueError):
    """Late receipt: a durable failure disposition was published instead."""

    def __init__(self, reason, disposition_path=None):
        super().__init__(reason)
        self.reason = reason
        self.disposition_path = disposition_path


def _sha256(path):
    digest = hashlib.sha256()
    with open(path, "rb") as stream:
        for chunk in iter(lambda: stream.read(65536), b""):
            digest.update(chunk)
    return digest.hexdigest()


def _git_checked(*args, timeout=10.0):
    proc = subprocess.run(["git", "-C", HERE, *args], capture_output=True,
                          text=True, timeout=max(0.1, timeout))
    if proc.returncode != 0:
        raise RuntimeError("git_failed:" + (proc.stderr.strip() or str(proc.returncode)))
    return proc.stdout.strip()


def git_state(timeout=10.0):
    return {"head": _git_checked("rev-parse", "HEAD", timeout=timeout),
            "clean": _git_checked("status", "--porcelain", timeout=timeout) == ""}


def source_identity(deadline=None):
    out = {}
    for name in TRANSITIVE_FILES:
        if deadline is not None and time.monotonic() > deadline:
            raise RuntimeError("budget_exceeded_during_source_identity")
        out[name] = _sha256(os.path.join(HERE, name))
    return out


def execution_identity(argv):
    resolved = argv[0] if os.path.isabs(argv[0]) else shutil.which(argv[0])
    return {
        "argv0": argv[0],
        "resolved": resolved,
        "sha256": _sha256(resolved) if resolved and os.path.isfile(resolved) else None,
        "python_version": platform.python_version(),
    }


def runtime_identity():
    return {
        "executable": sys.executable,
        "executable_sha256": _sha256(sys.executable),
        "version": platform.python_version(),
        "implementation": platform.python_implementation(),
    }


def build_launch_plan(argv):
    if not isinstance(argv, list) or not all(isinstance(item, str) for item in argv):
        raise ValueError("argv_invalid")
    state = git_state()
    return {
        "argv": list(argv),
        "cwd": HERE,
        "execution_authorised": False,
        "runtime": runtime_identity(),
        "sources_sha256": source_identity(),
        "git_head": state["head"],
        "git_clean": state["clean"],
        "limits": {"run_seconds_max_including_cleanup": RUN_SECONDS_MAX,
                   "stream_bytes_max": STREAM_CAP, "workers": 1, "retries": 0},
    }


def launch(argv=None):
    raise LaunchDisabled("launch_disabled: execution_authorised=false")


def _reader(stream, sink):
    kept = bytearray()
    total = 0
    try:
        while True:
            chunk = stream.read(8192)
            if not chunk:
                break
            total += len(chunk)
            if len(kept) < STREAM_CAP:
                kept.extend(chunk[:STREAM_CAP - len(kept)])
    except (OSError, ValueError) as error:
        sink["error"] = type(error).__name__
    sink["data"] = bytes(kept)
    sink["total"] = total
    sink["truncated"] = total > STREAM_CAP
    sink["finished"] = True


def _probe_group(pgid):
    try:
        os.killpg(pgid, 0)
        return False, None
    except ProcessLookupError:
        return True, None
    except PermissionError as exc:
        return False, "group_verify_permission_denied:" + str(exc)


def _verify_group_absent(pgid, timeout=2.0):
    """Poll the owned group probe until absent or the budget expires.

    Group-only scope: no external process-table scan is used, so a scan
    permission denial cannot masquerade as a surviving group, and a
    surviving (possibly zombie) group is never reported absent.
    """
    deadline = time.monotonic() + max(0.0, timeout)
    last_error = None
    while True:
        absent, error = _probe_group(pgid)
        if absent:
            return True, None
        if error is not None:
            # A permission-denied probe (e.g. a zombie already reparented
            # outside the caller's scope) is not proof of presence or
            # absence: keep polling until reaping resolves it or the
            # budget expires, then fail closed with the denial retained.
            last_error = error
        if time.monotonic() >= deadline:
            return False, last_error or "group_members_remain"
        time.sleep(min(0.02, max(0.0, deadline - time.monotonic())))


def run_stub(argv, timeout_seconds=5.0, *, receipt_path=None):
    """Synthetic stub child only. Never used for the scientific report."""
    return supervise_worker(argv, timeout_seconds, receipt_path=receipt_path)


def supervise_worker(argv, timeout_seconds, *, receipt_path=None, run_start=None):
    """Supervise a caller-bound worker. Dispatch authority belongs to the caller."""
    if not isinstance(argv, list) or not argv \
            or not all(isinstance(item, str) for item in argv):
        raise ValueError("argv_invalid")
    if type(timeout_seconds) not in (int, float) or not (
            0 < timeout_seconds <= RUN_SECONDS_MAX - CLEANUP_RESERVE_SECONDS):
        raise ValueError("timeout_invalid")
    signal_state = {"signum": None}
    proc_holder = {}
    old_handlers = {}

    def _signal_handler(signum, frame):
        signal_state["signum"] = signum
        target = proc_holder.get("pgid")
        if target is not None:
            try:
                os.killpg(target, signal.SIGKILL)
            except (ProcessLookupError, PermissionError):
                pass

    try:
        if threading.current_thread() is threading.main_thread():
            for sig in (signal.SIGTERM, signal.SIGHUP):
                old_handlers[sig] = signal.signal(sig, _signal_handler)
        receipt = _run_stub(argv, timeout_seconds, signal_state, proc_holder, run_start)
        if receipt_path is not None:
            try:
                write_receipt_no_clobber(receipt_path, receipt,
                                         observed_signal=lambda: signal_state["signum"])
                receipt["publication_verified"] = True
            except ReceiptLateError as error:
                receipt.update(success=False, publication_failure=error.reason)
        if signal_state["signum"] is not None:
            receipt.update(success=False, terminated_by_signal=signal_state["signum"])
        return receipt
    finally:
        for sig, old in old_handlers.items():
            signal.signal(sig, old)


def _run_stub(argv, timeout_seconds, signal_state, proc_holder, run_start=None):
    # The whole preflight-to-receipt budget starts here, before any
    # git, hashing or runtime identity work. No acceptance grace.
    start = time.monotonic() if run_start is None else run_start
    deadline = start + timeout_seconds
    hard_deadline = deadline + CLEANUP_RESERVE_SECONDS
    before = git_state(timeout=max(0.1, hard_deadline - time.monotonic()))
    sources_before = source_identity(deadline=hard_deadline)
    runtime_before = runtime_identity()
    execution_before = execution_identity(argv)

    def remaining():
        return max(0.0, hard_deadline - time.monotonic())

    if signal_state["signum"] is not None or time.monotonic() >= deadline:
        # Absolute pre-dispatch gate: the child window has already closed,
        # so nothing is spawned and the terminal receipt says so.
        elapsed = time.monotonic() - start
        return {
            "argv": list(argv), "exit_code": None, "timed_out": False,
            "elapsed_seconds": elapsed,
            "within_hard_budget": elapsed <= timeout_seconds
            + CLEANUP_RESERVE_SECONDS,
            "stdout": "", "stderr": "", "stdout_truncated": False,
            "stderr_truncated": False, "stdout_bytes_total": 0,
            "stderr_bytes_total": 0, "child_pid": None,
            "cleanup_scope": "process_group_only; setsid_detached_descendants_out_of_scope",
            "detached_descendants": "not_tracked_out_of_scope",
            "execution_before": execution_before, "execution_after": None,
            "group_verified_absent": True,
            "cleanup_error": ("signal_before_dispatch" if signal_state["signum"] is not None
                              else "budget_exceeded_before_dispatch"),
            "terminated_by_signal": signal_state["signum"],
            "run_start_monotonic": start,
            "run_deadline_monotonic": hard_deadline,
            "git_before": before, "git_after": None,
            "sources_before": sources_before, "sources_after": None,
            "runtime_before": runtime_before, "runtime_after": None,
            "success": False,
        }

    proc = None
    try:
        proc = subprocess.Popen(argv, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, start_new_session=True)
        proc_holder["pgid"] = proc.pid
        pgid = proc.pid
        out_sink, err_sink = {}, {}
        threads = [threading.Thread(target=_reader, args=(proc.stdout, out_sink),
                                    daemon=True),
                   threading.Thread(target=_reader, args=(proc.stderr, err_sink),
                                    daemon=True)]
        for thread in threads:
            thread.start()
    except BaseException as exc:
        if proc is not None:
            try:
                os.killpg(proc.pid, signal.SIGKILL)
            except (ProcessLookupError, PermissionError):
                pass
            finally:
                proc_holder.clear()
            try:
                proc.wait(timeout=remaining())
            except subprocess.TimeoutExpired:
                pass
            for stream in (proc.stdout, proc.stderr):
                if stream is not None:
                    stream.close()
        raise StubSpawnError("spawn_failed", original=exc) from exc
    timed_out = False
    cleanup_error = None
    absent = False
    try:
        try:
            proc.wait(timeout=max(0.0, deadline - time.monotonic()))
        except subprocess.TimeoutExpired:
            timed_out = True
            try:
                os.killpg(pgid, signal.SIGKILL)
            except ProcessLookupError:
                pass
            except PermissionError as exc:
                cleanup_error = "kill_permission_denied:" + str(exc)
            try:
                proc.wait(timeout=remaining())
            except subprocess.TimeoutExpired:
                cleanup_error = (cleanup_error or "") \
                    + "leader_not_reaped_in_reserve"
        # Cleanup/verification BEFORE waiting on inherited pipes, so a
        # descendant holding a descriptor cannot block the hard budget.
        absent, verify_error = _probe_group(pgid)
        if not absent:
            try:
                os.killpg(pgid, signal.SIGKILL)
            except ProcessLookupError:
                absent = True
            except PermissionError as exc:
                if cleanup_error is None:
                    cleanup_error = "kill_permission_denied:" + str(exc)
            if not absent:
                absent, verify_error = _verify_group_absent(
                    pgid, timeout=min(2.0, remaining()))
        if verify_error and cleanup_error is None:
            cleanup_error = verify_error
        for thread in threads:
            thread.join(timeout=remaining())
        if any(thread.is_alive() for thread in threads):
            cleanup_error = (cleanup_error or "") + "pipe_readers_overrun"
    finally:
        # Unconditional owned-group cleanup on every exit path, including
        # exceptions and signal-driven interruption of the waits above.
        try:
            absent_now, _ = _probe_group(pgid)
            if not absent_now:
                try:
                    os.killpg(pgid, signal.SIGKILL)
                except (ProcessLookupError, PermissionError):
                    pass
        except Exception:
            pass
        for stream in (proc.stdout, proc.stderr):
            try:
                if stream is not None:
                    stream.close()
            except Exception:
                pass
        try:
            if proc.poll() is None:
                proc.kill()
                proc.wait(timeout=remaining())
        except (OSError, subprocess.TimeoutExpired):
            cleanup_error = cleanup_error or "leader_cleanup_unverified"
        finally:
            proc_holder.clear()
    after = None
    sources_after = None
    runtime_after = None
    execution_after = None
    if remaining() > 0.05:
        try:
            after = git_state(timeout=min(5.0, remaining()))
            sources_after = source_identity(deadline=hard_deadline)
            runtime_after = runtime_identity()
            execution_after = execution_identity(argv)
        except Exception as exc:
            if cleanup_error is None:
                cleanup_error = "postflight_failed:" + str(exc)
    else:
        cleanup_error = (cleanup_error or "") + "postflight_skipped_budget"
    elapsed = time.monotonic() - start
    exit_code = proc.returncode
    within_budget = elapsed <= timeout_seconds + CLEANUP_RESERVE_SECONDS
    stream_errors = {name: sink.get("error", "reader_unfinished")
                     for name, sink in (("stdout", out_sink), ("stderr", err_sink))
                     if "error" in sink or not sink.get("finished")}
    success = (exit_code == 0 and not timed_out and absent and not stream_errors
               and cleanup_error is None
               and not out_sink.get("truncated") and not err_sink.get("truncated")
               and within_budget
               and after is not None and after["head"] == before["head"]
               and before["clean"] and after["clean"]
               and sources_after == sources_before
               and runtime_after == runtime_before
               and execution_after == execution_before
               and execution_before["sha256"] is not None
               and signal_state["signum"] is None)
    receipt = {
        "argv": list(argv),
        "exit_code": exit_code,
        "timed_out": timed_out,
        "elapsed_seconds": elapsed,
        "within_hard_budget": within_budget,
        "stdout": (out_sink.get("data") or b"").decode("utf-8", "replace"),
        "stderr": (err_sink.get("data") or b"").decode("utf-8", "replace"),
        "stdout_raw": out_sink.get("data", b""),
        "stderr_raw": err_sink.get("data", b""),
        "stream_errors": stream_errors,
        "stdout_truncated": bool(out_sink.get("truncated")),
        "stderr_truncated": bool(err_sink.get("truncated")),
        "stdout_bytes_total": int(out_sink.get("total") or 0),
        "stderr_bytes_total": int(err_sink.get("total") or 0),
        "child_pid": proc.pid,
        "cleanup_scope": "process_group_only; setsid_detached_descendants_out_of_scope",
        "detached_descendants": "not_tracked_out_of_scope",
        "execution_before": execution_before,
        "execution_after": execution_after,
        "group_verified_absent": absent,
        "cleanup_error": cleanup_error,
        "terminated_by_signal": signal_state["signum"],
        "run_start_monotonic": start,
        "run_deadline_monotonic": hard_deadline,
        "git_before": before,
        "git_after": after,
        "sources_before": sources_before,
        "sources_after": sources_after,
        "runtime_before": runtime_before,
        "runtime_after": runtime_after,
        "success": success,
    }
    return receipt


def _stage_bytes(directory, encoded):
    for attempt in range(100):
        staging = os.path.join(
            directory, ".receipt-staging-%d-%d" % (os.getpid(), attempt))
        try:
            fd = os.open(staging, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
        except FileExistsError:
            continue
        try:
            view = memoryview(encoded)
            while view:
                written = os.write(fd, view)
                if written <= 0:
                    raise OSError("short_write")
                view = view[written:]
            os.fsync(fd)
        finally:
            os.close(fd)
        return staging
    raise OSError("staging_unavailable")


def _publish_staged(staging, path, encoded):
    os.link(staging, path)  # FileExistsError if the destination exists.
    try:
        with open(path, "rb") as stream:
            published = stream.read(STREAM_CAP + 1)
        if published != encoded:
            raise OSError("publication_verification_failed")
    finally:
        try:
            os.unlink(staging)
        except FileNotFoundError:
            pass


def write_receipt_no_clobber(path, receipt, deadline=None, *, observed_signal=lambda: None):
    """Retain a provisional receipt and check the live outcome after publication."""
    effective_deadline = receipt.get("run_deadline_monotonic")
    if deadline is not None:
        effective_deadline = deadline if effective_deadline is None else min(deadline, effective_deadline)
    child_success = receipt.get("success") is True
    if child_success and effective_deadline is None:
        raise ValueError("receipt_deadline_missing")
    stored = dict(receipt, success=False, child_success=child_success,
                  receipt_state="provisional" if child_success else "failed")
    raw_streams = {}
    for name in ("stdout", "stderr"):
        raw = stored.pop(name + "_raw", None)
        if raw is None:
            if stored.get(name) or stored.get(name + "_bytes_total"):
                raise ValueError("raw_stream_missing")
            raw = b""
        if type(raw) is not bytes or len(raw) > STREAM_CAP:
            raise ValueError("raw_stream_invalid")
        raw_streams[name] = raw
        stored[name] = raw.decode("utf-8", "replace")[:1024]
        stored[name + "_sha256"] = hashlib.sha256(raw).hexdigest()
        stored[name + "_bytes_retained"] = len(raw)
    path = os.fspath(path)
    if os.path.lexists(path):
        raise FileExistsError(path)
    directory = os.path.dirname(os.path.abspath(path))

    def encode(record):
        raw = json.dumps(record, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8")
        if len(raw) > STREAM_CAP:
            raise ValueError("receipt_too_large")
        return raw

    def publish(destination, raw):
        staging = _stage_bytes(directory, raw)
        try:
            _publish_staged(staging, destination, raw)
        finally:
            try:
                os.unlink(staging)
            except FileNotFoundError:
                pass

    def failure_reason():
        sig = observed_signal()
        if sig is not None:
            return f"signal_{sig}"
        if effective_deadline is not None and time.monotonic() >= effective_deadline:
            return "budget_exceeded_after_receipt"
        return None

    encoded = encode(stored)

    def publish_failure(destination, reason):
        disposition = {
            "kind": "stub_receipt_failure", "success": False, "reason": reason,
            "original_success": child_success, "original_receipt_sha256": hashlib.sha256(encoded).hexdigest(),
            "run_deadline_monotonic": effective_deadline, "argv": receipt.get("argv"),
            "exit_code": receipt.get("exit_code"), "cleanup_error": receipt.get("cleanup_error"),
            "stream_errors": stored.get("stream_errors", {}),
            "streams_retained": retained,
        }
        publish(destination, encode(disposition))
        raise ReceiptLateError(reason, disposition_path=destination)

    retained = {}
    for name, raw in raw_streams.items():
        reason = failure_reason()
        if reason is not None:
            publish_failure(path, reason)
        sidecar = path + "." + name + ".bin"
        publish(sidecar, raw)
        retained[name] = {"file": os.path.basename(sidecar),
                          "bytes": len(raw), "sha256": stored[name + "_sha256"]}
    stored["streams_retained"] = retained
    encoded = encode(stored)
    reason = failure_reason()
    if reason is not None:
        publish_failure(path, reason)
    publish(path, encoded)
    reason = failure_reason()
    if reason is not None:
        publish_failure(path + ".failure.json", reason)
    return len(encoded)


def main(argv=None):
    raise SystemExit("launch_disabled: execution_authorised=false")


if __name__ == "__main__":
    main()
