import pytest
from fastapi.testclient import TestClient


@pytest.fixture
def api_client(integration_env, monkeypatch):
    monkeypatch.setattr("app.main.bootstrap_qdrant", lambda *_args, **_kwargs: "adpilot_embeddings")
    from app.main import app

    return TestClient(app)


def _lucos_chunk_payload() -> dict:
    return {
        "chunks": [
            {
                "chunk_id": "src/auth/middleware.ts:10-42:abc123",
                "chunk_hash": "sha256:lucos-integration",
                "repo_id": "lucos:ws:integration",
                "file_path": "src/auth/middleware.ts",
                "content": "export function authMiddleware() { return (req, res, next) => next(); }",
                "source_type": "code",
                "start_line": 10,
                "end_line": 42,
                "language": "typescript",
                "symbol_name": "authMiddleware",
                "snapshot_id": "workspace",
                "commit_sha": "integration",
            }
        ]
    }


@pytest.mark.integration
def test_lucos_embed_then_retrieve(integration_env, api_client):
    embed_response = api_client.post(
        "/internal/lucos/chunks/embed",
        json=_lucos_chunk_payload(),
    )
    assert embed_response.status_code == 200
    embed_body = embed_response.json()
    assert embed_body["requested"] == 1
    assert embed_body["embedded"] == 1
    assert embed_body["indexed"] == 1
    assert embed_body["failed"] == 0

    retrieve_response = api_client.post(
        "/internal/retrieve",
        json={
            "repo_id": "lucos:ws:integration",
            "snapshot_id": "workspace",
            "query_text": "auth middleware",
            "top_k": 5,
            "request_id": "req_lucos_integration",
            "graph_expand": False,
            "filters": {"source_types": ["code", "docs"]},
        },
    )
    assert retrieve_response.status_code == 200
    body = retrieve_response.json()
    assert body["metadata"]["request_id"] == "req_lucos_integration"
    assert body["metadata"]["retrieval_count"] >= 1
    assert len(body["hits"]) >= 1
    assert any("authMiddleware" in (hit.get("text") or "") for hit in body["hits"])


@pytest.mark.integration
def test_lucos_embed_is_idempotent_for_same_chunk_hash(integration_env, api_client):
    payload = _lucos_chunk_payload()

    first = api_client.post("/internal/lucos/chunks/embed", json=payload)
    second = api_client.post("/internal/lucos/chunks/embed", json=payload)

    assert first.status_code == 200
    assert second.status_code == 200
    assert first.json()["embedded"] == 1
    assert second.json()["embedded"] == 1
    assert integration_env["embedding_provider"].call_count == 1


@pytest.mark.integration
def test_lucos_delete_removes_vectors_from_retrieve(integration_env, api_client):
    embed_response = api_client.post(
        "/internal/lucos/chunks/embed",
        json=_lucos_chunk_payload(),
    )
    assert embed_response.status_code == 200

    record_id = "lucos:lucos:ws:integration:src/auth/middleware.ts:10-42:abc123"
    delete_response = api_client.post(
        "/internal/lucos/chunks/delete",
        json={"record_ids": [record_id]},
    )
    assert delete_response.status_code == 200
    assert delete_response.json()["deleted"] >= 1

    retrieve_response = api_client.post(
        "/internal/retrieve",
        json={
            "repo_id": "lucos:ws:integration",
            "snapshot_id": "workspace",
            "query_text": "auth middleware",
            "top_k": 5,
            "request_id": "req_lucos_after_delete",
            "graph_expand": False,
            "filters": {"source_types": ["code", "docs"]},
        },
    )
    assert retrieve_response.status_code == 200
    assert retrieve_response.json()["metadata"]["retrieval_count"] == 0
