from __future__ import annotations

import json
import sys
from pathlib import Path


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

import embed_1c_semantic_cache as worker  # noqa: E402


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

    def fake_adapter_call(adapter_url: str, method: str, payload: dict, *, timeout_seconds: int = 180) -> dict:
        calls.append((method, payload))
        if method == "semantic.cache.pending":
            return {
                "status": "ok",
                "documents": [
                    {
                        "document_id": "doc-1",
                        "content_sha1": "a" * 40,
                        "text": "ОбластьШапка макета",
                    }
                ],
            }
        if method == "semantic.cache.embedding.upsert":
            assert payload["document_id"] == "doc-1"
            assert payload["content_sha1"] == "a" * 40
            assert payload["embedding_model"] == "local-hashing-v1"
            assert isinstance(payload["embedding"], list)
            assert len(payload["embedding"]) == 16
            return {"status": "ok", "dimensions": len(payload["embedding"])}
        raise AssertionError(method)

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

    result = worker.embed_pending_semantic_cache(
        adapter_url="http://adapter/rpc",
        base_id="upo_test",
        limit=1,
        dimensions=16,
    )

    assert result["status"] == "ok"
    assert result["counts"] == {"pending": 1, "processed": 1, "stored": 1, "conflicts": 0, "skipped": 0, "errors": 0}
    assert [method for method, _ in calls] == ["semantic.cache.pending", "semantic.cache.embedding.upsert"]


def test_embed_pending_semantic_cache_dry_run_does_not_upsert(monkeypatch) -> None:
    calls: list[str] = []

    def fake_adapter_call(adapter_url: str, method: str, payload: dict, *, timeout_seconds: int = 180) -> dict:
        calls.append(method)
        return {
            "status": "ok",
            "documents": [{"document_id": "doc-1", "content_sha1": "b" * 40, "text": "Реквизиты"}],
        }

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

    result = worker.embed_pending_semantic_cache(
        adapter_url="http://adapter/rpc",
        base_id="upo_test",
        dimensions=8,
        dry_run=True,
    )

    assert result["counts"]["processed"] == 1
    assert result["counts"]["stored"] == 0
    assert result["upserts"][0]["status"] == "dry_run"
    assert calls == ["semantic.cache.pending"]
