"""External deadline wrapper for the PF-002 robustness study, version 1.

Virtual lab - simulated experiment tooling. The frozen study declares a one
hour runtime limit that its own source does not enforce. Those source bytes are
hashed into retained records, so the limit is enforced here instead. This file
is not an implementation input of retained version 1 records.

A run writes OUTPUT.partial, OUTPUT.stderr and OUTPUT.run.json without
clobbering anything. Only exit 0 with output promotes the partial file to
OUTPUT, and only after its manifest is written. Timeout, refusal, child failure,
wrapper I/O failure, leftover processes and cleanup failure stay visible as
their own status and exit status, and keep whatever partial bytes reached disk.
Once a child exists, process cleanup and descriptor closure always run, and
cleanup that cannot be verified is reported as unverified.
"""

import hashlib
import json
import os
from pathlib import Path
import selectors
import signal
import subprocess
import sys
import time

VERSION = "pf002-robustness-deadline-v1"
ROOT = Path(__file__).resolve().parent
STUDY = ROOT/"pf002_mechanistic_robustness_v1.py"
PROTOCOL = ROOT/"pf002-mechanistic-robustness-v1-protocol.json"
MODES = ("exploratory", "confirmatory")
GRACE_SECONDS = 5.0
KILL_SECONDS = 5.0
SCAN_SECONDS = 1.0
DRAIN_SECONDS = 1.0
PS_SECONDS = 5.0
CHUNK_BYTES = 65536
EXIT_STATUS = {"completed": 0, "no_output": 120, "operational_failure": 121,
               "cleanup_failed": 122, "orphaned_processes": 123,
               "timeout": 124, "output_limit": 125}


def _failure(stage, error):
    return {"stage": stage, "type": type(error).__name__,
            "errno": getattr(error, "errno", None)}


def _read(descriptor):
    return os.read(descriptor, CHUNK_BYTES)


def _table():
    """Return {pid: (ppid, pgid, start)} for live, non-zombie processes."""
    done = subprocess.run(
        ["ps", "-Ao", "pid=,ppid=,pgid=,stat=,lstart="], check=True,
        capture_output=True, text=True, timeout=PS_SECONDS)
    table = {}
    for line in done.stdout.splitlines():
        pid, ppid, pgid, state, start = line.split(None, 4)
        if not state.startswith("Z"):
            table[int(pid)] = (int(ppid), int(pgid), start)
    return table


def _track(root, tracked, scan_state):
    """Remember descendants, so one that leaves the session is still found."""
    try:
        table = _table()
    except (OSError, ValueError, subprocess.SubprocessError):
        scan_state["failures"] += 1
        return
    parents = {root}|{pid for pid, start in tracked.items()
                      if pid in table and table[pid][2] == start}
    changed = True
    while changed:
        changed = False
        for pid, row in table.items():
            if row[0] in parents and pid not in parents:
                parents.add(pid)
                changed = True
    parents.discard(os.getpid())
    for pid in parents:
        if pid in table:
            tracked[pid] = table[pid][2]


def _remaining(root, tracked, scan_state):
    try:
        table = _table()
    except (OSError, ValueError, subprocess.SubprocessError):
        scan_state["failures"] += 1
        return None
    found = {pid for pid, row in table.items() if row[1] == root}
    found |= {pid for pid, start in tracked.items()
              if pid in table and table[pid][2] == start}
    found.discard(os.getpid())
    return found


def _signal(pids, number):
    for pid in pids:
        try:
            os.kill(pid, number)
        except OSError:
            pass


def _fallback(child, grace):
    """Signal the known child and group when processes cannot be enumerated.

    Tracked descendants are not signalled, because a pid cannot be matched to
    its start time without enumeration. The caller reports this as unverified.
    """
    for number, seconds in ((signal.SIGTERM, grace),
                            (signal.SIGKILL, KILL_SECONDS)):
        try:
            os.killpg(child.pid, number)
        except OSError:
            pass
        try:
            child.send_signal(number)
            child.wait(timeout=seconds)
        except (OSError, subprocess.TimeoutExpired):
            pass


def _cleanup(child, tracked, grace, scan_state):
    """Terminate the group and tracked descendants; report what happened."""
    root = child.pid
    _track(root, tracked, scan_state)
    child.poll()
    found = _remaining(root, tracked, scan_state)
    if found is None:
        _fallback(child, grace)
        return {"terminated": 0, "survivors": None, "fallback": True}
    terminated = set(found)
    for number, seconds in ((signal.SIGTERM, grace),
                            (signal.SIGKILL, KILL_SECONDS)):
        limit = time.monotonic()+seconds
        _signal(found, number)
        while found and time.monotonic() < limit:
            time.sleep(0.02)
            child.poll()
            found = _remaining(root, tracked, scan_state)
            if found is None:
                _fallback(child, grace)
                return {"terminated": len(terminated), "survivors": None,
                        "fallback": True}
            terminated |= found
    return {"terminated": len(terminated), "survivors": len(found),
            "fallback": False}


