from __future__ import annotations

import pytest

from app.core.config import settings
from app.generation.llm_client import ChatCompletionResult
from app.models.repos import RepoEntry
from app.services.query_log_service import QueryLogService


@pytest.fixture(autouse=True)
def integration_env(monkeypatch):
    monkeypatch.setattr(settings, "RETRIEVAL_CLIENT_MOCK", True)
    monkeypatch.setattr(settings, "RETRIEVAL_MOCK_SCENARIO", "")
    monkeypatch.setattr(settings, "QUERY_LOGS_ENABLED", False)


@pytest.fixture
def mock_repo(monkeypatch):
    async def fake_list_repos(_self):
        return [
            RepoEntry(
                repo_id="ad/adpilot-indexing-commit-intel.com",
                clone_url="https://example.com/repo.git",
                latest_snapshot_id="snap_demo",
            )
        ]

    monkeypatch.setattr(
        "app.repositories.repo_repository.RepoRepository.list_repos",
        fake_list_repos,
    )


@pytest.fixture
def mock_llm(monkeypatch):
    async def fake_complete(messages, model=None):
        return ChatCompletionResult(
            text="Commit analysis is triggered via graph.delta.ready events [1][2].",
            model="gpt-4o",
            latency_ms=50,
            prompt_tokens=100,
            completion_tokens=20,
        )

    async def fake_stream(messages, model=None):
        yield "The indexing pipeline "
        yield "runs end to end [1][2]."

    from app.generation.llm_client import LLMClient

    llm = LLMClient(client=object())  # type: ignore[arg-type]
    llm.complete = fake_complete  # type: ignore[method-assign]
    llm.stream = fake_stream  # type: ignore[method-assign]
    monkeypatch.setattr("app.services.query_service.LLMRouter", lambda **_: llm)
    monkeypatch.setattr("app.api.routes.query._query_service._llm_client", llm)
    return llm


@pytest.fixture
def client(mock_repo, mock_llm):
    from fastapi.testclient import TestClient
    from app.main import app

    return TestClient(app)
