from argparse import Namespace
from datetime import UTC, datetime
from pathlib import Path

from home_agent.cli.main import _build_parser, _handle_embeddings
from home_agent.contracts.types import Item, ItemKind, UrgencyDecision, UrgencyLabel
from home_agent.core.config import (
    AlertsConfig,
    AppConfig,
    BudgetConfig,
    EmbeddingsConfig,
    LLMConfig,
    MemoryConfig,
    PollConfig,
    RetentionConfig,
    RetrievalConfig,
)
from home_agent.storage.sqlite_store import SqliteStore


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

    args = parser.parse_args(["embeddings", "backfill", "--dry-run", "--kind", "email"])

    assert args.command == "embeddings"
    assert args.embeddings_command == "backfill"
    assert args.dry_run is True
    assert args.kind == "email"


def test_handle_embeddings_backfill_dry_run(tmp_path: Path) -> None:
    store = SqliteStore(tmp_path / "agent.db")
    store.save_item(
        Item(
            provider="gmail",
            external_id="msg-1",
            kind=ItemKind.EMAIL,
            received_at=datetime.now(tz=UTC),
            subject="Deadline notice",
            sender="staff@example.com",
            metadata={"snippet": "Please reply"},
        ),
        UrgencyDecision(
            score=0.5,
            label=UrgencyLabel.MEDIUM,
            reasons=["seed"],
            used_llm=False,
        ),
    )

    cfg = AppConfig(
        poll=PollConfig(),
        budget=BudgetConfig(),
        retention=RetentionConfig(),
        alerts=AlertsConfig(),
        llm=LLMConfig(),
        memory=MemoryConfig(),
        enabled_providers=[],
        sqlite_path=tmp_path / "agent.db",
        daily_digest_enabled=True,
        embeddings=EmbeddingsConfig(enabled=True, provider="local", model="stub-v1", batch_size=5),
        retrieval=RetrievalConfig(),
    )
    args = Namespace(
        embeddings_command="backfill",
        provider=None,
        model=None,
        batch_size=None,
        limit=None,
        since=None,
        kind="email",
        dry_run=True,
        rebuild=False,
    )

    exit_code = _handle_embeddings(cfg, args)

    assert exit_code == 0
    assert store.get_item_embedding("gmail", "msg-1", "local", "stub-v1") is None