def _contain(child, tracked, grace, scan_state, failures):
    """Stop and reap the child. Nothing raised here hides the first failure."""
    try:
        cleanup = _cleanup(child, tracked, grace, scan_state)
    except Exception as error:
        failures.append(_failure("cleanup", error))
        _fallback(child, grace)
        cleanup = {"terminated": 0, "survivors": None, "fallback": True}
    try:
        child.wait(timeout=KILL_SECONDS)
    except Exception as error:
        failures.append(_failure("reap", error))
    return cleanup


def _close(selector, child, failures):
    items = [] if selector is None else [selector]
    if child is not None:
        items += [child.stdout, child.stderr]
    for item in items:
        try:
            item.close()
        except Exception as error:
            failures.append(_failure("close", error))


def _exit_status(status, child_exit):
    if status in EXIT_STATUS:
        return EXIT_STATUS[status]
    if status.startswith("interrupted:"):
        return 128+int(status.split(":")[1])
    return 128-child_exit if child_exit < 0 else child_exit


def _hash(path):
    return "sha256:"+hashlib.sha256(Path(path).read_bytes()).hexdigest()


def run(command, output, *, seconds, max_bytes, grace=GRACE_SECONDS,
        cwd=None, sources=()):
    """Run command under a deadline. Return the manifest it also writes."""
    if seconds <= 0 or max_bytes <= 0 or grace < 0:
        raise ValueError("deadline limits must be positive")
    output = Path(output)
    partial = output.with_name(output.name+".partial")
    errors = output.with_name(output.name+".stderr")
    manifest_path = output.with_name(output.name+".run.json")
    for path in (output, partial, errors, manifest_path):
        if os.path.lexists(path):
            raise FileExistsError(f"refusing to replace {path.name}")
    manifest = None
    try:
        with open(partial, "xb") as sink, open(errors, "xb") as error_sink:
            manifest = _supervise(command, sink, error_sink, seconds,
                                  max_bytes, grace, cwd)
    except OSError as error:
        if manifest is None:
            raise
        manifest["failures"].append(_failure("flush", error))
    failures = manifest["failures"]
    manifest.update(stdout_bytes=None, stdout_sha256=None, stderr_bytes=None,
                    sources={})
    try:
        manifest["stdout_bytes"] = partial.stat().st_size
        manifest["stdout_sha256"] = _hash(partial)
        manifest["stderr_bytes"] = errors.stat().st_size
        manifest["sources"] = {Path(path).name: _hash(path)
                               for path in sources}
    except OSError as error:
        failures.append(_failure("inspect", error))
    if manifest["status"] == "exited" and manifest["child_exit"] == 0:
        if failures:
            manifest["status"] = "operational_failure"
        elif manifest["stdout_bytes"] == 0:
            manifest["status"] = "no_output"
        else:
            manifest["status"] = "completed"
    manifest["promoted"] = False
    if manifest["status"] == "completed":
        try:
            os.link(partial, output)
            manifest["promoted"] = True
        except OSError as error:
            failures.append(_failure("promote", error))
            manifest["status"] = "operational_failure"
    manifest["exit_status"] = _exit_status(manifest["status"],
                                           manifest["child_exit"])
    manifest["manifest_written"] = True
    try:
        with open(manifest_path, "x", encoding="utf-8") as sink:
            json.dump(manifest, sink, sort_keys=True, indent=2)
            sink.write("\n")
    except Exception as error:
        _manifest_failed(manifest, output, error)
        return manifest
    if manifest["promoted"]:
        try:
            partial.unlink()
        except OSError as error:
            print(f"partial file kept: {type(error).__name__}", file=sys.stderr)
    return manifest


def _manifest_failed(manifest, output, error):
    """Keep the first failure; a record without a manifest is not promoted."""
    manifest["manifest_written"] = False
    manifest["failures"].append(_failure("manifest", error))
    if manifest["promoted"]:
        manifest["status"] = "operational_failure"
        manifest["exit_status"] = EXIT_STATUS["operational_failure"]
        try:
            output.unlink()
            manifest["promoted"] = False
        except OSError as unlink_error:
            manifest["failures"].append(_failure("demote", unlink_error))
    print(json.dumps({"manifest_written": False,
                      "status": manifest["status"],
                      "exit_status": manifest["exit_status"],
                      "failures": manifest["failures"]}, sort_keys=True),
          file=sys.stderr)


