"""Reprice one complete, two-route text-only ledger under the supplied call counts."""
from datetime import datetime, timezone
from hashlib import sha256
import json
from pathlib import Path
import platform

HERE = Path(__file__).resolve().parent
ROUTES = ("economy", "premium")


def nonnegative_integer(value, field):
    if type(value) is not int or value < 0:
        raise ValueError(f"{field} must be a nonnegative integer")
    return value


def cost_micro_usd(call, rate):
    # One USD per million tokens equals one microdollar per token.
    return call["input"] * rate["input"] + call["output"] * rate["output"]


def bounds(ledger):
    rates = ledger["rates_usd_per_million"]
    counts = ledger["observed_calls_by_route"]
    calls = ledger["calls"]
    if set(rates) != set(ROUTES) or set(counts) != set(ROUTES):
        raise ValueError("the ledger requires exactly the two declared routes")
    for route in ROUTES:
        if set(rates[route]) != {"input", "output"}:
            raise ValueError("each route needs both token rates")
        for value in rates[route].values():
            nonnegative_integer(value, "rate")
        nonnegative_integer(counts[route], "route count")
    if len(calls) != sum(counts.values()):
        raise ValueError("route counts must cover the same calls as the ledger")

    known = {route: 0 for route in ROUTES}
    ids = set()
    increments = []
    known_cost = 0
    unknown_at_economy = 0
    for call in calls:
        call_id = call["id"]
        if not isinstance(call_id, str) or not call_id or call_id in ids:
            raise ValueError("each call needs a unique, nonempty identifier")
        ids.add(call_id)
        for field in ("input", "output"):
            nonnegative_integer(call[field], field)
        route = call["route"]
        if route is None:
            economy = cost_micro_usd(call, rates["economy"])
            unknown_at_economy += economy
            increments.append((cost_micro_usd(call, rates["premium"]) - economy, call_id))
        elif route in ROUTES:
            known[route] += 1
            known_cost += cost_micro_usd(call, rates[route])
        else:
            raise ValueError("unknown route label")
    if any(known[route] > counts[route] for route in ROUTES):
        raise ValueError("labelled rows exceed the independent route count")

    premium_slots = counts["premium"] - known["premium"]
    increments.sort()
    baseline = known_cost + unknown_at_economy

    def endpoint(ordered):
        selected = ordered[:premium_slots]
        return {
            "total_micro_usd": baseline + sum(delta for delta, _ in selected),
            "example_premium_ids_among_unlabelled": sorted(call_id for _, call_id in selected),
        }

    return {
        "known_cost_micro_usd": known_cost,
        "unlabelled_calls": len(increments),
        "unlabelled_premium_slots": premium_slots,
        "minimum": endpoint(increments),
        "maximum": endpoint(list(reversed(increments))),
    }


if __name__ == "__main__":
    files = [HERE / "fixture.json", Path(__file__).resolve()]
    print(json.dumps({
        "author": "Anant Mishra",
        "scope": "Synthetic arithmetic for two eligible routes, complete quantities and flat token prices.",
        "executed_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"),
        "python": platform.python_version(),
        "command": "python3 -B replay.py",
        "sha256": {p.name: sha256(p.read_bytes()).hexdigest() for p in files},
        "results": bounds(json.loads(files[0].read_text())),
    }, indent=2))
