"""Exact teaching arithmetic, not a cache or reproduction of a prototype."""
from fractions import Fraction
import json
from pathlib import Path
import sys

def number(value, name):
    if isinstance(value, bool) or not isinstance(value, (int, Fraction)):
        raise ValueError(name + " must be an integer or exact Fraction")
    return Fraction(value)

def update_cost(previous, observation, weight):
    previous = number(previous, "previous")
    observation = number(observation, "observation")
    weight = number(weight, "weight")
    if previous < 0 or observation < 0 or not 0 <= weight <= 1:
        raise ValueError("nonnegative costs and weight in [0,1] required")
    return (1 - weight) * previous + weight * observation

def score(frequency, cost):
    frequency = number(frequency, "frequency")
    cost = number(cost, "cost")
    if frequency < 0 or cost < 0:
        raise ValueError("nonnegative frequency and cost required")
    return frequency * cost

def lowest(scores):
    if not scores:
        raise ValueError("nonempty candidate set required")
    checked = {k: number(v, "score") for k, v in scores.items()}
    if any(v < 0 for v in checked.values()):
        raise ValueError("nonnegative scores required")
    minimum = min(checked.values())
    return sorted(k for k, v in checked.items() if v == minimum)

def results():
    before = {"A": score(2, 8), "B": score(1, 20)}
    estimate = update_cost(8, 32, Fraction(1, 4))
    after = {"A": score(2, estimate), "B": before["B"]}
    return {
        "schema_version": 1,
        "kind": "constructed exact arithmetic",
        "generated": "2026-11-19",
        "method": "c_new=(1-alpha)*c_old+alpha*sample; priority=frequency*class_cost",
        "units": {"frequency": "accesses/s", "class_cost": "ms/fill", "priority": "ms/s"},
        "assumptions": [
            "Two equal-size evaluated residents, not a full cache or global minimum.",
            "Frequencies and resident identities remain fixed during the update.",
            "The new fill observation belongs to another object in A's class.",
            "Weight 1/4 is illustrative, not inferred from the author prototype.",
            "Scores are estimated cost-weighted frequencies, not measured saved time.",
        ],
        "inputs": {
            "frequencies": {"A": "2", "B": "1"},
            "initial_costs": {"A": "8", "B": "20"},
            "new_sample_A": "32", "new_sample_weight": "1/4",
        },
        "updated_cost_A": str(estimate),
        "before": {"scores": {k: str(v) for k, v in before.items()}, "lowest": lowest(before)},
        "after": {"scores": {k: str(v) for k, v in after.items()}, "lowest": lowest(after)},
        "paper": "https://www.usenix.org/system/files/conference/atc17/atc17-blankstein.pdf",
        "code": "https://hesela.dev/research/cache-cost-class/model.py",
    }

def main():
    if sys.argv[1:] not in ([], ["--check"]):
        raise SystemExit("usage: model.py [--check]")
    expected = json.dumps(results(), indent=2) + "\n"
    path = Path(__file__).with_name("results.json")
    if sys.argv[1:]:
        if path.read_text() != expected:
            raise SystemExit("Generated result drift")
        print("Exact result matches")
    else:
        path.write_text(expected)

if __name__ == "__main__":
    main()