def _pump(child, selector, sink, error_sink, deadline, max_bytes, stopped,
          tracked, scan_state):
    """Stream child output until a terminal status. May raise on I/O failure."""
    streams = ((child.stdout, sink), (child.stderr, error_sink))
    written = {}
    for stream, target in streams:
        written[target] = 0
        os.set_blocking(stream.fileno(), False)
        selector.register(stream, selectors.EVENT_READ, target)
    status, next_scan, drain_until = None, 0.0, None
    while status is None:
        now = time.monotonic()
        if stopped:
            status = f"interrupted:{stopped[0]}"
        elif now >= deadline:
            status = "timeout"
        if now >= next_scan and status is None:
            _track(child.pid, tracked, scan_state)
            next_scan = now+SCAN_SECONDS
        if selector.get_map():
            events = selector.select(0.05)
        else:
            events = []
            time.sleep(0.02)
        for key, _ in events:
            chunk = _read(key.fd)
            if not chunk:
                selector.unregister(key.fileobj)
                continue
            room = max_bytes-written[key.data]
            key.data.write(chunk[:room])
            written[key.data] += min(room, len(chunk))
            if len(chunk) > room:
                status = "output_limit"
        if status is None and child.poll() is not None:
            if not selector.get_map():
                status = "exited"
            elif drain_until is None:
                drain_until = time.monotonic()+DRAIN_SECONDS
            elif time.monotonic() >= drain_until and not events:
                status = "exited"
    return status


def _supervise(command, sink, error_sink, seconds, max_bytes, grace, cwd):
    stopped = []
    def stop(number, _frame):
        stopped.append(number)
    handled = (signal.SIGTERM, signal.SIGINT, signal.SIGHUP)
    previous = {number: signal.signal(number, stop) for number in handled}
    started = time.monotonic()
    child, selector, status = None, None, None
    tracked, scan_state, failures = {}, {"failures": 0}, []
    cleanup = {"terminated": 0, "survivors": 0, "fallback": False}
    try:
        try:
            child = subprocess.Popen(
                command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
                stderr=subprocess.PIPE, start_new_session=True, cwd=cwd)
            selector = selectors.DefaultSelector()
            status = _pump(child, selector, sink, error_sink, started+seconds,
                           max_bytes, stopped, tracked, scan_state)
        except Exception as error:
            failures.append(_failure("supervise", error))
            status = "operational_failure"
    finally:
        try:
            if child is not None:
                cleanup = _contain(child, tracked, grace, scan_state, failures)
            _close(selector, child, failures)
        finally:
            for number, handler in previous.items():
                signal.signal(number, handler)
    supervision_status = status
    child_exit = None if child is None else child.returncode
    verified = cleanup["survivors"] == 0 and (
        child is None or child_exit is not None)
    if not verified:
        status = "cleanup_failed"
    elif status == "exited" and cleanup["terminated"]:
        status = "orphaned_processes"
    return {
        "wrapper": VERSION,
        "environment": "Virtual lab - simulated experiment",
        "status": status, "supervision_status": supervision_status,
        "child_exit": child_exit, "failures": failures,
        "deadline_seconds": seconds, "grace_seconds": grace,
        "elapsed_seconds": round(time.monotonic()-started, 3),
        "maximum_output_bytes": max_bytes,
        "processes_terminated": cleanup["terminated"],
        "process_survivors": cleanup["survivors"],
        "cleanup_verified": verified,
        "cleanup_fallback": cleanup["fallback"],
        "process_scan_failures": scan_state["failures"],
    }


def limits():
    declared = json.loads(PROTOCOL.read_text(encoding="utf-8"))["limits"]
    # Cleanup is part of the declared hour, so it starts early enough to fit.
    seconds = declared["maximum_runtime_seconds"]-GRACE_SECONDS-KILL_SECONDS
    return seconds, declared["maximum_retained_bytes"]


def study_command(mode):
    return [sys.executable, "-B", str(STUDY), mode]


def main(arguments=None):
    arguments = sys.argv[1:] if arguments is None else arguments
    if len(arguments) != 2 or arguments[0] not in MODES:
        print("usage: pf002_robustness_deadline_v1.py "
              "exploratory|confirmatory OUTPUT", file=sys.stderr)
        return 2
    seconds, max_bytes = limits()
    try:
        manifest = run(study_command(arguments[0]), arguments[1],
                       seconds=seconds, max_bytes=max_bytes,
                       cwd=ROOT.parent.parent, sources=(STUDY, PROTOCOL))
    except FileExistsError as error:
        print(error, file=sys.stderr)
        return 2
    print(json.dumps({key: manifest[key] for key in (
        "status", "exit_status", "elapsed_seconds", "stdout_bytes")},
        sort_keys=True))
    return manifest["exit_status"]


if __name__ == "__main__":
    raise SystemExit(main())
