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

Virtual lab - simulated experiment tooling. This reuses the reviewed robustness
supervisor unchanged, so session isolation, process-tree cleanup, no-clobber
output, manifests and exit statuses are the same. Its manifest therefore names
that supervisor's version. Only the study, protocol and hash seed differ.
"""

import json
import os
from pathlib import Path
import subprocess
import sys

from pf002_robustness_deadline_v1 import (
    GRACE_SECONDS, KILL_SECONDS, MODES, run)

ROOT = Path(__file__).resolve().parent
STUDY = ROOT/"pf002_stationarity_v1.py"
BOUNDS = ROOT/"pf002_stationarity_bounds_v1.py"
PROTOCOL = ROOT/"pf002-stationarity-v1-protocol.json"


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 source_commit():
    """Commit of a clean tree. A retained record never comes from changes."""
    root = ROOT.parent.parent
    changes = subprocess.run(
        ["git", "status", "--porcelain"], cwd=root, capture_output=True,
        text=True, timeout=30, check=True).stdout
    if changes:
        raise ValueError("refusing to run: the tree has changes")
    return subprocess.run(
        ["git", "rev-parse", "HEAD"], cwd=root, capture_output=True, text=True,
        timeout=30, check=True).stdout.strip()


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_stationarity_deadline_v1.py "
              "exploratory|confirmatory OUTPUT", file=sys.stderr)
        return 2
    seconds, max_bytes = limits()
    os.environ["PYTHONHASHSEED"] = "0"
    try:
        commit = source_commit()
    except (OSError, ValueError, subprocess.SubprocessError) as error:
        print(error, file=sys.stderr)
        return 2
    try:
        manifest = run(study_command(arguments[0], commit), arguments[1],
                       seconds=seconds, max_bytes=max_bytes,
                       cwd=ROOT.parent.parent,
                       sources=(STUDY, BOUNDS, 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())
