from __future__ import annotations

import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "scripts"))

import search_1c_code_vectors as search_cli  # noqa: E402


def test_search_code_vectors_sends_model_and_strict_query_embedding(monkeypatch) -> None:
    calls: list[tuple[str, dict]] = []

    monkeypatch.setattr(
        search_cli,
        "embed_texts",
        lambda texts, **kwargs: [[1.0, 0.0, 0.0]],
    )

    def fake_adapter_call(
        adapter_url: str,
        method: str,
        payload: dict,
        *,
        timeout_seconds: int = 180,
    ) -> dict:
        calls.append((method, payload))
        return {"status": "ok", "matches": []}

    monkeypatch.setattr(search_cli, "adapter_call", fake_adapter_call)

    result = search_cli.search_code_vectors(
        adapter_url="http://adapter/rpc",
        base_id="upo_test",
        query="где рассчитывается налог",
        embedding_provider="openai-compatible",
        embedding_model="test-code-model",
        embedding_base_url="http://embeddings",
        dimensions=3,
    )

    assert result["status"] == "ok"
    assert result["client_embedding"]["stored_embedding_model"] == "openai-compatible:test-code-model@d3"
    assert calls == [
        (
            "metadata.code_vector.search",
            {
                "base_id": "upo_test",
                "query": "где рассчитывается налог",
                "query_embedding": [1.0, 0.0, 0.0],
                "embedding_model": "openai-compatible:test-code-model@d3",
                "limit": 10,
                "scan_limit": 2000,
                "verify": True,
                "strict": True,
            },
        )
    ]


def test_qwen3_search_uses_query_instruction_but_keeps_lexical_query_plain(monkeypatch) -> None:
    embedded_texts: list[str] = []
    calls: list[tuple[str, dict]] = []

    def fake_embed_texts(texts: list[str], **kwargs) -> list[list[float]]:
        embedded_texts.extend(texts)
        return [[0.5, 0.5]]

    monkeypatch.setattr(search_cli, "embed_texts", fake_embed_texts)

    def fake_adapter_call(
        adapter_url: str,
        method: str,
        payload: dict,
        *,
        timeout_seconds: int = 180,
    ) -> dict:
        calls.append((method, payload))
        return {"status": "ok", "matches": []}

    monkeypatch.setattr(search_cli, "adapter_call", fake_adapter_call)

    result = search_cli.search_code_vectors(
        adapter_url="http://adapter/rpc",
        base_id="upo_test",
        query="обработка проведения документа",
        embedding_provider="openai-compatible",
        embedding_model="qwen3-embedding-0.6b",
        embedding_base_url="http://embeddings",
    )

    assert embedded_texts == [
        "Instruct: Given a natural-language software task, retrieve the relevant "
        "1C Enterprise BSL source-code fragment that implements or explains it\n"
        "Query:обработка проведения документа"
    ]
    assert calls[0][1]["query"] == "обработка проведения документа"
    assert result["client_embedding"]["query_instruction"] == (
        search_cli.DEFAULT_QWEN3_CODE_RETRIEVAL_INSTRUCTION
    )
