"""Local review worksheet for the documented rollout contract, not a Chio CLI.

The example counts are synthetic. Passing this worksheet neither authenticates
the supplied measurements nor records a signed promotion in a runtime.
"""
from copy import deepcopy
import json


ZERO_SIGNALS = (
    "unsigned_or_stale_manifest_accepted", "adapter_declaration_loss",
    "hidden_store_error", "fail_closed_case_allowed", "late_event_entering_match",
    "state_eviction_without_health", "untrusted_executable_finding",
    "truncated_executable_plan", "production_decoy_false_positive",
    "canary_reaching_fake_server", "response_double_apply_or_remove",
    "lifted_with_reversible_contribution", "rollback_conflict_reported_clean",
    "receipt_state_contradiction",
)


def review(record, registered_attacks, required_recovery):
    integers = ("consecutive_days", "invocations", "authority_resets", "unknown_labels",
                "unknown_labels_reviewed", "reviewed_findings", "correct_findings")
    for name in integers:
        if type(record[name]) is not int or record[name] < 0:
            raise ValueError("invalid count: " + name)
    for name in ZERO_SIGNALS:
        if type(record["zero_signals"][name]) is not int or record["zero_signals"][name] < 0:
            raise ValueError("invalid signal: " + name)
    if record["unknown_labels"] > record["invocations"] or record["correct_findings"] > record["reviewed_findings"]:
        raise ValueError("numerator exceeds population")
    failed = []
    if record["complete_window"] is not True or record["authority_resets"]:
        failed.append("continuous window after the last authority reset")
    if not ((record["consecutive_days"] >= 14 and record["invocations"] >= 100_000)
            or record["consecutive_days"] >= 30):
        failed.append("shadow duration and invocation population")
    failed += [name for name in ZERO_SIGNALS if record["zero_signals"][name] != 0]
    if (record["invocations"] == 0 or 10_000 * record["unknown_labels"] > record["invocations"]
            or record["unknown_labels_reviewed"] != record["unknown_labels"]):
        failed.append("unknown-label rate and complete review")
    if record["reviewed_findings"] < 1_000 or 100 * record["correct_findings"] < 99 * record["reviewed_findings"]:
        failed.append("finding precision and minimum review population")
    for suite, expected in (("registered_attacks", registered_attacks),
                            ("required_recovery_cases", required_recovery)):
        cases = record[suite]
        if not expected or set(cases) != set(expected) or any(value is not True for value in cases.values()):
            failed.append(suite)
    if record["authority_ready"] is not True:
        failed.append("durable authority readiness")
    if not all(record["identity_bindings"].get(name) for name in (
            "cohort", "policy", "manifests", "rules", "classifier", "runtime_build", "evidence_window")):
        failed.append("complete release identity binding")
    return failed


if __name__ == "__main__":
    fixture = {
        "consecutive_days": 14, "invocations": 120_000, "authority_resets": 0,
        "complete_window": True, "unknown_labels": 3, "unknown_labels_reviewed": 3,
        "reviewed_findings": 1_000, "correct_findings": 995,
        "zero_signals": {name: 0 for name in ZERO_SIGNALS},
        "registered_attacks": {"credential-egress": True, "wrong-producer": True},
        "required_recovery_cases": {"overlap": True, "stale-fence": True,
                                    "restart": False, "out-of-order-expiry": True, "store-outage": True},
        "authority_ready": True,
        "identity_bindings": {name: "fixture-" + name for name in (
            "cohort", "policy", "manifests", "rules", "classifier", "runtime_build", "evidence_window")},
    }
    # In production these sets come from the independent registered test suite,
    # not from whatever case names the measurement record happens to contain.
    attacks = {"credential-egress", "wrong-producer"}
    recovery = {"overlap", "stale-fence", "restart", "out-of-order-expiry", "store-outage"}
    assert review(fixture, attacks, recovery) == ["required_recovery_cases"]
    print("HOLD worksheet: required_recovery_cases (restart observation missing)")
    repaired = deepcopy(fixture)
    repaired["required_recovery_cases"]["restart"] = True
    assert review(repaired, attacks, recovery) == []
    print("REVIEW complete worksheet: no failing checks; signed operator promotion still required")
    small = deepcopy(repaired)
    small["reviewed_findings"], small["correct_findings"] = 200, 199
    assert "finding precision and minimum review population" in review(small, attacks, recovery)
    print("HOLD worksheet: 99.5 percent across 200 reviews does not meet the sample minimum")
    print(json.dumps(fixture, indent=2, sort_keys=True))
