"""Replay the fictional long-document pricing study using Python's standard library."""
import argparse
import hashlib
import json
from pathlib import Path

HERE = Path(__file__).resolve().parent


def price_call(label, input_tokens, output_tokens, fixture):
    tier = "ordinary" if input_tokens <= fixture["ordinary_input_limit"] else "long"
    prices = fixture["rates_usd_per_million"][tier]
    # One USD per million tokens equals one microdollar per token.
    return {
        "call": label,
        "input_tokens": input_tokens,
        "output_tokens": output_tokens,
        "tier": tier,
        "micro_usd": input_tokens * prices["input"] + output_tokens * prices["output"],
    }


def scenario(calls):
    return {"calls": calls, "total_micro_usd": sum(row["micro_usd"] for row in calls)}


def replay(fixture):
    parts = fixture["source_tokens_by_part"]
    document = sum(parts)
    wrapper = fixture["instructions_per_call"]
    extract = fixture["extract_output_per_part"]
    answer = fixture["answer_output"]
    full = price_call("full document", document + wrapper, answer, fixture)
    extracts = [
        price_call(f"extract {index}", length + wrapper, extract, fixture)
        for index, length in enumerate(parts, 1)
    ]
    join_base = wrapper + len(parts) * extract

    def joined(reread):
        join = price_call("join", join_base + reread, answer, fixture)
        return scenario([*extracts, join])

    # Scan every feasible whole-token reread. Keep the transition and its neighbours.
    reread_costs = [joined(n)["total_micro_usd"] for n in range(document + 1)]
    first_higher = next((n for n, cost in enumerate(reread_costs) if cost > full["micro_usd"]), None)
    checkpoints = {0, document}
    if first_higher is not None:
        checkpoints.update([max(0, first_higher - 1), first_higher])
    threshold = fixture["ordinary_input_limit"]
    return {
        "scenarios": {
            "full": scenario([full]),
            "extracts_only": scenario(extracts),
            "join_extracts": joined(0),
            "join_with_full_reread": joined(document),
        },
        "reread_lengths_evaluated": len(reread_costs),
        "first_reread_above_full_cost_tokens": first_higher,
        "reread_sensitivity": [
            {"reread_tokens": n, **joined(n)} for n in sorted(checkpoints)
        ],
        "essay_examples": {
            "at_boundary": scenario([price_call("call", threshold, 500, fixture)]),
            "above_boundary": scenario([price_call("call", threshold + 1, 500, fixture)]),
            "equal_lengths": scenario([price_call(label, threshold, 500, fixture) for label in ("A", "B")]),
            "straddling_lengths": scenario([price_call("A", threshold - 1, 500, fixture),
                                            price_call("B", threshold + 1, 500, fixture)]),
        },
    }


def run():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--check", action="store_true", help="compare with the archived execution record")
    args = parser.parse_args()
    fixture_path = HERE / "fixture.json"
    fixture = json.loads(fixture_path.read_text())
    record = {
        "author": fixture["author"],
        "fixture_date": fixture["date"],
        "scope": "Offline synthetic token arithmetic. Quality and service performance unmeasured.",
        "sha256": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in (fixture_path, Path(__file__).resolve())},
        "results": replay(fixture),
    }
    if args.check:
        saved = json.loads((HERE / "execution-record.json").read_text())
        if record != saved:
            raise SystemExit("Execution record differs from the current fixture or replay.")
        print("Matched every call, price tier, scenario total, crossover and source hash.")
    else:
        print(json.dumps(record, indent=2))


if __name__ == "__main__":
    run()
