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

Virtual lab - simulated experiment tooling. Process tracking and cleanup are the
reviewed robustness supervisor's own helpers, unchanged. Its pump shares one cap
across streams, while this protocol caps stdout and stderr at 64 KiB and the
result at 2 MiB, so the result travels on its own pipe with its own cap.
"""

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

import pf002_reference_gain_inputs_v1 as inputs
import pf002_robustness_deadline_v1 as reviewed

VERSION = "pf002-reference-gain-deadline-v1"
ROOT = Path(__file__).resolve().parent
STUDY = ROOT/"pf002_reference_gain_v1.py"
PROTOCOL = ROOT/"pf002-reference-gain-v1-protocol.json"
MODES = reviewed.MODES
GRACE_SECONDS = reviewed.GRACE_SECONDS
KILL_SECONDS = reviewed.KILL_SECONDS


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_including_cleanup"]
               - GRACE_SECONDS-KILL_SECONDS)
    return {"seconds": seconds, "result": declared["maximum_retained_bytes"],
            "stdout": declared["maximum_stdout_bytes"],
            "stderr": declared["maximum_stderr_bytes"]}


def source_commit(root=ROOT.parent.parent):
    """Commit of a clean tree. A retained record never comes from changes."""
    commit = inputs.head_commit(root)
    inputs.assert_clean_commit(root, commit)
    return commit


def _pump(child, selector, streams, deadline, stopped, tracked, scan_state):
    """Stream every output until a terminal status. May raise on I/O failure."""
    written = {}
    for descriptor, sink, cap in streams:
        written[sink] = 0
        os.set_blocking(descriptor, False)
        selector.register(descriptor, selectors.EVENT_READ, (sink, cap))
    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:
            reviewed._track(child.pid, tracked, scan_state)
            next_scan = now+reviewed.SCAN_SECONDS
        if selector.get_map():
            events = selector.select(0.05)
        else:
            events = []
            time.sleep(0.02)
        for key, _ in events:
            sink, cap = key.data
            chunk = reviewed._read(key.fd)
            if not chunk:
                selector.unregister(key.fileobj)
                continue
            room = cap-written[sink]
            sink.write(chunk[:room])
            written[sink] += 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()+reviewed.DRAIN_SECONDS
            elif time.monotonic() >= drain_until and not events:
                status = "exited"
    return status


def _reap(child, grace, failures):
    """Last resort after containment failed: signal the group and collect it."""
    try:
        reviewed._fallback(child, grace)
        child.wait(timeout=KILL_SECONDS)
    except Exception as error:
        failures.append(reviewed._failure("reap", error))


def _close_streams(selector, child, descriptors, failures):
    try:
        reviewed._close(selector, child, failures)
    finally:
        for descriptor in descriptors:
            try:
                os.close(descriptor)
            except OSError:
                pass


def _supervise(command, sinks, seconds, caps, 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}
    read_end, write_end = None, None
    try:
        try:
            read_end, write_end = os.pipe()
            os.set_inheritable(write_end, True)
            child = subprocess.Popen(
                [*command, "--result-fd", str(write_end)],
                stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
                stderr=subprocess.PIPE, start_new_session=True, cwd=cwd,
                pass_fds=(write_end,))
            os.close(write_end)
            write_end = None
            selector = selectors.DefaultSelector()
            streams = ((read_end, sinks["result"], caps["result"]),
                       (child.stdout.fileno(), sinks["stdout"], caps["stdout"]),
                       (child.stderr.fileno(), sinks["stderr"], caps["stderr"]))
            status = _pump(child, selector, streams, started+seconds, stopped,
                           tracked, scan_state)
        except Exception as error:
            failures.append(reviewed._failure("supervise", error))
            status = "operational_failure"
    finally:
        # A cleanup failure is added beside the first error and never replaces it.
        try:
            if child is not None:
                try:
                    cleanup = reviewed._contain(child, tracked, grace, scan_state,
                                                failures)
                except Exception as error:
                    # Survivors are unknown here, so None and never a count.
                    failures.append(reviewed._failure("contain", error))
                    cleanup = {"terminated": 0, "survivors": None, "fallback": True}
                    _reap(child, grace, failures)
            try:
                _close_streams(selector, child,
                               [d for d in (read_end, write_end) if d is not None],
                               failures)
            except Exception as error:
                failures.append(reviewed._failure("close", error))
        finally:
            for number, handler in previous.items():
                signal.signal(number, handler)
    child_exit = None if child is None else child.returncode
    verified = cleanup["survivors"] == 0 and (
        child is None or child_exit is not None)
    supervision_status = status
    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),
        "caps": dict(caps), "processes_terminated": cleanup["terminated"],
        "process_survivors": cleanup["survivors"], "cleanup_verified": verified,
        "cleanup_fallback": cleanup["fallback"],
        "process_scan_failures": scan_state["failures"]}


def _source_hashes(sources):
    return {Path(path).name: reviewed._hash(path) for path in sources}


def run(command, output, *, seconds, caps, grace=GRACE_SECONDS, cwd=None,
        sources=()):
    """Run command under a deadline. Return the manifest it also writes."""
    if seconds <= 0 or grace < 0 or any(v <= 0 for v in caps.values()):
        raise ValueError("deadline limits must be positive")
    output = Path(output)
    partial = output.with_name(output.name+".partial")
    streams = {"stdout": output.with_name(output.name+".stdout"),
               "stderr": output.with_name(output.name+".stderr")}
    manifest_path = output.with_name(output.name+".run.json")
    for path in (output, partial, *streams.values(), manifest_path):
        if os.path.lexists(path):
            raise FileExistsError(f"refusing to replace {path.name}")
    before = _source_hashes(sources)
    manifest = None
    try:
        with open(partial, "xb") as result, open(
                streams["stdout"], "xb") as out, open(
                    streams["stderr"], "xb") as err:
            manifest = _supervise(
                command, {"result": result, "stdout": out, "stderr": err},
                seconds, caps, grace, cwd)
    except OSError as error:
        if manifest is None:
            raise
        manifest["failures"].append(reviewed._failure("flush", error))
    failures = manifest["failures"]
    manifest.update(result_bytes=None, result_sha256=None, sources={})
    try:
        manifest["result_bytes"] = partial.stat().st_size
        manifest["result_sha256"] = reviewed._hash(partial)
        manifest["stdout_bytes"] = streams["stdout"].stat().st_size
        manifest["stderr_bytes"] = streams["stderr"].stat().st_size
        manifest["sources"] = _source_hashes(sources)
        if manifest["sources"] != before:
            failures.append({"stage": "sources", "error": "input changed during run"})
    except OSError as error:
        failures.append(reviewed._failure("inspect", error))
    if manifest["status"] == "exited" and manifest["child_exit"] == 0:
        if failures:
            manifest["status"] = "operational_failure"
        elif manifest["result_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(reviewed._failure("promote", error))
            manifest["status"] = "operational_failure"
    manifest["exit_status"] = reviewed._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:
        reviewed._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 study_command(mode, commit):
    return [sys.executable, "-B", str(STUDY), mode, "--commit", commit]


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_reference_gain_deadline_v1.py "
              "exploratory|confirmatory OUTPUT", file=sys.stderr)
        return 2
    declared = limits()
    seconds = declared.pop("seconds")
    os.environ["PYTHONHASHSEED"] = "0"
    try:
        commit = source_commit()
    except inputs.BindingFailure as error:
        print(error, file=sys.stderr)
        return 2
    try:
        manifest = run(study_command(arguments[0], commit), arguments[1],
                       seconds=seconds, caps=declared, cwd=ROOT.parent.parent,
                       sources=[ROOT/name for name in inputs.INPUTS])
    except FileExistsError as error:
        print(error, file=sys.stderr)
        return 2
    print(json.dumps({key: manifest.get(key) for key in (
        "status", "exit_status", "elapsed_seconds", "result_bytes")},
        sort_keys=True))
    return manifest["exit_status"]


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