import pytest
from fastapi.testclient import TestClient


@pytest.fixture
def client():
    from app.main import app

    return TestClient(app)


def test_search_returns_409_when_repo_ambiguous(client, monkeypatch):
    from app.models.repos import RepoEntry, RepoStages

    async def fake_list_repos(_self):
        return [
            RepoEntry(
                repo_id="ad/adpilot-indexing-commit-intel.com",
                latest_snapshot_id="snap_1",
                indexing_status="completed",
                stages=RepoStages(embedding="completed"),
            ),
            RepoEntry(
                repo_id="ad/adpilot-indexing-code-parser.com",
                latest_snapshot_id="snap_2",
                indexing_status="completed",
                stages=RepoStages(embedding="completed"),
            ),
        ]

    monkeypatch.setattr(
        "app.repositories.repo_repository.RepoRepository.list_repos",
        fake_list_repos,
    )
    monkeypatch.setattr(
        "app.core.config.settings.REPO_RESOLVER_LLM_ENABLED",
        False,
    )

    response = client.post(
        "/api/v1/search/",
        json={"question": "Where is ProcessDelta defined?"},
    )
    assert response.status_code == 409
    body = response.json()
    assert body["status"] == "repo_clarification_required"
    assert len(body["candidates"]) == 2


def test_search_question_only_single_repo(client, monkeypatch):
    from app.core.config import settings
    from app.models.repos import RepoEntry, RepoStages

    async def fake_list_repos(_self):
        return [
            RepoEntry(
                repo_id="ad/adpilot-indexing-commit-intel.com",
                latest_snapshot_id="snap_demo",
                indexing_status="completed",
                stages=RepoStages(embedding="completed"),
            )
        ]

    monkeypatch.setattr(settings, "RETRIEVAL_CLIENT_MOCK", True)
    monkeypatch.setattr(settings, "REPO_RESOLVER_LLM_ENABLED", False)
    monkeypatch.setattr(
        "app.repositories.repo_repository.RepoRepository.list_repos",
        fake_list_repos,
    )

    response = client.post(
        "/api/v1/search/",
        json={"question": "How does commit analysis get triggered?"},
    )
    assert response.status_code == 200
    assert response.json()["repo_id"] == "ad/adpilot-indexing-commit-intel.com"
