"""AvartenConnector with WordPress REST as the primary structured source.

Everything runs against FakeSession; nothing touches the network. The legacy
HTML paths are stubbed to prove when they are (and are not) used.
"""
import pytest

from integrations.avarten.rest_client import AvartenRestClient, MEDIA_ENDPOINT, PROPERTIES_ENDPOINT
from integrations.avarten import connector as avarten_connector
from integrations.avarten.connector import AvartenConnector
from InvestmentWebsite.offers.validator import validate_canonical_offer
from tests.avarten.avarten_rest_fixtures import (
    BASE,
    FakeResponse,
    FakeSession,
    additional_features,
    connection_error,
    media_record,
    rest_property,
)


class FakeSite:
    """A tiny in-memory Avarten WordPress site."""

    def __init__(self, properties=(), media=(), *, media_error=None, list_error=None, list_status=200):
        self.properties = list(properties)
        self.media = {record["id"]: record for record in media}
        self.media_error = media_error
        self.list_error = list_error
        self.list_status = list_status
        self.session = FakeSession(self.handle)

    def handle(self, path, params):
        if path == MEDIA_ENDPOINT:
            if self.media_error:
                return self.media_error
            ids = [int(part) for part in params["include"].split(",")]
            return FakeResponse([self.media[i] for i in ids if i in self.media])
        if path == PROPERTIES_ENDPOINT:
            if self.list_error:
                return self.list_error
            if self.list_status != 200:
                return FakeResponse(status_code=self.list_status)
            items = self.properties
            if "slug" in params:
                items = [item for item in items if item["slug"] == params["slug"]]
            return FakeResponse(items, headers={"X-WP-TotalPages": "1"})
        if path.startswith(PROPERTIES_ENDPOINT + "/"):
            post_id = int(path.rsplit("/", 1)[1])
            for item in self.properties:
                if item["id"] == post_id:
                    return FakeResponse(item)
            return FakeResponse({"code": "rest_post_invalid_id"}, status_code=404)
        raise AssertionError(path)

    def connector(self):
        return AvartenConnector(rest_client=AvartenRestClient(session=self.session))


def _normalize(record, images=None, **extra):
    return AvartenConnector().normalize_offer(
        {"kind": "rest_offer", "offer": record, "images": images or [], **extra}
    )


def _shape(value, *, skip=("payload",)):
    """Nested key structure; raw.payload is source-specific by design."""
    if not isinstance(value, dict):
        return None
    return {key: (None if key in skip else _shape(item, skip=skip)) for key, item in value.items()}


# ------------------------------------------------------------ normalization

