from datetime import UTC, datetime
from pathlib import Path

from home_agent.contracts.types import (
    ItemKind,
    UrgencyLabel,
    VectorDocument,
    VectorDocumentKey,
    VectorQuery,
)
from home_agent.core.config import SqliteVecConfig
from home_agent.retrieval.vector_backends import SqliteVecBackend
from home_agent.storage.sqlite_store import SqliteStore


def test_sqlite_vec_backend_upserts_and_queries_documents(tmp_path: Path) -> None:
    backend = SqliteVecBackend(
        store=SqliteStore(tmp_path / "agent.db"),
        config=SqliteVecConfig(table_name="vec_items"),
    )
    backend.upsert_documents(
        [
            _document("best", [1.0, 0.0], UrgencyLabel.HIGH),
            _document("other", [0.0, 1.0], UrgencyLabel.LOW),
        ]
    )

    results = backend.query_similar(
        VectorQuery(
            vector=[1.0, 0.0],
            top_k=2,
            min_similarity=0.4,
            include_item_kinds={"email"},
            prioritize_labels={UrgencyLabel.HIGH},
            exclude_keys=set(),
        )
    )

    assert [result.external_id for result in results] == ["best"]
    assert results[0].similarity >= 0.99


def test_sqlite_vec_backend_healthcheck_initializes_extension(tmp_path: Path) -> None:
    backend = SqliteVecBackend(
        store=SqliteStore(tmp_path / "agent.db"),
        config=SqliteVecConfig(table_name="vec_items"),
    )

    backend.healthcheck()


def test_sqlite_vec_backend_accepts_documents_without_urgency_label(tmp_path: Path) -> None:
    backend = SqliteVecBackend(
        store=SqliteStore(tmp_path / "agent.db"),
        config=SqliteVecConfig(table_name="vec_items"),
    )

    backend.upsert_documents([_document("unlabeled", [1.0, 0.0], None)])

    results = backend.query_similar(
        VectorQuery(
            vector=[1.0, 0.0],
            top_k=1,
            min_similarity=0.4,
            include_item_kinds={"email"},
            prioritize_labels=None,
            exclude_keys=set(),
        )
    )

    assert [result.external_id for result in results] == ["unlabeled"]
    assert results[0].urgency_label is None


def _document(
    external_id: str,
    vector: list[float],
    label: UrgencyLabel | None,
) -> VectorDocument:
    return VectorDocument(
        key=VectorDocumentKey(
            provider="gmail",
            external_id=external_id,
            embedding_provider="local_sentence_transformers",
            embedding_model="all-MiniLM-L6-v2",
        ),
        kind=ItemKind.EMAIL,
        received_at=datetime.now(tz=UTC),
        urgency_label=label,
        summary_text=f"summary:{external_id}",
        source_version="v1",
        vector=vector,
        metadata={},
    )
