def test_format_realestate_match_full_card_single():
    from app.telegram.realestate_message import format_realestate_matches
    matches = [{
        "id": 1,
        "match_score": 90,
        "house_nm": "디에이치 강남",
        "region_name": "서울특별시",
        "district": "강남구",
        "is_speculative_area": "Y",
        "is_price_cap": "Y",
        "receipt_start": "2026-05-15",
        "receipt_end": "2026-05-19",
        "match_reasons": ["광역 일치", "자치구 S티어: 강남구 (+25)", "예산 범위"],
        "eligible_types": ["일반1순위", "특별-신혼부부"],
        "pblanc_url": "https://example.com/p/1",
    }]
    text = format_realestate_matches(matches)
    assert "디에이치 강남" in text
    assert "90점" in text
    assert "강남구" in text
    assert "2026-05-15" in text


def test_format_realestate_match_compact_when_three_or_more():
    from app.telegram.realestate_message import format_realestate_matches
    matches = [
        {"id": i, "match_score": 90 - i, "house_nm": f"단지{i}", "district": "강남구",
         "region_name": "서울특별시", "receipt_start": "2026-05-15", "receipt_end": "2026-05-19",
         "match_reasons": [], "eligible_types": [], "pblanc_url": ""}
        for i in range(3)
    ]
    text = format_realestate_matches(matches)
    assert "3건" in text or "3" in text
    for i in range(3):
        assert f"단지{i}" in text


def test_build_keyboard_single_match_has_bookmark_and_url():
    from app.telegram.realestate_message import build_match_keyboard
    matches = [{"id": 42, "pblanc_url": "https://example.com/p/42"}]
    kb = build_match_keyboard(matches)
    rows = kb["inline_keyboard"]
    flat = [b for row in rows for b in row]
    assert any(b.get("callback_data", "").startswith("realestate_bookmark_42") for b in flat)
    assert any(b.get("url") == "https://example.com/p/42" for b in flat)


def test_build_keyboard_multi_matches_uses_dashboard_link():
    from app.telegram.realestate_message import build_match_keyboard
    matches = [{"id": i, "pblanc_url": ""} for i in range(3)]
    kb = build_match_keyboard(matches)
    flat = [b for row in kb["inline_keyboard"] for b in row]
    # 3건 이상이면 [전체 보기] 단일 URL 버튼
    assert any("전체" in b.get("text", "") for b in flat)


def test_build_keyboard_empty_returns_none():
    from app.telegram.realestate_message import build_match_keyboard
    assert build_match_keyboard([]) is None
