import statistics
def _deals(vals, key="deposit", dt="전세"):
    return [{key: v, "deal_type": dt} for v in vals]

def test_compute_safety_tiers():
    from app.listing_matcher import compute_safety
    deals = _deals([40000, 42000, 44000, 43000])  # median ~42500
    assert compute_safety(28000, "전세", deals)["tier"] == "안전"    # 0.66
    assert compute_safety(32000, "전세", deals)["tier"] == "주의"    # 0.75
    assert compute_safety(38000, "전세", deals)["tier"] == "위험"    # 0.89
    assert compute_safety(28000, "전세", _deals([40000, 41000]))["tier"] == "보류"  # 표본<3

def test_compute_valuation_tiers():
    from app.listing_matcher import compute_valuation
    deals = _deals([80000, 88000, 90000, 87000], key="sale_amount", dt="매매")  # median ~87500
    assert compute_valuation(83000, deals)["tier"] == "저평가"    # 0.95
    assert compute_valuation(89000, deals)["tier"] == "시세"      # 1.02
    assert compute_valuation(95000, deals)["tier"] == "고가"      # 1.09

def test_match_listing_rent_deposit_cap():
    from app.listing_matcher import match_listing
    crit = {"dongs": ["신대방동"], "deal_types": ["전세"], "max_deposit": 32000,
            "min_area": 40.0, "house_types": ["아파트"]}
    ok = match_listing(crit, {"deal_type": "전세", "deposit": 29000, "area_exclusive": 42.0,
                              "dong": "신대방동"}, budget={"max_deposit": 45000})
    assert ok["passed"] is True
    over = match_listing(crit, {"deal_type": "전세", "deposit": 40000, "area_exclusive": 42.0,
                                "dong": "신대방동"}, budget={"max_deposit": 45000})
    assert over["passed"] is False