class TestNormalizeRestOffer:
    def test_maps_identity_and_source(self):
        canonical = _normalize(rest_property())

        assert canonical["schema_version"] == "1.0"
        assert canonical["source"] == {
            "platform": "avarten",
            "external_id": "26161",
            "external_url": f"{BASE}/property/laya-courtyard-at-dubai-studio-city/",
        }
        assert canonical["identity"]["offer_id"] == "26161"  # WP post id, never the translated title
        assert canonical["identity"]["slug"] == "laya-courtyard-at-dubai-studio-city"
        assert canonical["seo"]["canonical_url"] == canonical["source"]["external_url"]

    def test_title_is_html_unescaped_english_rest_title(self):
        canonical = _normalize(
            rest_property(title={"rendered": "Costa Mare at Al Marjan Island, Ras Al Khaimah &#8211; Ellington"})
        )
        assert canonical["listing"]["title"] == "Costa Mare at Al Marjan Island, Ras Al Khaimah – Ellington"

    def test_description_is_text_extracted_from_content_html(self):
        canonical = _normalize(rest_property())
        text = canonical["listing"]["description_text"]
        assert text.startswith("Laya Courtyard at Dubai Studio City by DECA properties")
        assert "\n\n" in text and "<p>" not in text
        assert "Second paragraph – details." in text.replace("\xa0", " ")
        assert canonical["raw"]["payload"]["rest_record"]["content"]["rendered"].startswith("<p>")

    @pytest.mark.parametrize(
        "raw_price,expected",
        [("699000", 699000), ("660,000", 660000), ("1 300 000", 1300000), ("1.234.567", 1234567), ("1,5", 1.5)],
    )
    def test_price_parsing(self, raw_price, expected):
        canonical = _normalize(rest_property(meta={"fave_property_price": [raw_price]}))
        assert canonical["pricing"]["amount"] == expected
        assert canonical["pricing"]["period"] == "total"

    @pytest.mark.parametrize("raw_price", ["", "abc", "0", "-5", "1,2,3", None])
    def test_unusable_price_is_none_not_a_guess(self, raw_price):
        canonical = _normalize(rest_property(meta={"fave_property_price": [raw_price]}))
        assert canonical["pricing"]["amount"] is None
        assert canonical["pricing"]["currency"] == "unknown"

    def test_currency_comes_from_price_label_and_is_aed(self):
        pricing = _normalize(rest_property())["pricing"]
        assert pricing["currency"] == "AED"
        assert pricing["price_label"] == "699,000 AED/-"

    def test_currency_defaults_to_aed_when_label_missing_and_says_so(self):
        canonical = _normalize(rest_property(meta={"fave_prop-price": [""]}))
        assert canonical["pricing"]["currency"] == "AED"
        assert canonical["raw"]["payload"]["price_currency_source"] == "source_default"
        assert canonical["pricing"]["price_label"] == "699 000 AED"

    def test_foreign_currency_in_label_is_not_relabelled_as_aed(self):
        canonical = _normalize(rest_property(meta={"fave_prop-price": ["699,000 USD"]}))
        assert canonical["pricing"]["currency"] == "unknown"

    def test_coordinates_and_location(self):
        location = _normalize(rest_property())["listing"]["location"]
        assert location["lat"] == pytest.approx(25.03605241282)
        assert location["lng"] == pytest.approx(55.231962187092)
        assert location["district"] == "Dubai Studio City"
        assert location["city"] == "Dubai"
        assert location["address_label"] == "Dubai Studio City, Dubai"

    def test_coordinates_fall_back_to_combined_meta_and_reject_garbage(self):
        record = rest_property(
            meta={"houzez_geolocation_lat": ["north"], "houzez_geolocation_long": [""]}
        )
        location = _normalize(record)["listing"]["location"]
        assert location["lat"] == pytest.approx(25.03605241282)  # from "lat,lng,zoom"

        broken = rest_property(
            meta={
                "houzez_geolocation_lat": ["north"],
                "houzez_geolocation_long": [""],
                "fave_property_location": ["nonsense"],
            }
        )
        location = _normalize(broken)["listing"]["location"]
        assert location["lat"] is None and location["lng"] is None

    def test_city_only_when_area_equals_city(self):
        record = rest_property(meta={"fave_property_map_address": ["Dubai"], "fave_property_address": ["Dubai"]})
        assert _normalize(record)["listing"]["location"]["address_label"] == "Dubai"

    @pytest.mark.parametrize(
        "status_class,market,label",
        [
            ("property_status-primary", "primary", "Pierwotny"),
            ("property_status-secondary", "secondary", "Wtórny"),
        ],
    )
    def test_primary_secondary_status(self, status_class, market, label):
        record = rest_property(class_list=["property", "property_type-apartments", status_class])
        canonical = _normalize(record)
        assert canonical["listing"]["market_type"] == market
        assert canonical["raw"]["payload"]["status"] == label  # what the catalog card badge reads
        assert canonical["raw"]["payload"]["market_status"] == market

    def test_missing_status_is_unknown_not_primary(self):
        canonical = _normalize(rest_property(class_list=["property"]))
        assert canonical["listing"]["market_type"] == "unknown"
        assert canonical["raw"]["payload"]["status"] is None

    def test_property_types_are_kept_as_labels_and_slugs(self):
        record = rest_property(class_list=["property_type-penthouses", "property_type-villas", "property_type-lofts"])
        payload = _normalize(record)["raw"]["payload"]
        assert payload["property_type"] == ["Penthousy", "Wille", "Lofts"]
        assert payload["property_type_slugs"] == ["penthouses", "villas", "lofts"]
        assert _normalize(record)["listing"]["property_type"] == "unknown"  # mixed types: no fake enum

    def test_developer_handover_and_payment_plan(self):
        canonical = _normalize(rest_property())
        payload = canonical["raw"]["payload"]
        assert payload["developer"] == "Deca Development"
        assert payload["handover"] == "Q4 - 2026"
        assert canonical["financials"]["payment_plan"] == [
            {"stage": "Down Payment", "value": "10%"},
            {"stage": "During Construction", "value": "40%"},
            {"stage": "On Handover", "value": "20%"},
            {"stage": "Post Handover", "value": "30%"},
        ]
        assert payload["payment_plan"]["Down Payment"] == "10%"

    def test_timestamps_and_raw_modified(self):
        canonical = _normalize(rest_property())
        assert canonical["status"]["published_at"] == "2025-04-04T12:34:54Z"
        assert canonical["status"]["updated_at"] == "2025-04-04T14:48:52Z"
        assert canonical["raw"]["payload"]["modified"] == "2025-04-04T14:48:52"
        assert canonical["raw"]["payload"]["data_source"] == "wp_rest"

    def test_featured_offer_gets_label(self):
        assert _normalize(rest_property())["status"]["labels"] == ["Wyróżniony"]
        assert _normalize(rest_property(meta={"fave_featured": ["0"]}))["status"]["labels"] == []

    def test_area_and_floor_are_never_invented(self):
        record = rest_property(
            content={"rendered": "<p>Units from 470 to 4,416 sq.ft. on the 12th floor.</p>"}
        )
        metrics = _normalize(record)["metrics"]
        for key in ("area_m2", "usable_area_m2", "plot_area_m2", "floor", "floors_total", "rooms"):
            assert metrics[key] is None

    # bedrooms / bathrooms ---------------------------------------------------

    def test_bedroom_range_is_not_collapsed_to_a_number(self):
        canonical = _normalize(rest_property())  # fave_bedroom = 1, 2; headline "2"
        assert canonical["metrics"]["bedrooms"] is None
        payload = canonical["raw"]["payload"]
        assert payload["beds_raw"] == "1, 2" and payload["bedrooms_options"] == [1, 2]

    def test_single_bedroom_option_is_a_number(self):
        record = rest_property(meta={"fave_bedroom": ["6"], "fave_property_bedrooms": ["6"]})
        assert _normalize(record)["metrics"]["bedrooms"] == 6

    def test_headline_only_bedrooms_and_non_numeric_headline(self):
        headline_only = rest_property(meta={"fave_bedroom": [], "fave_property_bedrooms": ["3"]})
        assert _normalize(headline_only)["metrics"]["bedrooms"] == 3
        multiple = rest_property(meta={"fave_bedroom": [], "fave_property_bedrooms": ["Multiple"]})
        canonical = _normalize(multiple)
        assert canonical["metrics"]["bedrooms"] is None
        assert canonical["raw"]["payload"]["beds_raw"] == "Multiple"

    def test_bathrooms(self):
        assert _normalize(rest_property())["metrics"]["bathrooms"] == 2
        assert _normalize(rest_property(meta={"fave_property_bathrooms": ["many"]}))["metrics"]["bathrooms"] is None

    # robustness -------------------------------------------------------------

    def test_minimal_record_with_missing_optional_fields(self):
        canonical = _normalize({"id": 7, "title": {"rendered": "Bare"}})

        assert canonical["identity"]["offer_id"] == "7"
        assert canonical["listing"]["title"] == "Bare"
        assert canonical["pricing"]["amount"] is None
        assert canonical["financials"]["payment_plan"] == []
        assert canonical["media"] == {"cover_image": None, "gallery": [], "video": None}
        assert canonical["listing"]["location"]["address_label"] is None
        assert validate_canonical_offer(canonical) == (True, [])

    def test_empty_title_falls_back_like_the_legacy_normalizer(self):
        assert _normalize({"id": 1, "title": {"rendered": ""}})["listing"]["title"] == "Nieruchomość"

    def test_malformed_fields_do_not_raise(self):
        record = rest_property(
            property_meta="not-a-dict",
            class_list="not-a-list",
            title=None,
            id="26161",
        )
        canonical = _normalize(record)
        assert canonical["pricing"]["amount"] is None
        assert canonical["listing"]["title"] == "Nieruchomość"
        # id is not an int -> identity falls back to the link, never to a guess
        assert canonical["identity"]["offer_id"] == record["link"]
        assert validate_canonical_offer(canonical) == (True, [])

    def test_undecodable_additional_features_are_skipped(self):
        record = rest_property(meta={"additional_features": ["a:2:{garbage"]})
        assert _normalize(record)["financials"]["payment_plan"] == []

    def test_payment_plan_entries_without_value_are_dropped(self):
        record = rest_property(meta={"additional_features": [additional_features(("Down Payment", "10%"), ("Empty", ""))]})
        assert _normalize(record)["financials"]["payment_plan"] == [{"stage": "Down Payment", "value": "10%"}]

    # contract ---------------------------------------------------------------

    def test_shape_matches_legacy_canonical_offer_and_validates(self):
        rest = _normalize(rest_property(), images=[f"{BASE}/a.jpg"])
        legacy = AvartenConnector().normalize_offer({"kind": "catalog_offer", "offer": {"title": "T"}})

        assert _shape(rest) == _shape(legacy)  # identical key structure
        assert validate_canonical_offer(rest) == (True, [])

    def test_images_feed_cover_and_gallery(self):
        canonical = _normalize(rest_property(), images=[f"{BASE}/1.jpg", f"{BASE}/2.jpg"])
        assert canonical["media"]["cover_image"] == f"{BASE}/1.jpg"
        assert canonical["media"]["gallery"] == [f"{BASE}/1.jpg", f"{BASE}/2.jpg"]
        assert canonical["seo"]["og_image"] == f"{BASE}/1.jpg"

    def test_unsupported_kind_still_raises(self):
        with pytest.raises(ValueError, match="Unsupported avarten raw offer kind"):
            AvartenConnector().normalize_offer({"kind": "nope"})


