"""A minimal LLM gateway: routing, retries with backoff, fallback, JSON checks, cost ledger.

Runs offline against a fake backend; swap FakeBackend for a real client to use it.
"""
from __future__ import annotations

import json
import random
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Callable, Protocol


class QuotaExceeded(Exception):
    """Stands in for HTTP 429 RESOURCE_EXHAUSTED."""


@dataclass(frozen=True)
class Reply:
    text: str
    input_tokens: int
    output_tokens: int


class Backend(Protocol):
    def generate(self, model: str, prompt: str) -> Reply: ...


@dataclass(frozen=True)
class Route:
    """Ordered model targets for one feature: the first is preferred, the rest are fallbacks."""
    feature: str
    models: tuple[str, ...]
    required_keys: tuple[str, ...] = ()


@dataclass
class Ledger:
    """Token and cost totals per feature, from a price table in USD per million tokens."""
    prices: dict[str, tuple[float, float]]
    totals: dict[str, list[float]] = field(default_factory=lambda: defaultdict(lambda: [0, 0, 0.0]))

    def record(self, feature: str, model: str, reply: Reply) -> None:
        price_in, price_out = self.prices[model]
        row = self.totals[feature]
        row[0] += reply.input_tokens
        row[1] += reply.output_tokens
        row[2] += (reply.input_tokens * price_in + reply.output_tokens * price_out) / 1e6


@dataclass
class Gateway:
    backend: Backend
    ledger: Ledger
    max_attempts: int = 3  # two retries, as the platform's error guide recommends
    base_delay: float = 1.0
    max_delay: float = 30.0
    sleep: Callable[[float], None] = lambda s: None
    rng: random.Random = field(default_factory=lambda: random.Random(0))
    log: list[str] = field(default_factory=list)

    def _backoff(self, attempt: int) -> float:
        """Full jitter: a random delay up to base * 2**attempt, capped."""
        return self.rng.uniform(0, min(self.max_delay, self.base_delay * 2 ** attempt))

    def _try_model(self, route: Route, model: str, prompt: str) -> dict | None:
        for attempt in range(self.max_attempts):
            try:
                reply = self.backend.generate(model, prompt)
            except QuotaExceeded:
                if attempt == self.max_attempts - 1:
                    self.log.append(f"{route.feature}: {model} 429, no attempts left")
                    break
                delay = self._backoff(attempt)
                self.log.append(f"{route.feature}: {model} 429, retry in {delay:.2f}s")
                self.sleep(delay)
                continue
            self.ledger.record(route.feature, model, reply)  # failed parses still cost tokens
            try:
                data = json.loads(reply.text)
            except json.JSONDecodeError:
                self.log.append(f"{route.feature}: {model} returned invalid JSON, retrying")
                continue
            missing = [k for k in route.required_keys if k not in data]
            if missing:
                self.log.append(f"{route.feature}: {model} missing {missing}, retrying")
                continue
            self.log.append(f"{route.feature}: {model} ok on attempt {attempt + 1}")
            return data
        return None

    def call(self, route: Route, prompt: str) -> dict:
        for model in route.models:
            data = self._try_model(route, model, prompt)
            if data is not None:
                return data
            self.log.append(f"{route.feature}: giving up on {model}, falling back")
        raise RuntimeError(f"{route.feature}: all models failed")


class FakeBackend:
    """Scripted failures per model, then a valid JSON reply."""

    def __init__(self, script: dict[str, list[str]]):
        self.script = {m: list(events) for m, events in script.items()}

    def generate(self, model: str, prompt: str) -> Reply:
        event = self.script[model].pop(0) if self.script[model] else "ok"
        if event == "429":
            raise QuotaExceeded(model)
        tokens_in = len(prompt.split()) * 4
        if event == "bad_json":
            return Reply("{'title': ", tokens_in, 20)
        return Reply(json.dumps({"title": "Section 3", "items": 4}), tokens_in, 60)


if __name__ == "__main__":
    prices = {"model-fast": (0.30, 2.50), "model-strong": (1.25, 10.00)}  # illustrative, USD per 1M tokens
    backend = FakeBackend({"model-fast": ["429", "bad_json", "429"], "model-strong": []})
    gateway = Gateway(backend, Ledger(prices))
    extract = Route("extract", ("model-fast", "model-strong"), required_keys=("title", "items"))
    summarise = Route("summarise", ("model-fast",), required_keys=("title",))
    prompt = "Extract the section title and the number of items from this page. " * 20

    print(gateway.call(extract, prompt))
    print(gateway.call(summarise, prompt))
    print("\n".join(gateway.log))
    for feature, (tin, tout, usd) in gateway.ledger.totals.items():
        print(f"{feature:10s} in={tin:6d} out={tout:4d} cost=${usd:.6f}")
