from argparse import Namespace
from pathlib import Path

from home_agent.cli.main import _handle_memory
from home_agent.contracts.types import MemoryRuleCandidate
from home_agent.core.config import (
    AlertsConfig,
    AppConfig,
    BudgetConfig,
    LLMConfig,
    MemoryConfig,
    PollConfig,
    RetentionConfig,
)
from home_agent.storage.sqlite_store import SqliteStore


def _config(db_path: Path) -> AppConfig:
    return AppConfig(
        poll=PollConfig(),
        budget=BudgetConfig(),
        retention=RetentionConfig(),
        alerts=AlertsConfig(),
        llm=LLMConfig(),
        memory=MemoryConfig(min_evidence=2, min_confidence=0.7),
        enabled_providers=[],
        sqlite_path=db_path,
        daily_digest_enabled=True,
    )


def test_memory_approve_respects_thresholds(tmp_path: Path) -> None:
    db_path = tmp_path / "memory.db"
    store = SqliteStore(db_path)
    store.save_memory_candidates(
        [
            MemoryRuleCandidate(
                rule_key="subject_token:rare",
                description="rare token",
                evidence_count=1,
                confidence=0.95,
            )
        ]
    )

    cfg = _config(db_path)
    args = Namespace(memory_command="approve", rule_key="subject_token:rare", reason=None)
    exit_code = _handle_memory(cfg, args)
    assert exit_code == 1


def test_memory_reject_command(tmp_path: Path) -> None:
    db_path = tmp_path / "memory.db"
    store = SqliteStore(db_path)
    store.save_memory_candidates(
        [
            MemoryRuleCandidate(
                rule_key="subject_token:promo",
                description="promo token",
                evidence_count=2,
                confidence=0.8,
            )
        ]
    )
    cfg = _config(db_path)
    args = Namespace(memory_command="reject", rule_key="subject_token:promo", reason="noise")
    exit_code = _handle_memory(cfg, args)
    assert exit_code == 0

    rejected = store.list_memory_candidates(status="rejected")
    assert len(rejected) == 1
    assert rejected[0].rule_key == "subject_token:promo"
