"""Synthetic price traces and cache replay; no model, network or client data.

Run with python3. Prices use integer minor units. The catalog reference is the
expected snapshot at request time, not a current live price. Assertions evaluate
structured claims; this example does not parse or grade arbitrary answer prose.
"""
from copy import deepcopy
import json

REFERENCE = {"sku": "MUG-01", "currency": "GBP", "price_minor": 2400,
             "version": "catalog-v2"}
STALE = dict(REFERENCE, price_minor=1900, version="catalog-v1")


def evaluate(reference, tool, answer):
    keys = ("sku", "currency", "price_minor")
    return {
        "tool_matches_reference": all(tool[k] == reference[k] for k in (*keys, "version")),
        "answer_matches_tool": all(answer[k] == tool[k] for k in keys),
        "answer_matches_reference": all(answer[k] == reference[k] for k in keys),
    }


def claim(payload):
    return {k: payload[k] for k in ("sku", "currency", "price_minor")}


CASES = [
    ("stale_tool_faithful_answer", STALE, claim(STALE), (False, True, False)),
    ("correct_tool_wrong_answer", REFERENCE, claim(STALE), (True, False, False)),
    ("correct_tool_correct_answer", REFERENCE, claim(REFERENCE), (True, True, True)),
    ("stale_tool_correct_answer", STALE, claim(REFERENCE), (False, False, True)),
]


class CatalogLookup:
    """The broken key ignores the requested catalog snapshot."""

    def __init__(self, include_version=False):
        self.include_version = include_version
        self.cache = {}
        self.catalog_reads = 0

    def lookup(self, catalog, sku):
        key = (sku, catalog["version"]) if self.include_version else sku
        if key not in self.cache:
            if catalog["sku"] != sku:
                raise KeyError(sku)
            self.catalog_reads += 1
            self.cache[key] = dict(catalog)
        return dict(self.cache[key])


def replay(include_version):
    lookup = CatalogLookup(include_version)
    lookup.lookup(STALE, "MUG-01")  # Warm the cache before the price change.
    tool = lookup.lookup(REFERENCE, "MUG-01")  # Replay after the change.
    answer = claim(tool)  # Deterministic stand-in for a faithful answer.
    return lookup, tool, evaluate(REFERENCE, tool, answer)


def check_cache_repair():
    broken, _, before = replay(False)
    fixed, tool, after = replay(True)
    if tuple(before.values()) != (False, True, False):
        raise AssertionError(("stale-cache failure did not reproduce", before))
    if tuple(after.values()) != (True, True, True):
        raise AssertionError(("cache repair did not pass", after))
    if (broken.catalog_reads, fixed.catalog_reads) != (1, 2):
        raise AssertionError("repair must fetch the new catalog snapshot")
    # The repaired lookup must still cache repeated requests to the same version.
    fixed.lookup(REFERENCE, "MUG-01")
    if fixed.catalog_reads != 2:
        raise AssertionError("same-version request missed cache")
    # Fetching an older snapshot again must not overwrite the newer cache entry.
    if fixed.lookup(STALE, "MUG-01") != STALE:
        raise AssertionError("snapshot isolation failed")
    if fixed.lookup(REFERENCE, "MUG-01") != REFERENCE:
        raise AssertionError("new snapshot lost after old-snapshot request")
    # A later answer error stays visible even with a repaired lookup.
    wrong_answer = evaluate(REFERENCE, tool, claim(STALE))
    if tuple(wrong_answer.values()) != (True, False, False):
        raise AssertionError(("answer regression hidden", wrong_answer))
    for name, scores in (("cache_before", before), ("cache_after", after),
                         ("answer_regression_after_repair", wrong_answer)):
        print(json.dumps({"case": name, **scores}, sort_keys=True))
    print("PASS: cache failure reproduced, repaired and replayed")


def main():
    for name, tool, answer, expected in CASES:
        scores = evaluate(REFERENCE, tool, answer)
        if tuple(scores.values()) != expected:
            raise AssertionError((name, scores, expected))
        print(json.dumps({"case": name, **scores}, sort_keys=True))
    # A price-only check would miss wrong-product, currency and version errors.
    for key, value in (("sku", "MUG-02"), ("currency", "USD"), ("version", "catalog-v1")):
        wrong = deepcopy(REFERENCE)
        wrong[key] = value
        scores = evaluate(REFERENCE, wrong, claim(wrong))
        if scores["tool_matches_reference"]:
            raise AssertionError(f"missed {key} mismatch")
        if not scores["answer_matches_tool"]:
            raise AssertionError(f"faithfulness misclassified for {key}")
        if scores["answer_matches_reference"] != (key == "version"):
            raise AssertionError(f"reference comparison misclassified for {key}")
    print("PASS: four trace cases and three contract mutations")
    check_cache_repair()


if __name__ == "__main__":
    main()
