"""Input binding for the PF-002 reference-gain study, version 1.

Virtual lab - simulated experiment tooling. This holds the deterministic union
of scientific and tooling inputs, and the checks at the real execution boundary.
Names are relative, so a record carries no machine path.
"""

import hashlib
import os
from pathlib import Path
import subprocess

OWN = (
    "PF002_REFERENCE_GAIN_V1.md", "pf002-reference-gain-v1-protocol.json",
    "pf002_reference_gain_v1.py", "pf002_reference_gain_bounds_v1.py",
    "pf002_reference_gain_oracle_v1.py", "pf002_reference_gain_deadline_v1.py",
    "pf002_reference_gain_inputs_v1.py")
# Every input the reviewed stationarity study binds, its protocol included.
INHERITED = (
    "pf002_stationarity_v1.py", "pf002_stationarity_bounds_v1.py",
    "pf002_stationarity_oracle_v1.py", "pf002_stationarity_deadline_v1.py",
    "PF002_STATIONARITY_V1.md", "pf002-stationarity-v1-protocol.json",
    "pf002_robustness_deadline_v1.py", "coupled_differential_optical_v2.py",
    "differential_instrument.py", "trial_detector.py",
    "detector_qualification.py", "detector_stability.py",
    "virtual_instruments.py", "recoil_budget.py", "optical_driver.py",
    "optical_reference.py")
# Imported by those inputs but absent from the reviewed list. A test keeps the
# union complete. The reviewed list itself is released and stays as it is.
TRANSITIVE = ("virtual_acquisition.py", "virtual_campaign.py",
              "whole_acquisition.py")
INPUTS = tuple(sorted(set(OWN) | set(INHERITED) | set(TRANSITIVE)))
GIT_SECONDS = 30


class BindingFailure(Exception):
    """The source state does not match the record about to be made."""


def digests(directory, names=INPUTS):
    """Hashes by relative name, in sorted order, so records stay deterministic."""
    directory = Path(directory)
    result = {}
    for name in sorted(names):
        if Path(name).name != name:
            raise BindingFailure(f"input name is not relative: {name}")
        try:
            result[name] = ("sha256:"
                            + hashlib.sha256((directory/name).read_bytes()).hexdigest())
        except OSError as error:
            raise BindingFailure(f"input unreadable: {name}") from error
    return result


def _git(root, *arguments):
    environment = dict(os.environ, GIT_OPTIONAL_LOCKS="0", GIT_NO_LAZY_FETCH="1")
    try:
        return subprocess.run(
            ["git", "-c", "protocol.allow=never", *arguments], cwd=root,
            capture_output=True, text=True, timeout=GIT_SECONDS, check=True,
            env=environment).stdout
    except (OSError, subprocess.SubprocessError) as error:
        raise BindingFailure(f"git {arguments[0]} failed") from error


def head_commit(root):
    return _git(root, "rev-parse", "HEAD").strip()


def assert_clean_commit(root, commit):
    head = head_commit(root)
    if head != commit:
        raise BindingFailure("commit does not match HEAD")
    if _git(root, "status", "--porcelain"):
        raise BindingFailure("the tree has changes")


def open_boundary(root, directory, commit, names=INPUTS):
    """Before any science runs: clean HEAD, then input hashes."""
    assert_clean_commit(root, commit)
    return digests(directory, names)


def close_boundary(root, directory, commit, opened, names=INPUTS):
    """After the run: the same clean HEAD and the same input bytes."""
    assert_clean_commit(root, commit)
    if digests(directory, names) != opened:
        raise BindingFailure("an input changed during the run")


def bound_run(root, directory, commit, runner, names=INPUTS):
    """Run under the boundary. The runner receives the hashes it must record."""
    opened = open_boundary(root, directory, commit, names)
    result = runner(opened)
    close_boundary(root, directory, commit, opened, names)
    return result
