"""Presentation helpers shared by every template.""" from __future__ import annotations from pathlib import Path from catalog import Product, Variant import re MEDIA_ROOT = Path(__file__).resolve().parents[1] / "static" / "assets" / "media" VIDEO_ROOT = Path(__file__).resolve().parents[1] / "static" / "assets" / "video" VIDEO_ID = re.compile(r"/v/columbia/([^/]+)/") def money(value: float | None) -> str: if value is None: return "" return f"${value:,.2f}" def media_url(image_id: str | None) -> str | None: """Map a source media id to the locally stored asset, if it was captured.""" if not image_id: return None if (MEDIA_ROOT / f"{image_id}.webp").exists(): return f"/static/assets/media/{image_id}.webp" return None def video_url(media_id: str | None) -> str | None: """PDP galleries mix in product videos; resolve those to local mp4s.""" if not media_id: return None match = VIDEO_ID.search(media_id) if not match: return None if (VIDEO_ROOT / f"{match.group(1)}.mp4").exists(): return f"/static/assets/video/{match.group(1)}.mp4" return None def slide(media_id: str | None) -> dict[str, str] | None: """Return the renderable gallery slide for a captured media id.""" video = video_url(media_id) if video: return {"kind": "video", "src": video} image = media_url(media_id) if image: return {"kind": "image", "src": image} return None def tile_images(product: Product, variant: Variant | None) -> tuple[str | None, str | None]: variant = variant or (product.variants[0] if product.variants else None) if variant is None: return (None, None) return (media_url(variant.primary_image), media_url(variant.hover_image)) def price_block(product: Product) -> dict[str, object]: """Reproduce the source's current/original price pairing.""" current = product.sale_price if product.sale_price is not None else product.min_price original = product.max_price spread = ( product.max_price is not None and product.min_price is not None and product.max_price != product.min_price ) return { "current": money(current), "original": money(original) if product.is_sale else "", "range_high": money(product.max_price) if spread else "", "is_sale": product.is_sale, }