# backend/tests/test_suggester.py — 반복 패턴 탐지
from app.automation import suggester
from app.automation.event_bus import EventBus
from app.automation.events import AUTOMATION_SUGGESTED
from app.models import AutomationRunLog


def _add_digest_logs(s, n):
    for i in range(n):
        s.add(
            AutomationRunLog(
                id=f"dg{i}",
                time="18:30",
                rule="뉴스레터는 저녁에",
                rule_id=None,
                text=f"뉴스레터 {i}통 → 저녁 다이제스트로 묶음",
                sort_order=100 + i,
            )
        )
    s.commit()


def test_scan_below_threshold_no_suggestion(client, session):
    s, engine = session
    # 시드 run_log 에는 '다이제스트' 1건뿐 → 임계(3) 미달
    created = suggester.scan(s)
    assert created == []


def test_scan_above_threshold_creates_and_publishes(client, session):
    s, engine = session
    _add_digest_logs(s, 3)
    bus = EventBus()
    created = suggester.scan(s, bus)
    assert len(created) == 1
    assert created[0].offer_name == "아침에도 다이제스트"
    assert any(e.type == AUTOMATION_SUGGESTED for e in bus.history)


def test_scan_dedupes(client, session):
    s, engine = session
    _add_digest_logs(s, 4)
    first = suggester.scan(s)
    second = suggester.scan(s)  # 이미 존재 → 재생성 안 함
    assert len(first) == 1 and second == []


def test_scan_endpoint(client):
    # API 경로(수동 스캔) — 시드만으로는 임계 미달이라 빈 생성
    r = client.post("/api/automation/suggest/scan").json()
    assert r == {"created": []}