# ------------------------------------------------------------------ catalog

def _catalog_site(**kwargs):
    older = rest_property(id=100, slug="older", date_gmt="2025-01-01T00:00:00", featured_media=0, meta={"fave_featured": ["0"], "fave_property_price": ["900000"]})
    newer = rest_property(id=200, slug="newer", date_gmt="2025-06-01T00:00:00", featured_media=0, meta={"fave_featured": ["0"], "fave_property_price": ["800000"]})
    featured_old = rest_property(id=300, slug="featured-old", date_gmt="2025-02-01T00:00:00", featured_media=26178)
    cheap = rest_property(id=400, slug="too-cheap", meta={"fave_property_price": ["300000"]})
    comma = rest_property(id=500, slug="comma-price", date_gmt="2025-03-01T00:00:00", featured_media=0, meta={"fave_featured": ["0"], "fave_property_price": ["660,000"]})
    return FakeSite([older, newer, featured_old, cheap, comma], [media_record(26178, "Laya-cover")], **kwargs)


class TestCatalog:
    def test_order_is_featured_first_then_newest_and_price_range_is_applied(self):
        site = _catalog_site()
        items, meta = site.connector().fetch_catalog({}, 1, 24)

        slugs = [item["offer"]["slug"] for item in items]
        assert slugs == ["featured-old", "newer", "comma-price", "older"]  # "too-cheap" < MIN_PRICE
        assert all(item["kind"] == "rest_offer" for item in items)
        assert meta == {"total_records": 4, "current_page": 1, "per_page": 24, "total_pages": 1, "max_pages": 1}

    def test_pagination_is_computed_locally(self):
        site = _catalog_site()
        connector = site.connector()

        page1, meta1 = connector.fetch_catalog({}, 1, 3)
        page2, meta2 = connector.fetch_catalog({}, 2, 3)
        page9, meta9 = connector.fetch_catalog({}, 9, 3)

        assert [i["offer"]["slug"] for i in page1] == ["featured-old", "newer", "comma-price"]
        assert [i["offer"]["slug"] for i in page2] == ["older"]
        assert meta1["total_pages"] == meta2["total_pages"] == 2
        assert page9 == [] and meta9["current_page"] == 9

    def test_catalog_uses_one_batched_media_request_for_covers(self):
        site = _catalog_site()
        items, _ = site.connector().fetch_catalog({}, 1, 24)

        assert len(site.session.calls_to(MEDIA_ENDPOINT)) == 1
        assert items[0]["images"] == [f"{BASE}/wp-content/uploads/2025/04/Laya-cover-592x444.jpg"]
        assert items[1]["images"] == []  # no featured media -> no cover, no guess

    def test_catalog_list_request_excludes_content_but_keeps_needed_meta(self):
        site = _catalog_site()
        site.connector().fetch_catalog({}, 1, 24)
        fields = site.session.calls_to(PROPERTIES_ENDPOINT)[0]["_fields"].split(",")
        assert "content" not in fields
        assert "property_meta.fave_property_price" in fields and "class_list" in fields

    def test_media_failure_keeps_catalog_without_covers(self):
        site = _catalog_site(media_error=connection_error())
        items, _ = site.connector().fetch_catalog({}, 1, 24)
        assert len(items) == 4 and all(item["images"] == [] for item in items)

    def test_normalized_catalog_item_matches_public_contract(self):
        site = _catalog_site()
        connector = site.connector()
        items, _ = connector.fetch_catalog({}, 1, 24)

        canonical = connector.normalize_offer(items[0])
        assert canonical["media"]["gallery"] and canonical["media"]["cover_image"]
        assert validate_canonical_offer(canonical) == (True, [])

    @pytest.mark.parametrize(
        "site_kwargs",
        [
            {"list_error": connection_error()},
            {"list_status": 503},
        ],
    )
    def test_rest_failure_falls_back_to_html_listing(self, monkeypatch, site_kwargs):
        sentinel = ([{"kind": "catalog_offer", "offer": {"title": "html"}}], {"total_pages": 3})
        monkeypatch.setattr(AvartenConnector, "_fetch_catalog_html", lambda self, page, per_page: sentinel)

        assert _catalog_site(**site_kwargs).connector().fetch_catalog({}, 1, 24) == sentinel

    def test_empty_rest_catalog_is_treated_as_failure_not_as_no_offers(self, monkeypatch):
        sentinel = ([], {"total_pages": 1})
        monkeypatch.setattr(AvartenConnector, "_fetch_catalog_html", lambda self, page, per_page: sentinel)

        assert FakeSite([]).connector().fetch_catalog({}, 1, 24) == sentinel

    def test_rest_and_html_both_failing_raises_instead_of_returning_fake_data(self, monkeypatch):
        def html_fails(self, page, per_page):
            raise RuntimeError("html down")

        monkeypatch.setattr(AvartenConnector, "_fetch_catalog_html", html_fails)
        with pytest.raises(RuntimeError, match="html down"):
            _catalog_site(list_error=connection_error()).connector().fetch_catalog({}, 1, 24)

    def test_html_fallback_items_are_marked(self, monkeypatch):
        monkeypatch.setattr(avarten_connector, "fetch_html", lambda page: "<html/>")
        monkeypatch.setattr(avarten_connector, "parse_listings", lambda page_html: [{"title": "T", "offer_id": "hz-1"}])
        monkeypatch.setattr(avarten_connector, "get_max_pages", lambda page_html: 2)

        items, meta = AvartenConnector()._fetch_catalog_html(1, 24)
        assert items[0]["offer"]["data_source"] == "html" and meta["total_pages"] == 2


