from __future__ import annotations

import pytest

from app.models.intent import IntentResult, QueryIntent
from app.models.query_log import QueryLogEntry
from app.services.query_log_service import QueryLogService


class FakeRepo:
    def __init__(self):
        self.entries: list[QueryLogEntry] = []

    async def insert_entry(self, entry: QueryLogEntry) -> str:
        self.entries.append(entry)
        return "fake_id"


@pytest.mark.asyncio
async def test_query_log_service_persists_entry(monkeypatch):
    monkeypatch.setattr("app.services.query_log_service.settings.QUERY_LOGS_ENABLED", True)
    repo = FakeRepo()
    service = QueryLogService(repository=repo)  # type: ignore[arg-type]

    intent = IntentResult(
        type=QueryIntent.CODE_LOOKUP,
        confidence=0.9,
        source_types_used=[],
        tier="tier1",
    )
    log_id = await service.log_query(
        request_id="req_log_1",
        user_id="user_42",
        repo_id="ad/example.com",
        snapshot_id="snap_1",
        question="Where is Foo?",
        intent=intent,
        model="gpt-4o",
        hit_count=3,
        latency_ms=150,
        streamed=False,
        status="success",
    )
    assert log_id == "fake_id"
    assert len(repo.entries) == 1
    entry = repo.entries[0]
    assert entry.request_id == "req_log_1"
    assert entry.user_id == "user_42"
    assert entry.intent_type == "code_lookup"
    assert entry.status == "success"


@pytest.mark.asyncio
async def test_query_log_service_respects_disabled_flag(monkeypatch):
    monkeypatch.setattr("app.services.query_log_service.settings.QUERY_LOGS_ENABLED", False)
    repo = FakeRepo()
    service = QueryLogService(repository=repo)  # type: ignore[arg-type]

    intent = IntentResult(type=QueryIntent.GENERAL, confidence=0.5, source_types_used=[])
    result = await service.log_query(
        request_id="req_skip",
        user_id=None,
        repo_id="ad/example.com",
        snapshot_id="snap_1",
        question="test?",
        intent=intent,
        model=None,
        hit_count=0,
        latency_ms=10,
        streamed=False,
        status="no_context",
    )
    assert result is None
    assert repo.entries == []
