from sqlalchemy import create_engine, text


def test_marketplace_matcher_accepts_same_product_identity():
    from services.marketplace_product_matcher import score_marketplace_match

    diagnostics = score_marketplace_match(
        "理膚寶水 B5 修復霜 40ml",
        "理膚寶水 全面修復霜 B5 40ml",
        momo_price=699,
        competitor_price=679,
    )

    assert diagnostics.score >= 0.9
    assert diagnostics.hard_veto is False
    assert "brand_match" in diagnostics.tags
    assert "spec_match" in diagnostics.tags


def test_marketplace_matcher_rejects_brand_conflict_even_when_volume_matches():
    from services.marketplace_product_matcher import score_marketplace_match

    diagnostics = score_marketplace_match(
        "【蘭蔻】官方直營 玫瑰霜60ml+玫瑰精露150ml",
        "LOREAL Paris 巴黎萊雅 金致臻顏花蜜奢養膠原輕盈乳霜_60ml",
        momo_price=18765,
        competitor_price=1249,
    )

    assert diagnostics.score < 0.76
    assert diagnostics.hard_veto is True
    assert "brand_conflict" in diagnostics.reasons


def test_marketplace_matcher_rejects_volume_conflict_for_same_brand():
    from services.marketplace_product_matcher import score_marketplace_match

    diagnostics = score_marketplace_match(
        "【CLARINS 克蘭詩】黃金亮眼萃20mlX2囤貨組",
        "【CLARINS克蘭詩】黃金雙萃精華 75ml",
        momo_price=4500,
        competitor_price=3549,
    )

    assert diagnostics.score < 0.76
    assert diagnostics.hard_veto is True
    assert "volume_conflict" in diagnostics.reasons


def test_marketplace_matcher_handles_bundle_piece_count():
    from services.marketplace_product_matcher import score_marketplace_match

    diagnostics = score_marketplace_match(
        "【Relove】馬甲纖纖飲-莓果風味X3盒 共72包",
        "【3入超值組】Relove 馬甲纖纖飲 24包/7克",
        momo_price=4590,
        competitor_price=4590,
    )

    assert diagnostics.score >= 0.76
    assert diagnostics.hard_veto is False


def test_batch_compare_top_uses_latest_momo_price_not_revenue(monkeypatch):
    from services import pchome_crawler

    engine = create_engine("sqlite:///:memory:")
    with engine.begin() as conn:
        conn.execute(text("CREATE TABLE products (id INTEGER PRIMARY KEY, name TEXT, i_code TEXT)"))
        conn.execute(text("CREATE TABLE daily_sales (product_id INTEGER, revenue NUMERIC, date TEXT)"))
        conn.execute(text("CREATE TABLE price_records (id INTEGER PRIMARY KEY, product_id INTEGER, price NUMERIC, timestamp TEXT)"))
        conn.execute(text("INSERT INTO products VALUES (1, '理膚寶水 B5 修復霜 40ml', 'SKU001')"))
        conn.execute(text("INSERT INTO daily_sales VALUES (1, 999999, '2026-05-19')"))
        conn.execute(text("INSERT INTO price_records VALUES (1, 1, 699, '2026-05-19 10:00:00')"))

    calls = []

    def fake_compare_product(name, momo_price, momo_icode=""):
        calls.append((name, momo_price, momo_icode))
        return {"found": True, "momo_price": momo_price}

    monkeypatch.setattr(pchome_crawler, "compare_product", fake_compare_product)

    results = pchome_crawler.batch_compare_top(engine, top_n=1)

    assert results == [{"found": True, "momo_price": 699.0}]
    assert calls == [("理膚寶水 B5 修復霜 40ml", 699.0, "SKU001")]
