from app.services.infra.database import bootstrap_tenant
import app.services.pairing.embeddings as mod


def test_a_second_run_embeds_nothing(temp_tenant, monkeypatch):
    # The whole point of the cache. Phase 1's second enrich made zero model
    # calls; this must too.
    calls = {"n": 0}

    def fake(texts, tenant_id=None, user_id=None):
        calls["n"] += 1
        return [[1.0, 0.0] for _ in texts]

    monkeypatch.setattr(mod, "_embed_batch", fake)
    bootstrap_tenant(temp_tenant)
    products = [{"product_key": "a", "name": "A", "description": "d",
                 "category": "c", "attributes": [], "content_hash": "h1"}]

    mod.vectors_for(temp_tenant, products)
    mod.vectors_for(temp_tenant, products)
    assert calls["n"] == 1


def test_a_crawled_product_with_no_content_hash_embeds_only_once(temp_tenant,
                                                                  monkeypatch):
    # The Phase 1 trap: NULL content_hash compared to NULL is NULL, not
    # "unchanged", so a naive check re-embeds and re-bills forever.
    calls = {"n": 0}

    def fake(texts, tenant_id=None, user_id=None):
        calls["n"] += 1
        return [[1.0, 0.0] for _ in texts]

    monkeypatch.setattr(mod, "_embed_batch", fake)
    bootstrap_tenant(temp_tenant)
    products = [{"product_key": "a", "name": "A", "description": "d",
                 "category": "c", "attributes": [], "content_hash": None}]

    mod.vectors_for(temp_tenant, products)
    mod.vectors_for(temp_tenant, products)
    assert calls["n"] == 1


def test_a_changed_content_hash_re_embeds(temp_tenant, monkeypatch):
    calls = {"n": 0}

    def fake(texts, tenant_id=None, user_id=None):
        calls["n"] += 1
        return [[1.0, 0.0] for _ in texts]

    monkeypatch.setattr(mod, "_embed_batch", fake)
    bootstrap_tenant(temp_tenant)
    products = [{"product_key": "a", "name": "A", "description": "d",
                 "category": "c", "attributes": [], "content_hash": "h1"}]

    mod.vectors_for(temp_tenant, products)
    products[0]["content_hash"] = "h2"
    mod.vectors_for(temp_tenant, products)
    assert calls["n"] == 2
