"""One-shot activation path for C3-S revision 2, gated by a local release."""

from fractions import Fraction
import hashlib
import json
import math
import os
from pathlib import Path
import subprocess
import sys

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))

import pf002_c3_completion_activate_v1 as bindings
import pf002_c3_completion_report_v2 as report
import pf002_c3_completion_supervisor_v1 as supervisor

REVIEWED_BASE = "9f48c81789049074194fbee8a179a2a26d6b9272"
RUN_DIRECTORY = "pf002-c3-completion-v2-single-run"
RELEASE_NAME = "pf002-c3-completion-v2-release.json"
PLAN_CAP = bindings.PLAN_CAP
RESERVE = bindings.CLEANUP_RESERVE
PARENT_FILES = {
    "launch.json": "93bdca72ed1c68ec2bc3e17a5845c716ec81261612a4bbbafa7881a0c417574d",
    "plan.json": "59e4f8e3747c8bc01b9addf52bf322ee1709807af22ef96ee177f145be1d3338",
    "receipt.json": "1c567cc1d2b733354f09c5e5e8daad038c9eb167fd8d80cf5f9eac94ce9d755a",
    "report.json": "ff712e64736004a3d521065d21399eeb786c131dc1f5f3f29925c802fa781ee7",
    "terminal.json": "9123b85d4ab3c436ca72c8abcf0ecfa0b0816e563724794ecae797fa3443144c",
    "worker-start.json": "fe1b67248e70f09a574102eaf352ae1de9be62d62977c447127dfc68cbe7793f",
    "stdout.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "stderr.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
}


def _digest(data):
    return hashlib.sha256(data).hexdigest()


def _read(path, limit):
    if path.is_symlink() or not path.is_file():
        raise ValueError("missing_or_indirect_file")
    return bindings._bounded_read(path, limit)


def _command():
    return [sys.executable, "-I", "-B", str(Path(__file__).resolve())]


def build_plan(clock):
    revision, _ = report._load_protocol()
    frozen = supervisor.build_launch_plan(clock)
    limits = revision["limits"]
    if (not frozen["git_clean_before"] or frozen["enabled"]
            or revision["execution_authorised"] is not False
            or revision["fixture_verification_authorised"] is not False
            or revision["authorised_modes"] != []
            or limits["report_seconds_including_cleanup"] != supervisor.TOTAL_DEADLINE
            or limits["stream_bytes_each"] != supervisor.STREAM_CAP
            or (limits["workers"], limits["retries"]) != (1, 0)):
        raise ValueError("frozen_launch_state")
    head = frozen["git_head_before"]
    sources = dict(frozen["source_sha256"])
    for name in ("pf002_c3_completion_activate_v1.py",
                 "pf002_c3_completion_report_v2.py",
                 "pf002-c3-completion-v2-protocol.json",
                 "PF002_C3_COMPLETION_V2_PLAN.md"):
        sources[name] = supervisor.sha_file(HERE / name, clock)
    bindings._git(clock, "merge-base", "--is-ancestor", REVIEWED_BASE, head)
    bindings._git(clock, "diff", "--quiet", REVIEWED_BASE, head, "--", *sorted(sources))
    common = Path(bindings._git(clock, "rev-parse", "--path-format=absolute", "--git-common-dir")).resolve()
    old_slot = common / bindings.RUN_DIRECTORY
    if old_slot.is_symlink() or not old_slot.is_dir():
        raise ValueError("parent_slot_missing")
    for name, expected in PARENT_FILES.items():
        clock.timeout(supervisor.TOTAL_DEADLINE)
        if _digest(_read(old_slot / name, limits["record_bytes"])) != expected:
            raise ValueError("parent_evidence_drift")
    path = common / RUN_DIRECTORY
    return {
        "schema": "pf002-c3-completion-v2-activation-plan/1",
        "reviewed_base": REVIEWED_BASE, "git_head": head,
        "source_sha256": sources, "runtime": frozen["runtime"],
        "runtime_sha256": frozen["executable_sha256"],
        "activation_sha256": supervisor.sha_file(__file__, clock),
        "supervisor_argv": _command(),
        "worker_argv": [*_command(), "--worker", str(path)],
        "output": str(path), "release": str(common / RELEASE_NAME),
        "parent_evidence_sha256": PARENT_FILES,
        "revision_protocol_sha256": report.PROTOCOL_SHA256,
        "parent_protocol_sha256": revision["parent_protocol_sha256"],
        "sampling": revision["sampling"], "limits": limits,
        "cleanup_reserve_seconds": RESERVE,
    }


def _release_bytes(plan, plan_sha):
    return bindings._json_bytes({"schema": "pf002-c3-completion-v2-release/1",
                                "plan_sha256": plan_sha, "git_head": plan["git_head"],
                                "authorised_runs": 1})


def _release_digest(plan, plan_sha):
    raw = _read(Path(plan["release"]), 4096)
    if raw != _release_bytes(plan, plan_sha):
        raise ValueError("release_binding")
    return _digest(raw)


