"""External deadline wrapper for the PF-002 mechanism hypotheses 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, its modes and its version name differ. The protocol goes through the
study's own strict parser at this launch boundary. The deterministic primary is
refused here while the protocol does not authorise it.
"""

import hashlib
import json
import os
from pathlib import Path
import sys

import pf002_mechanism_inputs_v1 as inputs
import pf002_mechanism_protocol_v1 as rules
import pf002_reference_gain_deadline_v1 as supervisor

VERSION = "pf002-mechanism-deadline-v1"
ROOT = Path(__file__).resolve().parent
STUDY = ROOT/"pf002_mechanism_hypotheses_v1.py"
PROTOCOL = ROOT/rules.PROTOCOL_FILE
MODES = ("fixture", "deterministic_primary")
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 primary_authorised(protocol=None):
    protocol = rules.load_protocol(PROTOCOL) if protocol is None else protocol
    return rules.primary_authorised(protocol)


def limits(mode, protocol=None):
    protocol = rules.load_protocol(PROTOCOL) if protocol is None else protocol
    return rules.launch_limits(protocol, mode, GRACE_SECONDS, KILL_SECONDS)


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 launch_hash():
    """Hash of this wrapper's whole argument vector. Records hold no path."""
    vector = list(getattr(sys, "orig_argv", [sys.executable, *sys.argv]))
    return hashlib.sha256(json.dumps(vector, separators=(",", ":")).encode("utf-8")).hexdigest()


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


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_mechanism_deadline_v1.py "
              "fixture|deterministic_primary OUTPUT", file=sys.stderr)
        return 2
    try:
        protocol = rules.load_protocol(PROTOCOL)
        declared = limits(arguments[0], protocol)
    except (OSError, ValueError) as error:
        print(f"protocol refused: {error}", file=sys.stderr)
        return 2
    if arguments[0] == "deterministic_primary" and not primary_authorised(protocol):
        print("execution is not authorised by the protocol", file=sys.stderr)
        return 3
    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, launch_hash()), 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())
