"""The tables this package reads and writes, created idempotently from the SQL files shipped with it.

    ensure_rates_table(platform_conn)         ai_model_rates in the platform's master DB (global, admin-managed)
    ensure_tenant_tables(tenant_conn, schema) the pool, holds and ledger in one tenant's schema (org_<tenantId>)
"""
from __future__ import annotations

from pathlib import Path
from typing import Set

SQL_DIR = Path(__file__).resolve().parent / "sql"
RATES_SQL = "ai_model_rates.sql"
TENANT_SQL = "ai_credits.sql"
TENANT_TABLES = ("ai_credit_periods", "ai_credit_reservations", "ai_usage")

_ensured: Set[str] = set()


def rates_sql() -> str:
    return (SQL_DIR / RATES_SQL).read_text(encoding="utf-8")


def tenant_sql(schema: str) -> str:
    if not schema.replace("_", "").replace("-", "").isalnum():
        raise ValueError(f"not a schema name: {schema!r}")
    return (SQL_DIR / TENANT_SQL).read_text(encoding="utf-8").replace("{schema}", schema).replace("{{", "{").replace("}}", "}")


def ensure_rates_table(conn) -> None:
    """Creates ai_model_rates if missing and seeds the example rates (disabled). Safe to run again."""
    with conn.transaction():
        conn.execute(rates_sql())


def ensure_tenant_tables(conn, schema: str) -> None:
    """Creates the tenant's pool, holds and ledger tables if missing; once per schema per process."""
    if schema in _ensured:
        return
    with conn.transaction():
        conn.execute(tenant_sql(schema))
    _ensured.add(schema)


def ensure_tables(conn) -> None:
    """The platform side only; kept for the scripts that call it."""
    ensure_rates_table(conn)
