from __future__ import annotations import json from pathlib import Path from typing import Any, Mapping from urllib.parse import urlparse HOME_COMMERCE_FIXTURE = "home-commerce-complete-2026-07-25.json" HOME_COMMERCE_EVIDENCE_CLASSES = frozenset( { "direct-home-commerce", "regional-converted-home-commerce", "local-simulation-home-commerce", } ) class HomeCommerceError(ValueError): pass def load_home_commerce_offers( fixture_root: Path, home_catalog: Mapping[str, Mapping[str, Any]], ) -> tuple[dict[str, Any], ...]: """Load dated default offers without widening their evidence boundary.""" fixture_root = fixture_root.resolve() candidate = (fixture_root / HOME_COMMERCE_FIXTURE).resolve() if fixture_root not in candidate.parents or not candidate.is_file(): raise HomeCommerceError("home commerce fixture does not exist") try: payload = json.loads(candidate.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as exc: raise HomeCommerceError("home commerce fixture is invalid") from exc if payload.get("schema") != "amazon-clone.home-commerce-offers.v2": raise HomeCommerceError("unsupported home commerce fixture schema") offers = payload.get("offers") if not isinstance(offers, list) or not offers: raise HomeCommerceError("home commerce offers must be a non-empty array") if payload.get("sourceHomepageProducts") != 157: raise HomeCommerceError("home commerce fixture has an invalid source denominator") if payload.get("sourceOfferCount") != len(offers): raise HomeCommerceError("home commerce fixture offer count is inconsistent") if len(offers) != 157: raise HomeCommerceError("home commerce fixture must cover all homepage products") expected_counts = payload.get("evidenceClassCounts") if not isinstance(expected_counts, dict): raise HomeCommerceError("home commerce evidence counts are missing") normalized: list[dict[str, Any]] = [] seen: set[str] = set() for offer in offers: if not isinstance(offer, dict): raise HomeCommerceError("home commerce offers must be objects") asin = offer.get("asin") home_product = home_catalog.get(str(asin)) title = offer.get("title") price_minor = offer.get("price_minor") currency = offer.get("currency") source_url = offer.get("source_url") evidence_class = offer.get("evidence_class") if ( not isinstance(asin, str) or len(asin) != 10 or asin in seen or home_product is None ): raise HomeCommerceError("home commerce offer has an invalid ASIN") if not isinstance(title, str) or not title.strip(): raise HomeCommerceError(f"home commerce offer {asin} has no title") if ( isinstance(price_minor, bool) or not isinstance(price_minor, int) or price_minor <= 0 or currency != "USD" ): raise HomeCommerceError(f"home commerce offer {asin} has an invalid price") if evidence_class not in HOME_COMMERCE_EVIDENCE_CLASSES: raise HomeCommerceError( f"home commerce offer {asin} has an invalid evidence class" ) if not isinstance(source_url, str): raise HomeCommerceError(f"home commerce offer {asin} has an invalid source URL") parsed_source = urlparse(source_url) if ( parsed_source.scheme != "https" or parsed_source.hostname not in {"www.amazon.com", "www.amazon.sg"} or asin not in parsed_source.path ): raise HomeCommerceError(f"home commerce offer {asin} has an invalid source URL") if evidence_class == "regional-converted-home-commerce": source_price_minor = offer.get("source_price_minor") if ( parsed_source.hostname != "www.amazon.sg" or isinstance(source_price_minor, bool) or not isinstance(source_price_minor, int) or source_price_minor <= 0 or offer.get("source_currency") != "SGD" or not offer.get("conversion_rate_source") ): raise HomeCommerceError( f"regional home commerce offer {asin} is incomplete" ) if evidence_class == "local-simulation-home-commerce" and not offer.get( "simulation_disclosure" ): raise HomeCommerceError( f"local simulation home commerce offer {asin} is undisclosed" ) if not ( offer.get("local_add_to_cart_enabled") and offer.get("local_buy_now_enabled") ): raise HomeCommerceError( f"home commerce offer {asin} has incomplete local purchase controls" ) image_path = home_product.get("image_path") if not isinstance(image_path, str) or not image_path.startswith("/static/"): raise HomeCommerceError(f"home commerce offer {asin} has no local image") seen.add(asin) normalized.append( { "asin": asin, "slug": "home-offer", "canonical_path": f"/dp/{asin}", "title": title, "brand": "", "capacity": "", "color": "", "price_minor": price_minor, "list_price_minor": None, "currency": "USD", "rating": "", "reviews": 0, "image_path": image_path, "badge": "", "evidence_class": evidence_class, "offer_observation_source": str( offer.get("price_observation_source") or "" ), "purchase_state": str(offer.get("purchase_state") or ""), "source_capture": str(offer.get("source_capture") or ""), "source_url": source_url, "offer_disclosure": ( "Direct USD offer captured from the product's Amazon purchase surface." if evidence_class == "direct-home-commerce" else "USD quote converted from a dated Amazon regional offer." if evidence_class == "regional-converted-home-commerce" else "Offline-only local simulation quote." ), } ) observed_counts = { evidence_class: sum( offer["evidence_class"] == evidence_class for offer in normalized ) for evidence_class in HOME_COMMERCE_EVIDENCE_CLASSES } if observed_counts != expected_counts: raise HomeCommerceError("home commerce evidence counts are inconsistent") return tuple(normalized)