"""The rate a call is priced at: the model's own row for this type of work when it is enabled, else the type's
'*' fallback (flagged on the usage row), else nothing, and the call is refused for want of a price."""
from __future__ import annotations

from typing import Optional

from .types import Rate


def rate_for(conn, model_key: str, type: str) -> Optional[Rate]:
    rows = conn.execute(
        "SELECT model_key, type, unit, input_tokens_per_unit, output_tokens_per_unit "
        "FROM ai_model_rates WHERE type = %s AND enabled AND model_key IN (%s, '*') "
        "ORDER BY (model_key = '*')",
        (type, model_key)).fetchall()
    if not rows:
        return None
    key, kind, unit, rate_in, rate_out = rows[0]
    return Rate(key, kind, unit, rate_in, rate_out, fallback=(key == "*"))
