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

Virtual lab - simulated experiment tooling. Supervision, process tracking and
cleanup are the reviewed reference-gain wrapper's own, unchanged. Only the
study, its limits and its version name differ.
"""

import json
import os
from pathlib import Path
import sys

import pf002_identifiability_inputs_v1 as inputs
import pf002_reference_gain_deadline_v1 as supervisor

VERSION = "pf002-identifiability-deadline-v1"
ROOT = Path(__file__).resolve().parent
STUDY = ROOT/"pf002_identifiability_v1.py"
PROTOCOL = ROOT/"pf002-identifiability-v1-protocol.json"
MODES = supervisor.MODES
GRACE_SECONDS = supervisor.GRACE_SECONDS
KILL_SECONDS = supervisor.KILL_SECONDS
# Manifests name this wrapper. The reviewed module reads this one global.
supervisor.VERSION = VERSION
run = supervisor.run


def limits():
    declared = json.loads(PROTOCOL.read_text(encoding="utf-8"))["limits"]
    # Cleanup is part of the declared limit, 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 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_identifiability_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())
