from pathlib import Path
import sqlite3

from auraindex.analyzers.db_introspection import introspect_existing_indexes_from_live_db
from auraindex.pipeline import ScanConfig, run_scan


def _prepare_sqlite_db(db_path: Path) -> None:
    connection = sqlite3.connect(str(db_path))
    try:
        connection.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT, status TEXT)")
        connection.execute("CREATE INDEX ix_users_email ON users (email)")
        connection.commit()
    finally:
        connection.close()


def test_sqlite_live_introspection_discovers_indexes(tmp_path: Path) -> None:
    db_path = tmp_path / "sample.db"
    _prepare_sqlite_db(db_path)

    indexes, warnings, summary = introspect_existing_indexes_from_live_db(
        dialect="sqlite",
        db_path=str(db_path),
    )

    assert warnings == []
    assert summary["connected"] is True
    assert summary["discovered_indexes"] >= 1
    assert any(index.table == "users" and index.columns == ["email"] for index in indexes)


def test_pipeline_schema_checks_use_live_sqlite_indexes(tmp_path: Path) -> None:
    db_path = tmp_path / "sample.db"
    _prepare_sqlite_db(db_path)

    sample = tmp_path / "queries.sql"
    sample.write_text(
        """
SELECT id FROM users WHERE email = 'a@example.com';
SELECT id FROM users WHERE email = 'a@example.com';
""".strip(),
        encoding="utf-8",
    )

    result = run_scan(
        ScanConfig(
            target_path=tmp_path,
            dialect="sqlite",
            extensions={".sql"},
            min_support=1,
            max_indexes_per_table=4,
            enable_db_introspection=True,
            db_dialect="sqlite",
            db_path=db_path,
        )
    )

    assert result.suggestions == []
    live_meta = result.metadata.get("live_db_introspection", {})
    assert live_meta.get("connected") is True
    schema_meta = result.metadata.get("schema_checks", {})
    summary = schema_meta.get("summary", {})
    assert summary.get("skipped_suggestions", 0) >= 1


def test_sqlite_live_introspection_requires_db_path() -> None:
    indexes, warnings, summary = introspect_existing_indexes_from_live_db(dialect="sqlite", db_path=None)
    assert indexes == []
    assert warnings
    assert summary["connected"] is False
