"""Shared test fixtures."""

import os
import tempfile
from unittest.mock import patch, MagicMock

import pyarrow as pa
import pytest

# Set test DB path before any imports
_test_dir = tempfile.mkdtemp()
os.environ["ARS25_DB_PATH"] = os.path.join(_test_dir, "test_lancedb")
os.environ["ARS25_CSV_PATH"] = os.path.join(os.path.dirname(__file__), "..", "file-landing", "ars_25.csv")


@pytest.fixture
def sample_csv(tmp_path):
    """Create a minimal test CSV file."""
    csv_content = (
        "chapter_number,chapter_title,chapter_section_range,article_number,"
        "article_title,ars_section,ars_title,ars_url\n"
        '1,MARRIAGE,25-101-25-130,1,Capacity of Persons to Marry,25-101,'
        'Void and prohibited marriages,https://www.azleg.gov/ars/25/00101.htm\n'
        '1,MARRIAGE,25-101-25-130,2,Validity of Marriage,25-111,'
        'Requirement of license and solemnization; covenant marriages,'
        'https://www.azleg.gov/ars/25/00111.htm\n'
        '4,"DISSOLUTION OF MARRIAGE, LEGAL SEPARATION AND ANNULMENT",'
        '25-301-25-381.09,6,Custody and Parenting Time,25-403,'
        '"Legal decision-making; best interests of child",'
        'https://www.azleg.gov/ars/25/00403.htm\n'
    )
    csv_path = tmp_path / "test_ars_25.csv"
    csv_path.write_text(csv_content, encoding="utf-8-sig")
    return str(csv_path)


@pytest.fixture
def mock_embedder():
    """Mock the sentence-transformers embedder to return dummy 384d vectors."""
    dummy_vec = [0.1] * 384

    with patch("ars25.ingestion.embedder.get_model") as mock_get:
        mock_model = MagicMock()
        mock_model.encode.side_effect = lambda texts, **kw: (
            [dummy_vec] * len(texts) if isinstance(texts, list)
            else dummy_vec
        )
        mock_get.return_value = mock_model
        # Also patch embed_query and embed_texts so they use the mock
        with patch("ars25.ingestion.embedder._model", mock_model):
            yield mock_model


@pytest.fixture
def populated_db(tmp_path, mock_embedder):
    """Create a LanceDB with sample data for search tests."""
    import lancedb
    from ars25.core.config import get_settings

    db_path = str(tmp_path / "test_db")
    settings = get_settings()

    # Override settings for test
    with patch.object(settings, "db_path", db_path), \
         patch.object(settings, "table_name", "ars25_chunks"):

        conn = lancedb.connect(db_path)

        # Create sample data
        data = pa.table({
            "section": ["25-101", "25-101", "25-403", "25-403", "25-411"],
            "title": [
                "Void and prohibited marriages",
                "Void and prohibited marriages",
                "Legal decision-making; best interests of child",
                "Legal decision-making; best interests of child",
                "Parenting time",
            ],
            "chapter_number": [1, 1, 4, 4, 4],
            "chapter_title": ["MARRIAGE", "MARRIAGE", "DISSOLUTION", "DISSOLUTION", "DISSOLUTION"],
            "article_number": [1, 1, 6, 6, 6],
            "article_title": [
                "Capacity of Persons to Marry",
                "Capacity of Persons to Marry",
                "Custody and Parenting Time",
                "Custody and Parenting Time",
                "Custody and Parenting Time",
            ],
            "url": [
                "https://www.azleg.gov/ars/25/00101.htm",
                "https://www.azleg.gov/ars/25/00101.htm",
                "https://www.azleg.gov/ars/25/00403.htm",
                "https://www.azleg.gov/ars/25/00403.htm",
                "https://www.azleg.gov/ars/25/00411.htm",
            ],
            "chunk_index": [0, 1, 0, 1, 0],
            "text": [
                "Marriage between parents and children is prohibited.",
                "Marriage between siblings is void.",
                "The court shall determine custody in accordance with best interests of the child.",
                "The court shall consider all relevant factors including wishes of the child.",
                "Each parent is entitled to reasonable parenting time.",
            ],
            "vector": [[0.1] * 384, [0.2] * 384, [0.5] * 384, [0.6] * 384, [0.7] * 384],
        })

        table = conn.create_table("ars25_chunks", data)

        # Patch db module to use our test connection
        with patch("ars25.core.db._connection", conn), \
             patch("ars25.core.db.get_connection", return_value=conn):
            yield conn, db_path
