"""Reviewable preparation for one C3-S M1 normalized verification report."""

import argparse
import hashlib
import json
import math
import os
import subprocess
from pathlib import Path
import sys
import time

HERE = Path(__file__).resolve().parent
if __name__ == "__main__":
    sys.path.insert(0, str(HERE))

import pf002_c3s_m1_nominal_checker as checker
import pf002_c3s_m1_nominal_oracle as oracle
import pf002_c3s_m1_nominal_supervisor as supervisor

PROTOCOL = "pf002-c3s-m1-nominal-protocol.json"
PROTOCOL_SHA256 = "1b323bc8ceb073ee0eac4cd849de49cf0f5e159bdf108d15f9889196ea045693"
COHORT = (0.01, 0.025, 0.0)
WORKER = "pf002_c3s_m1_nominal_worker_v1.py"
ATTEMPT = "pf002-c3s-m1-normalised-v1-attempt"
KEYS = ("S1", "S2", "A_n_plus", "A_n_minus", "A_n2_plus", "A_n2_minus")


def _encoded(value):
    return (json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n").encode()


def prepare_plan(*, deadline=None):
    """Read the pinned protocol and bind the current clean candidate."""
    deadline = time.monotonic() + 10.0 if deadline is None else deadline

    def git(*args):
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise ValueError("preparation_deadline")
        return subprocess.run(
            ["git", *args], cwd=HERE, capture_output=True,
            check=True, timeout=remaining,
        ).stdout

    with (HERE / PROTOCOL).open("rb") as stream:
        raw = stream.read(checker.PROTOCOL_BYTES_MAX + 1)
    if hashlib.sha256(raw).hexdigest() != PROTOCOL_SHA256:
        raise ValueError("frozen_protocol_mismatch")
    protocol = checker.parse_protocol(raw)
    if tuple(protocol["integrals"]["normalised_kappaL"]) != COHORT:
        raise ValueError("frozen_cohort_mismatch")
    head = git("rev-parse", "--verify", "HEAD").decode("ascii").strip()
    if git("status", "--porcelain=v1", "--untracked-files=all"):
        raise ValueError("source_dirty")
    prefix = git("rev-parse", "--show-prefix").decode().strip()
    sources = {}
    for name in (*supervisor.TRANSITIVE_FILES, Path(__file__).name, WORKER,
                 "PF002_C3S_M1_NOMINAL_ACTIVATION.md"):
        path = HERE / name
        blob = f"{head}:{prefix}{name}"
        size = int(git("cat-file", "-s", blob))
        if path.is_symlink() or not path.is_file() or not 0 <= size <= 65536:
            raise ValueError("source_path_or_size")
        with path.open("rb") as stream:
            data = stream.read(65537)
        if len(data) != size or data != git("cat-file", "blob", blob):
            raise ValueError("source_drift")
        sources[name] = hashlib.sha256(data).hexdigest()
    if sources[PROTOCOL] != PROTOCOL_SHA256:
        raise ValueError("frozen_protocol_mismatch")
    runtime = supervisor.runtime_identity()
    if (git("rev-parse", "--verify", "HEAD").decode("ascii").strip() != head
            or git("status", "--porcelain=v1", "--untracked-files=all")
            or time.monotonic() >= deadline):
        raise ValueError("preparation_not_stable")
    plan = {
        "state": "normalised_single_attempt",
        "execution_authorised": True,
        "protocol_id": protocol["protocol_id"],
        "protocol_sha256": PROTOCOL_SHA256,
        "git": {"head": head, "clean": True},
        "source_sha256": sources,
        "runtime": runtime,
        "scope": "normalised_integrals_and_weighted_areas",
        "cases": [{"kappaL": x, "zero_decay_control": x == 0.0} for x in COHORT],
        "normalisation": {"L": 1.0, "n0": 1.0, "DX": 1.0},
        "tolerances": {key: protocol["integrals"][key] for key in
                       ("S_absolute_tolerance", "area_relative_tolerance")},
        "limits": {**protocol["limits"], "attempts": 1,
                   "cleanup_reserve_seconds": supervisor.CLEANUP_RESERVE_SECONDS},
        "excluded": ["coupling_dependent_nominal_quantities", "instrument_claims"],
        "entry_argv": [str(Path(sys.executable).resolve()), "-I", "-S", "-B",
                       str(Path(__file__).resolve()), "--execute", "PLAN_SHA256"],
        "dispatch": "explicit_reviewed_plan_digest",
        "attempt_name": ATTEMPT,
    }
    return {"plan": plan, "plan_sha256": hashlib.sha256(_encoded(plan)).hexdigest()}


def evaluate_normalised_case(kappa_l):
    """Evaluate a single identity at caller-supplied synthetic or future reviewed input."""
    checked = checker.arm_areas(kappa_l, 1.0, 1.0, 1.0)
    independent = oracle.arm_areas(kappa_l, 1.0, 1.0, 1.0)
    # Reconstruct all four totals from the separately evaluated legs.
    # The oracle's closed paired formula for A_n2 shares Route A algebra.
    for arm in ("plus", "minus"):
        for measure in ("A_n", "A_n2"):
            independent[f"{measure}_{arm}"] = math.fsum(
                leg[measure] for leg in independent["legs"] if leg["arm"] == arm)
    differences = oracle.compare(checked, independent)
    if kappa_l == 0.0:
        exact = (2.0, 2.0, -2.0, 2.0, 0.0, 0.0)
        if tuple(checked[name] for name in KEYS) != exact or tuple(
                independent[name] for name in KEYS) != exact:
            raise oracle.OracleRefusal("zero_decay_control_failed")
    return {"kappaL": kappa_l, "checker": {name: checked[name] for name in KEYS},
            "oracle": {name: independent[name] for name in KEYS},
            "oracle_legs": independent["legs"], "absolute_differences": differences}


def _write_once(path, record):
    raw = _encoded(record)
    if len(raw) > 65536:
        raise ValueError("record_cap")
    staging = supervisor._stage_bytes(path.parent, raw)
    try:
        supervisor._publish_staged(staging, path, raw)
    finally:
        try:
            os.unlink(staging)
        except FileNotFoundError:
            pass
    return hashlib.sha256(raw).hexdigest()


def run_worker(attempt, plan_digest, deadline):
    rows = []
    # Checkpoint each completed case. A refusal ends this single attempt.
    for index, kappa_l in enumerate(COHORT):
        if time.monotonic() >= deadline:
            raise TimeoutError("worker_deadline")
        row = evaluate_normalised_case(kappa_l)
        _write_once(attempt / f"case-{index}.json", row)
        rows.append(row)
    _write_once(attempt / "report.json", {
        "mode": "normalised_integrals_and_weighted_areas",
        "execution_environment": "virtual_lab_simulated_experiment",
        "plan_sha256": plan_digest, "protocol_sha256": PROTOCOL_SHA256, "rows": rows,
    })
    return 0 if time.monotonic() < deadline else 2


def _report_hash(attempt, plan_digest):
    with (attempt / "report.json").open("rb") as stream:
        raw = stream.read(65537)
    if len(raw) > 65536:
        raise ValueError("record_cap")
    record = json.loads(raw)
    if _encoded(record) != raw or record.get("mode") != "normalised_integrals_and_weighted_areas":
        raise ValueError("record_identity")
    if record.get("plan_sha256") != plan_digest or record.get("protocol_sha256") != PROTOCOL_SHA256:
        raise ValueError("record_provenance")
    rows = record["rows"]
    if (set(record) != {"mode", "execution_environment", "plan_sha256", "protocol_sha256", "rows"}
            or record["execution_environment"] != "virtual_lab_simulated_experiment"
            or tuple(row["kappaL"] for row in rows) != COHORT
            or any(type(row["kappaL"]) is not float for row in rows)):
        raise ValueError("record_case_coverage")
    for index, row in enumerate(rows):
        expected = _encoded(row)
        with (attempt / f"case-{index}.json").open("rb") as stream:
            if stream.read(65537) != expected:
                raise ValueError("checkpoint_mismatch")
        if (set(row) != {"kappaL", "checker", "oracle", "oracle_legs", "absolute_differences"}
                or set(row["checker"]) != set(KEYS) or set(row["oracle"]) != set(KEYS)):
            raise ValueError("record_witness_coverage")
        legs = row["oracle_legs"]
        if [(leg["arm"], leg["leg"], leg["delay"]) for leg in legs] != [
                (arm, leg, float(leg)) for arm in ("plus", "minus") for leg in range(4)]:
            raise ValueError("record_leg_coverage")
        for leg in legs:
            if set(leg) != {"arm", "leg", "delay", "A_n", "A_n2"}:
                raise ValueError("record_leg_fields")
            checker.require_finite(leg["A_n"])
            checker.require_finite(leg["A_n2"])
        for arm in ("plus", "minus"):
            for measure in ("A_n", "A_n2"):
                if row["oracle"][f"{measure}_{arm}"] != math.fsum(
                        leg[measure] for leg in legs if leg["arm"] == arm):
                    raise ValueError("record_leg_sum")
        if row["kappaL"] == 0.0 and tuple(row["checker"][key] for key in KEYS) != (
                2.0, 2.0, -2.0, 2.0, 0.0, 0.0):
            raise ValueError("record_zero_control")
        if oracle.compare(row["checker"], row["oracle"]) != row["absolute_differences"]:
            raise ValueError("record_comparison_mismatch")
    if checker._depth_nodes(record) > 2000:
        raise ValueError("record_nodes")
    return hashlib.sha256(raw).hexdigest()


def execute_once(approved_digest):
    start = time.monotonic()
    hard_deadline = start + 60
    worker_deadline = hard_deadline - supervisor.CLEANUP_RESERVE_SECONDS
    envelope = prepare_plan(deadline=min(start + 10, worker_deadline))
    if approved_digest != envelope["plan_sha256"]:
        raise ValueError("reviewed_plan_mismatch")
    plan = envelope["plan"]
    checkout = subprocess.run(
        ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"], cwd=HERE,
        capture_output=True, text=True, check=True, timeout=2,
    )
    common = Path(checkout.stdout.strip()).resolve(strict=True)
    attempt = common / ATTEMPT
    with (HERE / WORKER).open("rb") as stream:
        bootstrap = stream.read(65537)
    if hashlib.sha256(bootstrap).hexdigest() != plan["source_sha256"][WORKER]:
        raise ValueError("bootstrap_drift")
    argv = [plan["entry_argv"][0], "-I", "-S", "-B", "-c", bootstrap.decode(),
            str(HERE), str(attempt), str(os.getpid()), approved_digest, repr(worker_deadline)]
    if time.monotonic() >= worker_deadline:
        raise TimeoutError("before_attempt_deadline")
    # The fixed git-common-dir path is shared by linked worktrees. Once
    # created, this directory spends the attempt even if later I/O fails.
    attempt.mkdir(mode=0o700)
    terminal = {"success": False, "parent_pid": os.getpid(),
                "plan_sha256": approved_digest}
    try:
        launch_hash = _write_once(attempt / "launch.json", {
            "parent_pid": os.getpid(), "worker_deadline": worker_deadline,
            "start_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "argv": argv, "envelope": envelope,
        })
        terminal["launch_sha256"] = launch_hash
        live = supervisor.supervise_worker(argv, 58, run_start=start,
                                           receipt_path=attempt / "receipt.json")
        terminal.update(child_pid=live["child_pid"], child_exit=live["exit_code"],
                        group_verified_absent=live["group_verified_absent"],
                        detached_descendants=live["detached_descendants"])
        if not live["success"] or not live.get("publication_verified"):
            raise ValueError("supervisor_refused")
        if (live["git_before"] != plan["git"] or live["git_after"] != plan["git"]
                or live["runtime_before"] != plan["runtime"]
                or live["runtime_after"] != plan["runtime"]
                or prepare_plan(deadline=hard_deadline) != envelope):
            raise ValueError("launch_source_drift")
        terminal["report_sha256"] = _report_hash(attempt, approved_digest)
        if time.monotonic() >= hard_deadline:
            raise TimeoutError("terminal_deadline")
        terminal["state"] = "provisional"
        terminal["elapsed_before_publication_seconds"] = time.monotonic() - start
        _write_once(attempt / "terminal.json", terminal)
        if time.monotonic() >= hard_deadline:
            raise TimeoutError("terminal_publication_deadline")
    except Exception as error:
        terminal.update(state="failed", failure=type(error).__name__,
                        elapsed_seconds=time.monotonic() - start)
        _write_once(attempt / "terminal-failure.json", terminal)
        raise
    return {"attempt": str(attempt), "child_exit": terminal["child_exit"],
            "elapsed_seconds": time.monotonic() - start,
            "report_sha256": terminal["report_sha256"]}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    mode = parser.add_mutually_exclusive_group(required=True)
    mode.add_argument("--plan", action="store_true")
    mode.add_argument("--execute", metavar="REVIEWED_PLAN_SHA256")
    args = parser.parse_args()
    if args.execute is not None and (len(args.execute) != 64
            or any(char not in "0123456789abcdef" for char in args.execute)):
        parser.error("execute requires the exact reviewed lowercase SHA-256")
    sys.stdout.buffer.write(_encoded(prepare_plan() if args.plan else execute_once(args.execute)))
    return 0


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