"""The one object a product holds. It never raises for a billing reason except Refused, and it fails open: when
the platform or the tenant's database cannot be reached the model call goes ahead, the usage is kept and settled
when they are back, and one line is logged. A billing fault must not stop a campaign; only a pool known to be
used up does.

Two databases: the platform's master DB for the rates and the subscription (what the organisation may spend),
the tenant's own schema for the pool and the ledger (what it has spent), beside the product's own usage table.
"""
from __future__ import annotations

import logging
import threading
import uuid
from contextlib import contextmanager
from datetime import datetime
from typing import Callable, List, Optional

import psycopg

from . import pool
from .allowance import Entitlement, read_entitlement
from .notices import tell_members_in_the_bell
from .rates import rate_for
from .schema import ensure_tenant_tables
from .types import Charge, Decision, Rate

log = logging.getLogger("galaxiq.ai_credits")


def org_schema(tenant_id: str) -> str:
    """The platform's schema for a tenant's data: org_<tenantId>, however the product spells the tenant."""
    tenant_id = str(tenant_id)
    return tenant_id if tenant_id.startswith("org_") else f"org_{tenant_id}"


class Refused(Exception):
    """The pool cannot cover this call. `decision` says how much is left and when it renews."""

    def __init__(self, decision: Decision):
        if decision.reason == "no_rate":
            message = "AI work with this model is not priced yet, so it cannot be charged to your credits."
        elif decision.renews_at:
            message = f"AI credits used up; they renew on {decision.renews_at:%d %b}"
        else:
            message = "AI credits used up"
        super().__init__(message)
        self.decision = decision


