"""Aivora's model client asks the platform's AI credit pool before every call and reports after; the purpose is
the service module that called; the ai_tokens quota check reads the pool. The pool and the model are fakes."""
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace

import pytest
from galaxiq_utils.ai_credits.types import Charge, Decision

from app.core import llm_client as door
from app.core.asking import note_who_is_asking
from app.services.infra.quotas import QuotaExceededError, check_quota


class FakePool:
    def __init__(self):
        self.allow, self.remaining, self.asked, self.recorded = True, 1000, [], []

    def may_spend(self, tenant, feature, type, model_key, input_estimate=0, output_estimate=0):
        self.asked.append((tenant, feature, type, model_key))
        end = datetime.now(timezone.utc) + timedelta(days=5)
        return Decision(True, "", "hold", 5, self.remaining, end) if self.allow else Decision(False, "used_up", None, 5, 0, end)

    def record(self, reservation_id, call_id, tenant, feature, type, model_key, input_units=0, cached_input_units=0, output_units=0):
        self.recorded.append((tenant, feature, type, model_key, input_units, output_units))
        return Charge(5, self.remaining - 5, None)

    def release(self, reservation_id):
        pass

    def summary(self, tenant):
        end = datetime.now(timezone.utc) + timedelta(days=5)
        return {"allowance": 1000, "purchased": 0, "used": 1000 - self.remaining, "reserved": 0, "remaining": self.remaining,
                "used_by_type": {}, "period_start": end - timedelta(days=25), "period_end": end}


class FakeOpenAI:
    def __init__(self):
        self.calls = 0
        self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._chat))
        self.embeddings = SimpleNamespace(create=self._embed)

    def _chat(self, **kwargs):
        self.calls += 1
        return SimpleNamespace(model="gpt-4o", usage=SimpleNamespace(prompt_tokens=700, completion_tokens=90, prompt_tokens_details=None),
                               choices=[SimpleNamespace(message=SimpleNamespace(content="ok"))])

    def _embed(self, **kwargs):
        self.calls += 1
        return SimpleNamespace(usage=SimpleNamespace(prompt_tokens=30), data=[SimpleNamespace(embedding=[0.1])])


def call_as(module_name: str, code: str):
    """Runs `code` as if from a service module, so the caller's purpose is read the way it is in production."""
    scope = {"__name__": module_name, "client": door.client}
    exec(code, scope)
    return scope["result"]


@pytest.fixture
def pool():
    pool, fake = FakePool(), FakeOpenAI()
    door.use(pool, fake)
    note_who_is_asking("tenant-1")
    yield pool, fake
    note_who_is_asking(None)


def test_chat_from_a_service_module_is_asked_and_reported_under_its_purpose(pool):
    pool, fake = pool
    resp = call_as("app.services.chat.chat",
                   "result = client.chat.completions.create(model='gpt-4o', messages=[{'role': 'user', 'content': 'hi'}])")
    assert resp.choices[0].message.content == "ok"
    assert pool.asked[-1] == ("tenant-1", "chat_answer", "text", "gpt-4o")
    assert pool.recorded[-1] == ("tenant-1", "chat_answer", "text", "gpt-4o", 700, 90)


def test_the_api_used_sets_the_type_not_the_module(pool):
    pool, _ = pool
    call_as("app.services.catalog.products",
            "result = client.chat.completions.create(model='gpt-5.2-chat', messages=[{'role': 'user', 'content': 'hi'}])\n"
            "client.embeddings.create(input='hello', model='text-embedding-3-small')")
    assert pool.asked[0] == ("tenant-1", "catalog_products", "text", "gpt-5.2-chat")
    assert pool.asked[1] == ("tenant-1", "catalog_products", "embedding", "text-embedding-3-small")


def test_embedding_is_charged_on_input_under_the_embedding_type(pool):
    pool, _ = pool
    call_as("app.services.infra.embedding", "result = client.embeddings.create(input='hello', model='text-embedding-3-small')")
    assert pool.asked[-1] == ("tenant-1", "embedding", "embedding", "text-embedding-3-small")
    assert pool.recorded[-1][3:] == ("text-embedding-3-small", 30, 0)


def test_an_unnamed_module_is_still_charged_under_its_own_name(pool):
    pool, _ = pool
    call_as("app.services.new.thing", "result = client.chat.completions.create(model='gpt-4o', messages=[])")
    assert pool.asked[-1][1:3] == ("thing", "text")


def test_refusal_stops_the_model_call(pool):
    pool, fake = pool
    pool.allow = False
    with pytest.raises(door.Refused):
        call_as("app.services.chat.chat", "result = client.chat.completions.create(model='gpt-4o', messages=[])")
    assert fake.calls == 0


def test_without_a_tenant_the_call_goes_as_it_is(pool):
    pool, fake = pool
    note_who_is_asking(None)
    call_as("app.services.chat.chat", "result = client.chat.completions.create(model='gpt-4o', messages=[])")
    assert pool.asked == [] and fake.calls == 1


def test_ai_tokens_quota_reads_the_pool_and_notes_the_tenant(pool):
    pool, _ = pool
    pool.remaining = 3
    with pytest.raises(QuotaExceededError) as said:
        check_quota("tenant-2", "ai_tokens", requested_amount=10)
    assert "used up" in str(said.value) and "renew on" in str(said.value)
    pool.remaining = 50
    check_quota("tenant-2", "ai_tokens", requested_amount=10)
    from app.core.asking import who_is_asking
    assert who_is_asking() == "tenant-2"
