from argparse import Namespace
from pathlib import Path

import pytest

from home_agent.cli.main import _build_parser, _handle_retrieval
from home_agent.core.config import (
    AlertsConfig,
    AppConfig,
    BudgetConfig,
    EmbeddingsConfig,
    LLMConfig,
    MemoryConfig,
    PollConfig,
    RetentionConfig,
    RetrievalConfig,
    SqliteVecConfig,
)


def _config(db_path: Path) -> AppConfig:
    return AppConfig(
        poll=PollConfig(),
        budget=BudgetConfig(),
        retention=RetentionConfig(),
        alerts=AlertsConfig(),
        llm=LLMConfig(),
        memory=MemoryConfig(),
        enabled_providers=[],
        sqlite_path=db_path,
        daily_digest_enabled=True,
        embeddings=EmbeddingsConfig(enabled=True, provider="local_sentence_transformers"),
        retrieval=RetrievalConfig(enabled=True),
        sqlite_vec=SqliteVecConfig(),
    )


def test_parser_accepts_retrieval_commands() -> None:
    parser = _build_parser()

    args = parser.parse_args(["retrieval", "doctor"])

    assert args.command == "retrieval"
    assert args.retrieval_command == "doctor"


def test_handle_retrieval_stats_prints_backend_information(
    capsys: pytest.CaptureFixture[str],
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    class FakeBackend:
        backend_name: str = "sqlite_vec"

        def healthcheck(self) -> None:
            return None

        def indexed_count(self) -> int:
            return 7

        def rebuild(self, documents: list[object]) -> None:
            _ = documents

    monkeypatch.setattr(
        "home_agent.cli.main._build_vector_backend",
        lambda config, store: FakeBackend(),
    )
    exit_code = _handle_retrieval(
        _config(tmp_path / "agent.db"),
        Namespace(retrieval_command="stats"),
    )

    captured = capsys.readouterr()
    assert exit_code == 0
    assert "backend=sqlite_vec" in captured.out
    assert "indexed=7" in captured.out


def test_handle_retrieval_doctor_reports_health(
    capsys: pytest.CaptureFixture[str],
    monkeypatch: pytest.MonkeyPatch,
    tmp_path: Path,
) -> None:
    class FakeBackend:
        backend_name: str = "sqlite_vec"

        def healthcheck(self) -> None:
            return None

        def indexed_count(self) -> int:
            return 0

        def rebuild(self, documents: list[object]) -> None:
            _ = documents

    monkeypatch.setattr(
        "home_agent.cli.main._build_vector_backend",
        lambda config, store: FakeBackend(),
    )
    exit_code = _handle_retrieval(
        _config(tmp_path / "agent.db"),
        Namespace(retrieval_command="doctor"),
    )

    captured = capsys.readouterr()
    assert exit_code == 0
    assert "retrieval doctor: ok backend=sqlite_vec" in captured.out
