"""Runtime-tunable configuration from the `settings` table (OPS-05).
Tenant scope overrides platform scope. Cached for 60 s."""
import time
from typing import Any


class _Missing:
    pass


_MISSING = _Missing()
_cache: dict[tuple[str, str], tuple[float, Any]] = {}
TTL = 60.0

DEFAULTS: dict[str, Any] = {
    "ai.extract.provider": "fake",
    "ai.extract.model": "fake-vision",
    "ai.extract.fallback": None,          # {"provider": "...", "model": "..."}
    "ai.score.provider": "fake",
    "ai.score.model": "fake-text",
    "ai.score.granularity": "script",     # 'script' | 'question'
    "ai.score.max_input_tokens": 150_000,
    "ai.pricing": {},                     # {"<model>": {"in": usd/Mtok, "out": usd/Mtok, "cached_in": usd/Mtok}}
    "extract.confidence_threshold": 0.75,
    "scoring.spelling_penalty": 0.1,
    "scoring.grammar_penalty": 0.1,
    "scoring.max_spelling_penalty": 0.5,  # rating floor for spelling = 1 - this
    "credits.extract_page": 1000,         # milli-credits
    "credits.score_script": 0,
    "credits.rescore_script": 0,
}


def get(conn, key: str, tenant_id: str | None = None) -> Any:
    scopes = ([tenant_id] if tenant_id else []) + ["platform"]
    now = time.monotonic()
    for scope in scopes:
        hit = _cache.get((key, scope))
        if hit and now - hit[0] < TTL:
            val = hit[1]
        else:
            row = conn.execute("SELECT value_json FROM settings WHERE key=%s AND scope=%s",
                               (key, scope)).fetchone()
            val = row["value_json"] if row else _MISSING
            _cache[(key, scope)] = (now, val)
        if val is not _MISSING:
            return val
    return DEFAULTS.get(key)


def clear_cache() -> None:
    _cache.clear()
