"""Deterministic reliability, release, and incident drills; no network."""
import argparse
import copy
import json


class Clock:
    def __init__(self):
        self.now = 0

    def advance(self, milliseconds):
        self.now += milliseconds


def lesson1():
    clock = Clock()
    deadline = 100
    attempts = 0
    failures = 0
    breaker = "closed"
    while attempts < 3 and clock.now + 40 <= deadline and breaker == "closed":
        attempts += 1
        clock.advance(40)
        failures += 1
        if failures == 2:
            breaker = "open"
    assert attempts == 2 and clock.now == 80 and breaker == "open"
    result = {"answer": None, "status": "evidence_unavailable"}
    assert result["answer"] is None
    # A separate worker lane still executes an independent authorization check.
    assert {"alice": "reader"}.get("alice") == "reader"
    print(json.dumps({"simulated_ms": clock.now, "attempts": attempts, "breaker": breaker, "result": result}))


GOOD = dict(code="c1", prompt="p1", model="fixture-m1", index="i1", policy="acl1", schema=1)


def checks(release):
    return {"answer": release["index"] == "i1", "authorization": release["policy"] == "acl1",
            "compatible_schema": release["schema"] == 1}


def lesson2():
    active = copy.deepcopy(GOOD)
    candidate = dict(GOOD, index="i-bad")
    assert not all(checks(candidate).values())
    assert active == GOOD  # Gate rejection never promoted candidate.
    active = candidate  # Explicit simulated accidental activation for recovery drill.
    active = copy.deepcopy(GOOD)
    assert all(checks(active).values()) and active == GOOD
    incompatible = dict(GOOD, schema=2)
    assert not checks(incompatible)["compatible_schema"]
    print(json.dumps({"candidate_gate": checks(candidate), "restored": active, "post_rollback": checks(active)}))


def lesson3():
    timeline = []
    clock = Clock()
    state = {"release": "bad", "accepting": True, "effects": {"op-1": "committed"}}
    def event(name):
        timeline.append({"simulated_ms": clock.now, "event": name})
        clock.advance(10)
    event("detect: req-2 missing evidence")
    state["accepting"] = False
    event("contain: pause affected route")
    # Reconcile committed effect before deciding whether to retry it.
    assert state["effects"]["op-1"] == "committed"
    event("reconcile: op-1 already committed, do not repeat")
    state["release"] = "good"
    assert all(checks(GOOD).values())
    event("verify: answer and denial fixtures passed")
    state["accepting"] = True
    event("resume")
    assert state["accepting"] and len(state["effects"]) == 1
    print(json.dumps({"simulated_timeline": timeline, "state": state}, indent=2))


if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--lesson", choices=["1", "2", "3", "all"], default="all")
    a = p.parse_args()
    for n, fn in enumerate((lesson1, lesson2, lesson3), 1):
        if a.lesson in (str(n), "all"):
            fn()