def _provenance(plan, plan_sha):
    return {"git_head": plan["git_head"], "runtime": plan["runtime"],
            "source_sha256": json.dumps(plan["source_sha256"], sort_keys=True),
            "runtime_sha256": plan["runtime_sha256"],
            "activation_sha256": plan["activation_sha256"], "plan_sha256": plan_sha,
            "worker_argv_sha256": _digest(bindings._json_bytes(plan["worker_argv"]))}


def _worker(output, clock):
    if not output.is_absolute() or output.name != RUN_DIRECTORY or output.is_symlink():
        raise ValueError("worker_output")
    raw = _read(output / "plan.json", PLAN_CAP)
    plan, sha = json.loads(raw), _digest(raw)
    launch = json.loads(_read(output / "launch.json", PLAN_CAP))
    argv = [*_command(), "--worker", str(output)]
    if (launch["supervisor_pid"] != os.getppid() or launch["plan_sha256"] != sha
            or plan["output"] != str(output) or plan["worker_argv"] != argv
            or sys.orig_argv[1:] != argv[1:] or plan["runtime"] != sys.version):
        raise ValueError("worker_binding")
    started = launch["clock_started_monotonic"]
    if type(started) is not float or not math.isfinite(started) or not 0 < started <= clock.start:
        raise ValueError("worker_clock_binding")
    clock.start = started
    if bindings._json_bytes(build_plan(clock)) != raw:
        raise ValueError("worker_plan_drift")
    if _release_digest(plan, sha) != launch["release_sha256"]:
        raise ValueError("worker_release_drift")
    clock.timeout(supervisor.TOTAL_DEADLINE, RESERVE)
    supervisor._publish_receipt(output, "worker-start.json", {
        "pid": os.getpid(), "ppid": os.getppid(), "started_utc": bindings._utc(),
        "argv": argv, "invoked_argv": sys.orig_argv, "plan_sha256": sha})
    data = report.build_report_record(report.checker.evaluate_report_rows(), _provenance(plan, sha))
    clock.timeout(supervisor.TOTAL_DEADLINE, RESERVE)
    report.parent_report.write_record_no_clobber(output / "report.json", data)


def _rational_vector(values, width):
    if type(values) is not list or len(values) != width:
        raise ValueError("sample_width")
    for value in values:
        if (type(value) is not str or len(value) > 160
                or not report.parent_report._RATIONAL.fullmatch(value)
                or str(Fraction(value)) != value):
            raise ValueError("sample_rational")


def _sample_counts(name, row, spec):
    sampled = row["sampled"]
    fields = report.VELOCITY_FIELDS if name == "VS8" else report.CURVATURE_FIELDS
    points = sampled["points"]
    required = spec["points_per_check"]
    distinct = required if name == "VS11" else spec["distinct_projected_assignments"]
    if (sampled["fields"] != list(fields) or type(points) is not list
            or len(points) != required or sampled["point_count"] != required
            or sampled["required_points"] != required
            or type(row["symbolic_outcome"]) is not bool
            or type(sampled["distinct_valid_inputs"]) is not int
            or not 0 <= sampled["distinct_valid_inputs"] <= distinct):
        raise ValueError("sample_binding")
    counts = dict(passed=0, mismatched=0, refused=0)
    for index, point in enumerate(points):
        state = point["status"]
        if type(point["index"]) is not int or point["index"] != index or state not in counts:
            raise ValueError("sample_index_or_status")
        counts[state] += 1
        if state == "refused":
            if point.keys() != {"index", "status", "reason"} or point["reason"] not in {
                "non_rational_input", "off_chart", "off_unit_circle", "nonpositive_hbar",
                "non_rational_result_or_shape", "zero_divisor",
            }:
                raise ValueError("sample_refusal_binding")
            continue
        required_keys = {"index", "status", "values"}
        if state == "mismatched":
            required_keys.add("expected_values")
            _rational_vector(point["expected_values"], len(fields))
            if point["values"] == point["expected_values"]:
                raise ValueError("sample_false_mismatch")
        if point.keys() != required_keys:
            raise ValueError("sample_witness_keys")
        _rational_vector(point["values"], len(fields))
    if (sampled["counts"].keys() != counts.keys()
            or any(type(sampled["counts"][k]) is not int for k in counts)
            or sampled["counts"] != counts):
        raise ValueError("sample_count_binding")
    passed = row["symbolic_outcome"] and (
        counts == dict(passed=required, mismatched=0, refused=0)
        and sampled["distinct_valid_inputs"] == distinct)
    if row["outcome"] is not passed:
        raise ValueError("sample_outcome_binding")
    return counts


def _unique_pairs(items):
    result = {}
    for key, value in items:
        if key in result:
            raise ValueError("duplicate_report_key")
        result[key] = value
    return result


def _refuse_constant(_):
    raise ValueError("nonfinite_report_value")


