import sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from app.notifiers.telegram_lotto import _format_evolution_report


def test_evolution_report_winner_4plus():
    eval_result = {
        "ok": True,
        "draw_no": 1225,
        "week_start": "2026-05-18",
        "winner": {
            "day_of_week": 3,
            "weight": [0.18, 0.32, 0.20, 0.22, 0.08],
            "avg_score": 0.42,
            "max_correct": 4,
            "n_picks": 5,
        },
        "new_base": [0.18, 0.32, 0.20, 0.22, 0.08],
        "previous_base": [0.20, 0.20, 0.20, 0.20, 0.20],
        "update_reason": "winner_4plus",
        "per_day": [
            {"day_of_week": 0, "avg_score": 0.20, "max_correct": 2},
            {"day_of_week": 3, "avg_score": 0.42, "max_correct": 4},
        ],
    }
    current_base = [0.20, 0.20, 0.20, 0.20, 0.20]
    text = _format_evolution_report(eval_result, current_base)
    assert "🧬" in text
    assert "1225" in text
    assert "목요일" in text or "Winner" in text
    assert "4개 일치" in text or "max=4" in text
    assert "winner_4plus" in text


def test_evolution_report_unchanged():
    eval_result = {
        "ok": True,
        "draw_no": 1226,
        "week_start": "2026-05-25",
        "winner": {
            "day_of_week": 1,
            "weight": [0.21, 0.19, 0.20, 0.20, 0.20],
            "avg_score": 0.10,
            "max_correct": 2,
            "n_picks": 5,
        },
        "new_base": [0.20, 0.20, 0.20, 0.20, 0.20],
        "update_reason": "unchanged",
        "per_day": [],
    }
    current_base = [0.20, 0.20, 0.20, 0.20, 0.20]
    text = _format_evolution_report(eval_result, current_base)
    assert "unchanged" in text or "유지" in text
    assert "2개 일치" in text or "max=2" in text


def test_evolution_report_empty_returns_empty():
    """evaluate가 ok=False면 빈 문자열 (발송 skip)."""
    text = _format_evolution_report({"ok": False, "reason": "no_trials"}, [0.2]*5)
    assert text == ""


def test_evolution_report_uses_previous_base_for_diff():
    """previous_base와 new_base 차이가 메시지 diff에 정확히 반영됨."""
    eval_result = {
        "ok": True,
        "draw_no": 1227,
        "winner": {
            "day_of_week": 0,
            "weight": [0.30, 0.20, 0.20, 0.20, 0.10],
            "avg_score": 0.50,
            "max_correct": 4,
            "n_picks": 5,
        },
        "new_base": [0.30, 0.20, 0.20, 0.20, 0.10],
        "previous_base": [0.20, 0.20, 0.20, 0.20, 0.20],
        "update_reason": "winner_4plus",
    }
    # current_base는 stale (post-update 값) — previous_base가 우선 적용되어야 함
    text = _format_evolution_report(eval_result, [0.30, 0.20, 0.20, 0.20, 0.10])
    # freq: 0.20 → 0.30 (+0.10 = "++")
    # divers: 0.20 → 0.10 (-0.10 = "--")
    assert "0.20 → 0.30" in text   # freq 증가
    assert "0.20 → 0.10" in text   # divers 감소
    assert "(++)" in text or "(+)" in text   # freq marker
    assert "(--)" in text or "(-)" in text   # divers marker
