"""Evaluation fixtures and actual local tracing. Python standard library only."""
import argparse
import json
import math
import statistics
import time
import uuid


CASES = [
    dict(id="normal", group="a", kind="normal", tool="lookup", args={"item": "A"}, allowed=True, answer="4"),
    dict(id="absent", group="b", kind="unanswerable", tool=None, args={}, allowed=True, answer="unknown"),
    dict(id="private", group="c", kind="unauthorized", tool=None, args={}, allowed=False, answer="denied"),
    dict(id="long", group="d", kind="long-context", tool="lookup", args={"item": "Z"}, allowed=True, answer="9"),
]


def lesson1():
    """Score components separately; predictions are deliberately supplied fixtures."""
    predictions = {c["id"]: dict(tool=c["tool"], args=dict(c["args"]), allowed=c["allowed"], answer=c["answer"]) for c in CASES}
    predictions["long"]["args"] = {"item": "A"}
    rows = []
    for c in CASES:
        p = predictions[c["id"]]
        checks = {k: p[k] == c[k] for k in ("tool", "args", "allowed", "answer")}
        rows.append(dict(id=c["id"], slice=c["kind"], checks=checks, success=all(checks.values())))
    assert sum(r["success"] for r in rows) == 3
    assert rows[-1]["checks"]["tool"] and not rows[-1]["checks"]["args"]
    print(json.dumps({"fixture_only": True, "version": "gold-v1", "cases": rows}, indent=2))


def lesson2():
    """Counterbalanced judge fixture, not a real model or human review."""
    adjudicated = ["A", "B", "A", "B"]
    first_order = ["A", "A", "A", "A"]
    # Swapped judgments are mapped back to original answer identities.
    reversed_order = ["B", "B", "B", "B"]
    agreement = sum(a == b for a, b in zip(adjudicated, first_order)) / len(adjudicated)
    flips = sum(a != b for a, b in zip(first_order, reversed_order))
    assert agreement == .5 and flips == 4
    # An objective citation check rejects an attractive fabricated reference.
    assert "doc-9" not in {"doc-1", "doc-2"}
    print(json.dumps({"judge_fixture_only": True, "reference_agreement": agreement, "order_flips": flips,
                      "conclusion": "Do not use this fixture judge as a release gate."}))


def lesson3():
    spans = []
    for request in range(5):
        trace_id = str(uuid.uuid4())
        for stage in ("retrieval", "model_fixture", "tool"):
            attempts = 2 if request == 4 and stage == "tool" else 1
            for attempt in range(attempts):
                start = time.perf_counter()
                if attempts == 2:
                    time.sleep(.005)  # Explicit controlled delay, not model latency.
                result = sum(range(100))
                spans.append(dict(trace=trace_id, stage=stage, attempt=attempt + 1,
                                  elapsed_ms=(time.perf_counter()-start)*1000, result=result))
    totals = [sum(s["elapsed_ms"] for s in spans if s["trace"] == tid) for tid in dict.fromkeys(s["trace"] for s in spans)]
    tail = sorted(totals)[math.ceil(.95 * len(totals))-1]
    assert len(spans) == 16 and len(totals) == 5
    # Hypothetical prices: never presented as a current provider price.
    estimated = (1000 * 2 + 100 * 6) / 1_000_000
    print(json.dumps({"measured_local_harness_ms": totals, "median_ms": statistics.median(totals),
                      "nearest_rank_p95_ms": tail, "injected_delay_ms": 10,
                      "hypothetical_currency_cost": estimated, "spans": spans}, 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()
