import json
import httpx

from timesheet import productimages


def test_exact_codes_do_not_confuse_1c_with_website_ids():
    assert productimages.code("10142911-БК-2585436") == "10142911"
    assert productimages.code("10001020-расп-2403087") == "10001020"
    assert productimages.code("00-09077613") == ""
    assert productimages.code(None) == ""
    assert productimages.defect_code({"article": "236941-БК-2065948", "search_code": "8149412"}) == "236941"
    assert productimages.defect_code({"search_code": "8149412"}) == ""
    assert productimages.discount_code({"origin_product_id": 10001020, "product_code": "00-09077613"}) == "10001020"


def test_shared_catalogue_has_one_entry_per_original_product(tmp_path):
    productimages.register(tmp_path, [{"code": "10142911", "title": "Товар", "sources": "Брак, Уценка"}])
    productimages.register(tmp_path, [{"code": "10142911", "title": "Товар", "sources": "Брак, Уценка, РМБ"}])
    result = productimages.catalogue(tmp_path)
    assert result["total"] == 1
    assert result["counts"] == {"pending": 1}
    assert result["rows"][0]["sources"] == "Брак, Уценка, РМБ"
    assert productimages.catalogue(tmp_path, query="товар")["total"] == 1


def test_legacy_file_is_reused_and_catalogued_without_network(tmp_path, monkeypatch):
    legacy = tmp_path / "old"
    legacy.mkdir()
    (legacy / "10142911.image").write_bytes(b"photo")
    (legacy / "10142911.json").write_text(json.dumps({"mime":"image/png", "source":"https://cdn21vek.by/photo.png", "checked_at":1}))
    root = tmp_path / "catalogue"
    productimages.migrate_legacy(root, legacy)
    monkeypatch.setattr(productimages.rmbimages.httpx, "Client", lambda **kw: (_ for _ in ()).throw(AssertionError("Unexpected network")))
    path, mime = productimages.resolve(root, "10142911")
    assert path.read_bytes() == b"photo" and mime == "image/png"
    result = productimages.catalogue(root, status="found")
    assert result["total"] == 1
    assert result["rows"][0]["source_url"] == "https://cdn21vek.by/photo.png"


def test_missing_is_distinct_from_request_error(tmp_path, monkeypatch):
    photos = tmp_path / "photos"
    photos.mkdir()
    import time
    (photos / "123.json").write_text(json.dumps({"status":"missing", "checked_at":time.time()}))
    (photos / "456.json").write_text(json.dumps({"status":"error", "checked_at":time.time(), "retry_after":300}))
    monkeypatch.setattr(productimages.rmbimages.httpx, "Client", lambda **kw: (_ for _ in ()).throw(AssertionError("Unexpected network")))
    assert productimages.resolve(tmp_path, "123") is None
    assert productimages.resolve(tmp_path, "456") is None
    counts = productimages.catalogue(tmp_path)["counts"]
    assert counts["missing"] == counts["error"] == 1


def test_dead_photo_link_is_missing_but_rate_limit_is_retryable(tmp_path):
    def respond(request):
        if request.url.host == "gate.21vek.by":
            return httpx.Response(200, json={"data":[{"group_type":"products", "items":[{
                "product_id":"123", "image":"https://cdn21vek.by/image.png"}]}]})
        return httpx.Response(404)
    with httpx.Client(transport=httpx.MockTransport(respond)) as client:
        assert productimages.resolve(tmp_path, "123", client=client) is None
    assert productimages.catalogue(tmp_path)["counts"] == {"missing":1}
    with httpx.Client(transport=httpx.MockTransport(lambda request:httpx.Response(429))) as client:
        assert productimages.resolve(tmp_path, "456", client=client) is None
    assert productimages.catalogue(tmp_path)["counts"]["error"] == 1