def _inspect_report(output, plan, sha, pid, clock):
    clock.timeout(supervisor.TOTAL_DEADLINE)
    start = json.loads(_read(output / "worker-start.json", PLAN_CAP))
    if (start["pid"] != pid or start["ppid"] != os.getpid() or start["plan_sha256"] != sha
            or start["argv"] != plan["worker_argv"]
            or start["invoked_argv"][1:] != plan["worker_argv"][1:]):
        raise ValueError("worker_start_binding")
    raw = _read(output / "report.json", plan["limits"]["record_bytes"])
    value = json.loads(raw, object_pairs_hook=_unique_pairs, parse_constant=_refuse_constant)
    if (value["study"] != "pf002-c3-completion-v2-formal-algebra"
            or value["interpretation"] != "formal_algebra_only_no_physical_inference"
            or value["partial"] is not False or value["provenance"] != _provenance(plan, sha)
            or value["revision_protocol_sha256"] != plan["revision_protocol_sha256"]
            or value["parent_protocol_sha256"] != plan["parent_protocol_sha256"]
            or set(value["checks"]) != set(report.parent_report.FROZEN_CHECKS)
            or any(type(row["outcome"]) is not bool for row in value["checks"].values())
            or report.parent_report._nodes(value) > plan["limits"]["record_nodes"]):
        raise ValueError("report_binding")
    for name, row in value["checks"].items():
        if (row["guard"] != list(report.checker.CHECK_GUARDS[name])
                or not report.parent_report._matches(row["quantity"], report.parent_report._WITNESSES[name])):
            raise ValueError("symbolic_witness_binding")
    sampled = {name: _sample_counts(name, value["checks"][name], plan["sampling"])
               for name in report.SAMPLED}
    clock.timeout(supervisor.TOTAL_DEADLINE)
    return {"bytes": len(raw), "sha256": _digest(raw), "checks": len(value["checks"]),
            "sampled": sampled}


def _run(approved_sha, clock):
    plan = build_plan(clock)
    raw = bindings._json_bytes(plan)
    sha = _digest(raw)
    if approved_sha != sha or len(raw) > PLAN_CAP:
        raise ValueError("activation_plan_digest")
    release_sha = _release_digest(plan, sha)
    supervisor._ps_table(clock)
    clock.timeout(supervisor.TOTAL_DEADLINE, RESERVE)
    output = Path(plan["output"])
    output.mkdir(mode=0o700)
    report.parent_report.write_record_no_clobber(output / "plan.json", raw)
    launch = {"plan_sha256": sha, "release_sha256": release_sha,
              "supervisor_pid": os.getpid(), "parent_pid": os.getppid(),
              "argv": [*plan["supervisor_argv"], "--run", sha], "invoked_argv": sys.orig_argv,
              "started_utc": bindings._utc(), "clock_started_monotonic": clock.start}
    supervisor._publish_receipt(output, "launch.json", launch)
    record = {"launch": launch}

    def postflight(shared_clock):
        after = build_plan(shared_clock)
        match = after == plan and _release_digest(after, sha) == release_sha
        result = {"before_after_match": match,
                  "git_head_after": after["git_head"], "source_sha256_after": after["source_sha256"],
                  "runtime_sha256_after": after["runtime_sha256"],
                  "activation_sha256_after": after["activation_sha256"],
                  "parent_evidence_sha256_after": after["parent_evidence_sha256"]}
        if match and record["child_success"]:
            result["report"] = _inspect_report(output, plan, sha, record["child_pid"], shared_clock)
        return result

    interrupted = None
    try:
        supervisor.supervise(plan["worker_argv"], HERE, output, record, clock,
                             reserve=RESERVE, postflight=postflight)
    except supervisor.SupervisorSignal as error:
        interrupted = error.signum
    candidate = bool(record.pop("success", False) and record.get("after", {}).get("report"))
    state = "provisional" if candidate and clock.remaining() > 0 else "failed"
    supervisor._publish_receipt(output, "terminal.json", {
        "state": state, "plan_sha256": sha, "supervisor_pid": os.getpid(),
        "supervision": record, "terminal_snapshot_utc": bindings._utc(),
        "elapsed_seconds_before_terminal_write": clock.elapsed()})
    if clock.remaining() <= 0:
        supervisor._retain_publication_failure(output, dict(record, deadline_exceeded=True))
        return 1
    if interrupted is not None:
        return 128 + interrupted
    return 0 if state == "provisional" else 1


def main(argv):
    clock = supervisor.Clock(supervisor.TOTAL_DEADLINE)
    if not sys.flags.isolated or not sys.dont_write_bytecode:
        return 2
    try:
        if argv == ["--plan"]:
            plan = build_plan(clock)
            sys.stdout.buffer.write(bindings._json_bytes({
                "plan": plan, "plan_sha256": _digest(bindings._json_bytes(plan))}))
        elif len(argv) == 2 and argv[0] == "--run":
            if sys.orig_argv[1:] != [*_command()[1:], *argv]:
                raise ValueError("supervisor_argv_binding")
            return _run(argv[1], clock)
        elif len(argv) == 2 and argv[0] == "--worker":
            _worker(Path(argv[1]), clock)
        else:
            return 2
    except (OSError, ValueError, KeyError, TypeError, TimeoutError, subprocess.SubprocessError) as error:
        sys.stderr.write(f"C3-S revision 2 activation refused or failed: {error}\n")
        return 2
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
