from utils.momo_url_utils import build_momo_product_url, extract_momo_i_code, is_probable_momo_icode, normalize_momo_product_url


def test_build_momo_product_url_from_code():
    assert build_momo_product_url("12345") == "https://www.momoshop.com.tw/goods/GoodsDetail.jsp?i_code=12345"


def test_build_momo_product_url_empty_returns_none():
    assert build_momo_product_url("") is None
    assert build_momo_product_url(None) is None


def test_normalize_keeps_valid_goodsdetail_url():
    valid = "https://www.momoshop.com.tw/goods/GoodsDetail.jsp?i_code=12345"
    assert normalize_momo_product_url(valid, "12345") == valid


def test_normalize_falls_back_for_javascript_link():
    assert normalize_momo_product_url("javascript:void(0)", "12345") == build_momo_product_url("12345")


def test_normalize_falls_back_for_err404_page():
    assert normalize_momo_product_url(
        "https://www.momoshop.com.tw/ecm/js/err404/EC404.html",
        "12345",
    ) == build_momo_product_url("12345")


def test_normalize_adds_https_for_protocol_relative_url():
    assert normalize_momo_product_url("//www.momoshop.com.tw/goods/GoodsDetail.jsp?i_code=12345", "12345") == (
        "https://www.momoshop.com.tw/goods/GoodsDetail.jsp?i_code=12345"
    )


def test_extract_momo_i_code():
    assert extract_momo_i_code("https://www.momoshop.com.tw/goods/GoodsDetail.jsp?i_code=12345") == "12345"
    assert extract_momo_i_code("/goods/GoodsDetail.jsp?i_code=999") == "999"
    assert extract_momo_i_code("not-a-url") is None


def test_invalid_placeholder_codes():
    assert is_probable_momo_icode("momo_0") is False
    assert is_probable_momo_icode("manual_123") is False
    assert is_probable_momo_icode("pchome_1") is False
    assert is_probable_momo_icode("1234") is True


def test_normalize_blocks_goodsdetail_without_i_code():
    invalid = "https://www.momoshop.com.tw/goods/GoodsDetail.jsp?foo=1"
    assert normalize_momo_product_url(invalid, "12345") == build_momo_product_url("12345")
