"""Around one model call: ask, run, report. The call's own usage report is what gets priced."""
from __future__ import annotations

import uuid
from typing import Callable, Optional, Tuple

from .client import Credits, Refused


def usage_of_completion(resp) -> Tuple[int, int, int]:
    """(input, cached input, output) from an OpenAI-style chat completion."""
    usage = getattr(resp, "usage", None)
    if usage is None:
        return 0, 0, 0
    details = getattr(usage, "prompt_tokens_details", None)
    cached = getattr(details, "cached_tokens", 0) or 0
    return int(getattr(usage, "prompt_tokens", 0) or 0), int(cached), int(getattr(usage, "completion_tokens", 0) or 0)


def usage_of_images(resp) -> Tuple[int, int, int]:
    """(0, 0, images) from an OpenAI-style image response."""
    return 0, 0, len(getattr(resp, "data", None) or [])


def metered(credits: Credits, tenant_id: str, feature: str, type: str, model_key: str, call: Callable[[], object],
            input_estimate: int = 0, output_estimate: int = 0,
            usage_of: Callable[[object], Tuple[int, int, int]] = usage_of_completion,
            call_id: Optional[str] = None):
    """Runs `call()` if the pool allows and records what it used. Raises Refused when the pool cannot cover it;
    any other billing trouble lets the call go ahead and settles later."""
    decision = credits.may_spend(tenant_id, feature, type, model_key, input_estimate, output_estimate)
    if not decision:
        raise Refused(decision)
    try:
        resp = call()
    except Exception:
        credits.release(tenant_id, decision.reservation_id)
        raise
    input_units, cached, output_units = usage_of(resp)
    credits.record(decision.reservation_id, call_id or str(uuid.uuid4()), tenant_id, feature, type, model_key,
                   input_units, cached, output_units)
    return resp