# ------------------------------------------------------------ single offer

def _detail_site(**kwargs):
    record = rest_property()
    media = [
        media_record(26162, "Laya-21"),
        media_record(26163, "Laya-02"),
        media_record(26178, "Laya-cover"),
    ]  # 26169 is a deleted attachment: present in meta, absent from the media library
    return FakeSite([record], media, **kwargs)


class TestFetchOffer:
    @pytest.mark.parametrize(
        "identifier",
        [
            {"url": f"{BASE}/property/laya-courtyard-at-dubai-studio-city/"},
            {"url": f"{BASE}/pl/property/laya-courtyard-at-dubai-studio-city/"},  # old public tokens
            {"url": "ignored", "listing_id": 26161},
            {"url": "ignored", "offer_id": "hz-26161"},
        ],
    )
    def test_resolves_by_url_slug_listing_id_or_offer_id(self, identifier):
        raw = _detail_site().connector().fetch_offer(identifier)

        assert raw["kind"] == "rest_offer"
        assert raw["offer"]["id"] == 26161

    def test_gallery_follows_meta_order_uses_gallery_size_and_skips_missing_media(self):
        site = _detail_site()
        raw = site.connector().fetch_offer({"url": f"{BASE}/property/laya-courtyard-at-dubai-studio-city/"})

        assert raw["images"] == [
            f"{BASE}/wp-content/uploads/2025/04/Laya-21-1170x785.jpg",
            f"{BASE}/wp-content/uploads/2025/04/Laya-02-1170x785.jpg",
        ]
        assert raw["images_source"] == "rest_media"
        assert len(site.session.calls_to(MEDIA_ENDPOINT)) == 1  # no per-image requests

    def test_detail_request_asks_for_content(self):
        site = _detail_site()
        site.connector().fetch_offer({"listing_id": 26161})
        assert "content" in site.session.calls_to(f"{PROPERTIES_ENDPOINT}/26161")[0]["_fields"].split(",")

    def test_unknown_offer_is_none_and_html_is_not_consulted(self, monkeypatch):
        def html_must_not_run(self, identifier):
            raise AssertionError("HTML fallback used for a REST-confirmed missing offer")

        monkeypatch.setattr(AvartenConnector, "_fetch_offer_html", html_must_not_run)
        site = _detail_site()

        assert site.connector().fetch_offer({"url": f"{BASE}/property/does-not-exist/"}) is None
        assert site.connector().fetch_offer({"listing_id": 1}) is None

    def test_gallery_falls_back_to_featured_image_when_meta_has_no_gallery(self):
        record = rest_property(meta={"fave_property_images": []})
        site = FakeSite([record], [media_record(26178, "Laya-cover")])
        raw = site.connector().fetch_offer({"listing_id": 26161})
        assert raw["images"] == [f"{BASE}/wp-content/uploads/2025/04/Laya-cover-1170x785.jpg"]

    def test_media_failure_falls_back_to_html_gallery(self, monkeypatch):
        class Page:
            text = "<html/>"

            def raise_for_status(self):
                pass

        monkeypatch.setattr(avarten_connector.requests, "get", lambda *a, **k: Page())
        monkeypatch.setattr(
            avarten_connector, "parse_property_details", lambda **k: {"gallery": ["https://img/html-1.jpg"]}
        )
        site = _detail_site(media_error=connection_error())

        raw = site.connector().fetch_offer({"url": f"{BASE}/pl/property/laya-courtyard-at-dubai-studio-city/"})

        assert raw["images"] == ["https://img/html-1.jpg"]
        assert raw["images_source"] == "html_fallback"
        assert raw["offer"]["id"] == 26161  # business data still comes from REST

    def test_no_images_anywhere_gives_empty_gallery_that_still_validates(self, monkeypatch):
        monkeypatch.setattr(avarten_connector.requests, "get", lambda *a, **k: (_ for _ in ()).throw(connection_error()))
        site = _detail_site(media_error=connection_error())
        connector = site.connector()

        raw = connector.fetch_offer({"url": f"{BASE}/property/laya-courtyard-at-dubai-studio-city/"})
        canonical = connector.normalize_offer(raw)

        assert raw["images"] == [] and raw["images_source"] == "none"
        assert canonical["media"]["gallery"] == []
        assert validate_canonical_offer(canonical) == (True, [])

    def test_rest_failure_falls_back_to_html_page(self, monkeypatch):
        sentinel = {"kind": "offer_details", "offer": {"title": "html", "data_source": "html"}, "url": "u"}
        monkeypatch.setattr(AvartenConnector, "_fetch_offer_html", lambda self, identifier: sentinel)
        site = _detail_site(list_error=connection_error())

        # slug lookup goes through the list endpoint, which is down
        assert site.connector().fetch_offer({"url": f"{BASE}/property/laya-courtyard-at-dubai-studio-city/"}) is sentinel

    def test_url_rest_cannot_resolve_keeps_legacy_html_behaviour(self, monkeypatch):
        sentinel = {"kind": "offer_details", "offer": {}, "url": "https://example.com/x"}
        monkeypatch.setattr(AvartenConnector, "_fetch_offer_html", lambda self, identifier: sentinel)

        assert _detail_site().connector().fetch_offer({"url": "https://example.com/x"}) is sentinel
        assert _detail_site().connector().fetch_offer({}) is sentinel  # legacy: None-when-no-url lives in the html path

    def test_html_fallback_details_are_marked(self, monkeypatch):
        class Page:
            text = "<html/>"

            def raise_for_status(self):
                pass

        monkeypatch.setattr(avarten_connector.requests, "get", lambda *a, **k: Page())
        monkeypatch.setattr(avarten_connector, "parse_property_details", lambda **k: {"title": "T"})
        monkeypatch.setattr(avarten_connector.time, "sleep", lambda seconds: None)

        raw = AvartenConnector()._fetch_offer_html({"url": "https://example.com/x"})
        assert raw["offer"] == {"title": "T", "data_source": "html"}
        assert AvartenConnector()._fetch_offer_html({}) is None
