"""Tests for similarity filter in compute_similarities — real DB, real code, no mocks."""

import json
import duckdb
from database import MotionDatabase
import similarity.compute as sc


def test_filter_skips_identical_short_title_pairs(tmp_path):
    """Pairs with identical short titles and perfect cosine similarity are filtered out."""
    db_path = str(tmp_path / "test.db")

    # 1. Initialize schema
    db = MotionDatabase(db_path)

    # 2. Insert 2 motions with identical short titles
    motion1 = {
        "title": "Aangenomen.",
        "description": "desc1",
        "date": "2020-01-01",
        "policy_area": "",
        "voting_results": {},
        "winning_margin": 0.5,
        "url": "u1",
    }
    motion2 = {
        "title": "Aangenomen.",
        "description": "desc2",
        "date": "2020-01-02",
        "policy_area": "",
        "voting_results": {},
        "winning_margin": 0.6,
        "url": "u2",
    }

    assert db.insert_motion(motion1) is True
    assert db.insert_motion(motion2) is True

    # fetch ids
    conn = duckdb.connect(db_path)
    id1 = conn.execute(
        "SELECT id FROM motions WHERE url = ?", (motion1["url"],)
    ).fetchone()[0]
    id2 = conn.execute(
        "SELECT id FROM motions WHERE url = ?", (motion2["url"],)
    ).fetchone()[0]

    assert id1 is not None and id2 is not None and id1 != id2

    # 3. Insert identical unit vectors into fused_embeddings using store_fused_embedding
    vec = [1.0] + [0.0] * 7  # 8-dim unit vector

    # use a window id (schema requires NOT NULL); compute_similarities will read all fused embeddings when window_id=None
    window_id = "w"
    assert db.store_fused_embedding(id1, window_id, vec, svd_dims=0, text_dims=0) > 0
    assert db.store_fused_embedding(id2, window_id, vec, svd_dims=0, text_dims=0) > 0
    conn.close()

    # 4. Run compute_similarities
    inserted = sc.compute_similarities(
        vector_type="fused",
        window_id=None,
        db_path=db_path,
    )

    # 5. The pair (id1, id2) has perfect similarity and identical short titles
    #    The filter should remove it → 0 rows inserted into similarity_cache
    assert inserted == 0, f"Expected 0 pairs after filter, got {inserted}"