class Credits:
    def __init__(self, platform_dsn: str, tenant_dsn: str, product: str,
                 tell_owners: Optional[Callable[[str, int, int, int, datetime], None]] = None,
                 schema_of: Callable[[str], str] = org_schema, connect_timeout: int = 10,
                 connect: Optional[Callable[[str], object]] = None):
        """`tell_owners(tenant_id, mark, used, limit, renews_at)` is called once per mark per period; without one the
        every member is told in the platform bell (notices.py).
        `schema_of(tenant_id)` names the tenant's schema; org_<tenantId> unless the product says otherwise.
        `connect(dsn)` gives a connection to use in a with-block, such as a pool's; without it each check opens its own,
        which from a server far from the database costs seconds a model call."""
        self._platform_dsn = platform_dsn
        self._tenant_dsn = tenant_dsn
        self.product = product
        self._tell_owners = tell_owners
        self._schema_of = schema_of
        self._timeout = connect_timeout
        self._connect = connect or (lambda dsn: psycopg.connect(dsn, connect_timeout=connect_timeout))
        self._pending: List[dict] = []
        self._lock = threading.Lock()

    def _platform(self):
        return self._connect(self._platform_dsn)

    @contextmanager
    def _tenant(self, schema: str):
        with self._connect(self._tenant_dsn) as conn:
            ensure_tenant_tables(conn, schema)
            yield conn

    def entitlement(self, tenant_id: str) -> Optional[Entitlement]:
        with self._platform() as conn:
            return read_entitlement(conn, tenant_id)

    def summary(self, tenant_id: str) -> Optional[dict]:
        """Allowance, purchased, used, reserved, remaining and the split by type, or None without a subscription."""
        with self._platform() as platform:
            entitlement = read_entitlement(platform, tenant_id)
        if entitlement is None:
            return None
        schema = self._schema_of(tenant_id)
        with self._tenant(schema) as tenant:
            return pool.summary(tenant, schema, entitlement)

    def may_spend(self, tenant_id: str, feature: str, type: str, model_key: str,
                  input_estimate: int = 0, output_estimate: int = 0) -> Decision:
        """Ask before the model runs. Allowed with a hold, allowed unverified when the databases are unreachable,
        or refused with the reason and the renewal date."""
        try:
            with self._platform() as platform:
                self._drain()
                entitlement = read_entitlement(platform, tenant_id)
                if entitlement is None:
                    return Decision(True, "no_subscription")
                rate = rate_for(platform, model_key, type)
            schema = self._schema_of(tenant_id)
            with self._tenant(schema) as tenant:
                hold, estimate, period, reason = pool.reserve(tenant, schema, entitlement, rate, self.product, feature, type,
                                                              model_key, input_estimate, output_estimate)
                told_now = reason == "used_up" and pool.tell_once(tenant, schema, period.id, 100)
            if told_now:   # the pool is as good as empty: the owners hear it now, not only when a charge lands on 100%
                self._tell(tenant_id, 100, period.used, period.allowance + period.purchased, period.end)
            if reason in ("used_up", "no_rate"):
                return Decision(False, reason, None, estimate, period.remaining, period.end)
            return Decision(True, "", hold, estimate, period.remaining, period.end)
        except Exception as exc:  # noqa: BLE001 -- a billing fault must not stop a campaign
            log.warning("ai credits: could not check %s for %s (%s); letting the call go ahead", feature, tenant_id, exc)
            return Decision(True, "unverified")

    def record(self, reservation_id: Optional[str], call_id: Optional[str], tenant_id: str, feature: str, type: str,
               model_key: str, input_units: int = 0, cached_input_units: int = 0, output_units: int = 0) -> Charge:
        """Report what ran. Priced and taken off the pool; kept and settled later if a database is unreachable."""
        call_id = call_id or str(uuid.uuid4())
        entry = dict(reservation_id=reservation_id, call_id=call_id, tenant_id=tenant_id, feature=feature, type=type,
                     model_key=model_key, input_units=input_units, cached_input_units=cached_input_units,
                     output_units=output_units)
        try:
            self._drain()
            return self._settle(entry) or Charge(0, None, None)
        except Exception as exc:  # noqa: BLE001
            with self._lock:
                self._pending.append(entry)
            log.warning("ai credits: could not record %s for %s (%s); kept to settle later (%d pending)",
                        feature, tenant_id, exc, len(self._pending))
            return Charge(0, None, None, deferred=True)

    def release(self, tenant_id: str, reservation_id: Optional[str]) -> None:
        """Nothing ran: let the hold go."""
        if not reservation_id:
            return
        try:
            schema = self._schema_of(tenant_id)
            with self._tenant(schema) as tenant:
                pool.release(tenant, schema, reservation_id)
        except Exception as exc:  # noqa: BLE001
            log.warning("ai credits: could not release hold %s (%s); it expires on its own", reservation_id, exc)

    def expire_holds(self, tenant_id: str) -> int:
        schema = self._schema_of(tenant_id)
        with self._tenant(schema) as tenant:
            return pool.expire_holds(tenant, schema)

    @property
    def pending(self) -> int:
        return len(self._pending)

    def _settle(self, entry: dict) -> Optional[Charge]:
        with self._platform() as platform:
            entitlement = read_entitlement(platform, entry["tenant_id"])
            if entitlement is None:
                log.info("ai credits: %s has no subscription; %s recorded nowhere", entry["tenant_id"], entry["feature"])
                return None
            rate: Optional[Rate] = rate_for(platform, entry["model_key"], entry["type"])
        schema = self._schema_of(entry["tenant_id"])
        with self._tenant(schema) as tenant:
            charge = pool.settle(tenant, schema, entitlement, rate, entry["reservation_id"], entry["call_id"], self.product,
                                 entry["feature"], entry["type"], entry["model_key"], entry["input_units"],
                                 entry["cached_input_units"], entry["output_units"])
            if charge.marks_crossed:
                period = pool.open_period(tenant, schema, entitlement)
                for mark in charge.marks_crossed:
                    self._tell(entry["tenant_id"], mark, period.used, period.allowance + period.purchased, period.end)
        return charge

    def _tell(self, tenant_id: str, mark: int, used: int, limit: int, renews_at: datetime) -> None:
        """The product's own notifier when it gave one, else the platform bell for every owner. The charge stands
        whether or not it was announced."""
        try:
            if self._tell_owners:
                self._tell_owners(tenant_id, mark, used, limit, renews_at)
            else:
                with self._platform() as platform:
                    tell_members_in_the_bell(platform, tenant_id, mark, used, limit, renews_at)
        except Exception as exc:  # noqa: BLE001
            log.warning("ai credits: could not tell the owners of %s about %s%% (%s)", tenant_id, mark, exc)

    def _drain(self) -> None:
        """Settles what could not be recorded earlier, oldest first; stops at the first failure."""
        with self._lock:
            waiting, self._pending = self._pending, []
        for entry in waiting:
            try:
                self._settle(entry)
            except Exception as exc:  # noqa: BLE001
                with self._lock:
                    self._pending.insert(0, entry)
                log.warning("ai credits: still cannot settle %s (%s)", entry["call_id"], exc)
                break
