"""tenant.quota — Quota check, reserve, settle."""
from __future__ import annotations
from agentpaas.db.session import get_db


class QuotaExceededError(Exception):
    def __init__(self, limit, used, requested):
        self.limit, self.used, self.requested = limit, used, requested
        super().__init__(f"Quota exceeded: limit={limit}, used={used}, requested={requested}")


async def check_and_reserve(tenant_id: str, estimated_tokens: int = 5000):
    db = get_db()
    tenant = db.fetchone("SELECT quota_tokens_monthly FROM tenants WHERE id=?", (tenant_id,))
    if not tenant:
        raise QuotaExceededError(0, 0, estimated_tokens)
    used = db.fetchone(
        "SELECT COALESCE(SUM(input_tokens + output_tokens), 0) as total FROM runs WHERE tenant_id=? AND status='completed'",
        (tenant_id,))
    total_used = used["total"] if used else 0
    limit = tenant["quota_tokens_monthly"]
    if total_used + estimated_tokens > limit:
        raise QuotaExceededError(limit, total_used, estimated_tokens)
    return {"remaining": limit - total_used}


async def check_concurrency(tenant_id: str):
    db = get_db()
    tenant = db.fetchone("SELECT quota_concurrency FROM tenants WHERE id=?", (tenant_id,))
    active = db.fetchone("SELECT COUNT(*) as cnt FROM runs WHERE tenant_id=? AND status='running'", (tenant_id,))
    if active and tenant and active["cnt"] >= tenant["quota_concurrency"]:
        raise QuotaExceededError(tenant["quota_concurrency"], active["cnt"], 1)
