"""Hosted-image URL helpers (SD-0002 ยง6.3.1, INV-12). Build the canonical hosted Image Src for a fetched image, and recognize one on re-import. DB-free and host-agnostic: recognition is a path-parse, so an export round-trips across localhost / PPE / the #23 rebrand. The diff resolves a parsed id against the storefront-scoped catalog snapshot. """ from __future__ import annotations import re from urllib.parse import urlsplit RENDITIONS = ("original", "thumb", "card", "detail") EXPORT_RENDITION = "detail" _PATH = re.compile(r"^/api/products/images/(\d+)/(original|thumb|card|detail)$") def image_url(base_url: str, image_id: int, rendition: str = EXPORT_RENDITION) -> str: """Absolute when base_url is set, else a root-relative path.""" path = f"/api/products/images/{image_id}/{rendition}" return f"{base_url.rstrip('/')}{path}" if base_url else path def parse_image_id(url: str) -> int | None: """The image id if url is one of our hosted-image URLs (any host), else None.""" if not url: return None m = _PATH.match(urlsplit(url).path) return int(m.group(1)) if m else None