"""Python 3.11+, standard library only. Offline harness simulation, NOT Jev.
No network, shell execution, real code edits, GPU or model benchmark.
Run: python3 lab.py
"""
from dataclasses import dataclass
from hashlib import sha256
import json
import math
import sqlite3

@dataclass(frozen=True)
class Chunk:
    id: str
    revision: str
    text: str
    tokens: int  # Synthetic fixture sizes, not a tokenizer measurement.
    utility: float
    mandatory: bool = False


def select(chunks, budget):
    if budget < 0 or len({c.id for c in chunks}) != len(chunks):
        raise ValueError("invalid budget or duplicate chunk")
    if any(c.tokens <= 0 or not math.isfinite(c.utility) for c in chunks):
        raise ValueError("invalid chunk")
    pinned = [c for c in chunks if c.mandatory]
    left = budget - sum(c.tokens for c in pinned)
    if left < 0:
        raise ValueError("mandatory evidence exceeds budget")
    result = pinned[:]
    # A transparent greedy heuristic; not an optimal dependency-aware solver.
    for c in sorted((c for c in chunks if not c.mandatory),
                    key=lambda c: (-c.utility / c.tokens, c.id)):
        if c.tokens <= left:
            result.append(c)
            left -= c.tokens
    return result


def validate_answer(answer):
    if not isinstance(answer, dict) or set(answer) != {"choice", "probabilities"}:
        raise ValueError("invalid answer schema")
    p = answer["probabilities"]
    if not isinstance(p, dict) or set(p) != {"local", "frontier", "review"}:
        raise ValueError("unknown candidates")
    if any(type(x) not in (int, float) or not math.isfinite(x) or not 0 <= x <= 1
           for x in p.values()) or not math.isclose(sum(p.values()), 1.0, abs_tol=1e-8):
        raise ValueError("invalid probabilities")
    if answer["choice"] not in p or p[answer["choice"]] != max(p.values()):
        raise ValueError("choice does not match maximum")
    return p


def choose_route(answer, action, policy):
    # These are typed fixture actions. No shell-string safety claims.
    if action not in policy["allowed_actions"]:
        return "deny"
    try:
        p = validate_answer(answer)
    except ValueError:
        return "review"
    target = answer["choice"]
    if target not in policy["eligible_routes"] or p[target] < policy["threshold"]:
        return "review"
    return target


def record(db, state, action, policy, answer):
    # Identity includes all decision inputs, not just an action name.
    payload = json.dumps([state, action, policy, answer], sort_keys=True,
                         separators=(",", ":"), allow_nan=False)
    key = sha256(payload.encode()).hexdigest()
    existing = db.execute("SELECT result FROM events WHERE id=?", (key,)).fetchone()
    if existing:
        return existing[0], True
    result = choose_route(answer, action, policy)
    with db:
        db.execute("INSERT INTO events VALUES (?, ?, ?)", (key, payload, result))
    return result, False


def run():
    policy = {"version": "policy-1", "allowed_actions": ["inspect", "propose_patch"],
              "eligible_routes": ["local", "frontier", "review"], "threshold": 0.9}
    chunks = [Chunk("policy", "r1", "Keep retry cap; do not deploy.", 40, 1, True),
              Chunk("assertion", "r1", "Expected at most three attempts.", 60, 1, True),
              Chunk("implementation", "r1", "Current retry loop.", 120, 0.96),
              Chunk("old_chat", "r0", "Superseded discussion.", 400, 0.1)]
    chosen = select(chunks, 240)
    assert [x.id for x in chosen] == ["policy", "assertion", "implementation"]
    try:
        select(chunks, 99)
    except ValueError:
        pass
    else:
        raise AssertionError("must reject missing mandatory evidence")
    state = {"task": "retry-incident", "revision": "r1", "question_version": "q1",
             "chunks": [c.__dict__ for c in chosen]}
    good = {"choice": "local", "probabilities": {"local": 0.94, "frontier": 0.04, "review": 0.02}}
    low = {"choice": "local", "probabilities": {"local": 0.55, "frontier": 0.4, "review": 0.05}}
    malformed = {"choice": "delete_production", "probabilities": {"other": 1.0}}
    # In-memory SQLite tests replay logic without leaving personal data behind.
    with sqlite3.connect(":memory:") as db:
        db.execute("CREATE TABLE events (id TEXT PRIMARY KEY, payload TEXT, result TEXT)")
        assert record(db, state, "inspect", policy, good) == ("local", False)
        assert record(db, state, "inspect", policy, good) == ("local", True)
        assert record(db, state, "inspect", policy, low)[0] == "review"
        assert record(db, state, "inspect", policy, malformed)[0] == "review"
        assert record(db, state, "deploy", policy, good)[0] == "deny"
        changed = dict(state, revision="r2")
        assert record(db, changed, "inspect", policy, good) == ("local", False)
        count = db.execute("SELECT COUNT(*) FROM events").fetchone()[0]
        assert count == 5
    n, p = 3, 0.8
    confidence = (p - 1/n) / (1 - 1/n)
    speedup = 1 / (0.8 + 0.2/200)
    assert math.isclose(confidence, 0.7)
    # Synthetic binary forecasts; Brier is not measured on Jev.
    forecasts, outcomes = [0.9, 0.8, 0.4, 0.1], [1, 0, 1, 0]
    brier = sum((p-y)**2 for p, y in zip(forecasts, outcomes)) / len(outcomes)
    print(json.dumps({"mode": "offline_fixture_not_jev", "network_calls": 0,
                      "selected_chunks": [x.id for x in chosen], "audit_rows": count,
                      "choice_confidence": round(confidence, 6),
                      "synthetic_task_speedup": round(speedup, 6),
                      "synthetic_brier": round(brier, 6),
                      "replay_schema_policy_revision_checks": "passed"}, indent=2))

if __name__ == "__main__":
    run()
