diff --git "a/tasks/amazon/solution/site/implementation/clone/render.py" "b/tasks/amazon/solution/site/implementation/clone/render.py"
new file mode 100644--- /dev/null
+++ "b/tasks/amazon/solution/site/implementation/clone/render.py"
@@ -0,0 +1,4980 @@
+from __future__ import annotations
+
+import contextvars
+import json
+from html import escape
+from pathlib import Path
+from typing import Any, Iterable, Mapping
+from urllib.parse import quote_plus, urlencode
+
+from home_category_catalog import home_category_products, load_home_category_groups
+from payment_methods import DEFAULT_PAYMENT_METHOD, public_payment_methods
+from stripe_gateway import PAYMENT_MODE_STRIPE_TEST
+from product_options import T7_SOURCE_OPTIONS, option_groups_from_detail
+from review_catalog import render_reviews_section
+from search_catalog import (
+ DEFAULT_SEARCH_DEPARTMENT,
+ SOURCE_DEPARTMENTS,
+ SOURCE_DEPARTMENT_BY_SLUG,
+ SearchPage,
+ SearchRequest,
+ normalize_search_query,
+ search_href,
+ source_department_for_query,
+ source_department_for_rail,
+)
+from store import (
+ BEST_SELLERS_PATH,
+ DEFAULT_DELIVERY_COUNTRY,
+ DESKTOP_TERMINAL_PATH,
+ MOBILE_TERMINAL_PATH,
+ PDP_PATH,
+ SUPPORTED_DELIVERY_COUNTRIES,
+ TARGET_ASIN,
+)
+
+
+# The storefront delivery location is per-browser-session state, but it is read
+# by header/PDP/notice renderers that sit ~200 call sites below `layout()`.
+# Threading it through every signature would be churn, so the request handler
+# publishes it once per request and the renderers read it here. Each request is
+# served on its own thread, and a thread starts from an empty context, so the
+# default applies to anything rendered outside a request (tests, tooling).
+_DELIVERY_COUNTRY: contextvars.ContextVar[tuple[str, str]] = contextvars.ContextVar(
+ "amazon_delivery_country", default=DEFAULT_DELIVERY_COUNTRY
+)
+_DELIVERY_TOKEN: contextvars.ContextVar[str] = contextvars.ContextVar(
+ "amazon_delivery_token", default=""
+)
+
+
+def set_delivery_context(country: tuple[str, str], token: str = "") -> None:
+ """Publish the delivery location for everything rendered in this request."""
+
+ _DELIVERY_COUNTRY.set(country)
+ _DELIVERY_TOKEN.set(token)
+
+
+def current_delivery_country() -> tuple[str, str]:
+ return _DELIVERY_COUNTRY.get()
+
+
+def current_delivery_label() -> str:
+ return _DELIVERY_COUNTRY.get()[1]
+
+
+def delivery_country_options(selected_code: str | None = None) -> str:
+ """Render the storefront delivery option set.
+
+ The header picker, its no-JavaScript landing page and the JSON endpoint all
+ read this one function so the three surfaces cannot drift apart.
+ """
+
+ code = (selected_code or current_delivery_country()[0]).upper()
+ return "".join(
+ f''
+ for country, label in SUPPORTED_DELIVERY_COUNTRIES
+ )
+
+
+def delivery_location_picker(error: bool = False) -> str:
+ """Header delivery-location dialog.
+
+ Progressive enhancement only: the trigger in `header()` is a real link to
+ DELIVERY_PREFERENCE_HREF, and this dialog posts a real form, so both the
+ no-JavaScript and the scripted path go through the same server route.
+ """
+
+ status = (
+ "The address has not been updated. Choose a country/region and try again."
+ if error
+ else ""
+ )
+ return f"""
+
+
+
+
+
Choose your location
+
+
+
+
{escape(status)}
+
+
+ """
+
+
+SITE_NAME = "Amazon.com"
+CUSTOMER_SERVICE_HREF = "/gp/help/customer/display.html?nodeId=508510"
+SHIPPING_POLICIES_HREF = "/gp/help/customer/display.html?nodeId=468520"
+RETURNS_REPLACEMENTS_HREF = "/gp/help/customer/display.html?nodeId=201819200"
+CONDITIONS_OF_USE_HREF = "/gp/help/customer/display.html?nodeId=508088"
+PRIVACY_NOTICE_HREF = "/gp/help/customer/display.html?nodeId=468496"
+GIFT_CARDS_HREF = "/gift-cards/b/?ie=UTF8&node=2238192011"
+DELIVERY_PREFERENCE_HREF = "/gp/delivery/ajax/address-change.html"
+DELIVERY_SELECTIONS_HREF = "/gp/delivery/ajax/address-selections"
+SITE_DIRECTORY_HREF = "/gp/site-directory"
+T7_TITLE = (
+ "Samsung T7 Portable SSD, 1TB External Solid State Drive, Speeds Up to "
+ "1,050MB/s, USB 3.2 Gen 2, Reliable Storage for Gaming, Students, "
+ "Professionals, MU-PC1T0T/AM, Gray"
+)
+
+
+def money(minor: int | None, currency: str = "USD") -> str:
+ if minor is None:
+ return ""
+ symbol = "$" if currency == "USD" else f"{currency} "
+ return f"{symbol}{minor / 100:,.2f}"
+
+
+def _quote_data_attributes(product: dict[str, Any]) -> str:
+ """Embed server-resolved transaction facts without executable markup.
+
+ JSON lives in quoted data attributes so the HTML parser decodes entities
+ before the frontend reads them. The browser must never derive a quote
+ from the visible price or from option-button copy.
+ """
+
+ quote_matrix = product.get("option_quote_matrix")
+ if not isinstance(quote_matrix, (list, tuple)):
+ quote_matrix = []
+ public_quote_matrix: list[dict[str, Any]] = []
+ for quote in quote_matrix:
+ if not isinstance(quote, Mapping):
+ continue
+ transaction_target = quote.get("transaction_target")
+ selection_key = (
+ transaction_target.get("selection_key")
+ if isinstance(transaction_target, Mapping)
+ else None
+ )
+ public_quote = {
+ key: quote[key]
+ for key in (
+ "availability",
+ "price_minor",
+ "currency",
+ "image_path",
+ "display_availability",
+ "selected_options",
+ )
+ if key in quote
+ }
+ if isinstance(selection_key, str) and selection_key:
+ public_quote["transaction_target"] = {"selection_key": selection_key}
+ public_quote_matrix.append(public_quote)
+ default_selection = product.get("default_selected_options")
+ if not isinstance(default_selection, dict):
+ default_selection = {}
+ unavailable_copy = str(
+ product.get("option_unavailable_copy")
+ or "This selection is currently unavailable"
+ )
+ quote_json = escape(
+ json.dumps(public_quote_matrix, ensure_ascii=True, sort_keys=True, separators=(",", ":")),
+ quote=True,
+ )
+ default_json = escape(
+ json.dumps(default_selection, ensure_ascii=True, sort_keys=True, separators=(",", ":")),
+ quote=True,
+ )
+ return (
+ f'data-product-quote-matrix="{quote_json}" '
+ f'data-default-selected-options="{default_json}" '
+ f'data-option-unavailable-copy="{escape(unavailable_copy, quote=True)}"'
+ )
+
+
+def product_href(product: dict[str, Any]) -> str:
+ canonical_path = product.get("canonical_path")
+ if isinstance(canonical_path, str) and canonical_path.startswith("/") and not canonical_path.startswith("//"):
+ return canonical_path
+ slug = product.get("slug")
+ if isinstance(slug, str) and slug:
+ return f"/{slug}/dp/{product['asin']}"
+ return f"/dp/{product['asin']}"
+
+
+def product_review_href(product: dict[str, Any]) -> str:
+ """Link every server-known product to its live local review surface."""
+
+ asin = str(product.get("asin", "")).upper()
+ return f"/product-reviews/{escape(asin, quote=True)}"
+
+
+def amazon_logo() -> str:
+ return (
+ 'amazon'
+ ''
+ )
+
+
+def source_department_href(department: dict[str, Any]) -> str:
+ return f'/s?i={quote_plus(str(department["slug"]))}'
+
+
+def source_department_navigation(active_slug: str = "") -> str:
+ """Render only real, rail-backed department destinations."""
+
+ links = []
+ for department in SOURCE_DEPARTMENTS:
+ slug = str(department["slug"])
+ current = ' aria-current="page"' if slug == active_slug else ""
+ links.append(
+ f'{escape(str(department["title"]))}'
+ )
+ return "".join(links)
+
+
+def shopping_browse_href(label: str, page_category: str = "") -> str:
+ """Return a local department or search destination for PDP browse links."""
+
+ query = " ".join(str(label).split()).strip()
+ normalized = query.casefold().replace("&", "and")
+ for department in SOURCE_DEPARTMENTS:
+ aliases = {
+ str(department["slug"]).casefold().replace("-", " "),
+ str(department["title"]).casefold().replace("&", "and"),
+ *(
+ str(alias).casefold().replace("&", "and")
+ for alias in department.get("aliases", ())
+ ),
+ }
+ if normalized in aliases:
+ return source_department_href(department)
+
+ parameters: dict[str, str] = {"k": query or "products"}
+ category = " ".join(str(page_category).split()).strip().casefold().replace("&", "and")
+ for department in SOURCE_DEPARTMENTS:
+ aliases = {
+ str(department["title"]).casefold().replace("&", "and"),
+ *(str(alias).casefold().replace("&", "and") for alias in department.get("aliases", ())),
+ }
+ if category in aliases:
+ parameters["i"] = str(department["slug"])
+ break
+ return "/s?" + urlencode(parameters)
+
+
+def pdp_full_view_controls(image_path: str, title: str) -> tuple[str, str]:
+ """Build the keyboard-operable full-image trigger and its local dialog."""
+
+ safe_image = escape(str(image_path), quote=True)
+ safe_alt = escape(str(title), quote=True)
+ trigger = (
+ ''
+ )
+ dialog = f"""
+
+ """
+ return trigger, dialog
+
+
+def secure_transaction_dialog() -> str:
+ """Explain the modeled checkout boundary without implying a live processor."""
+
+ return """
+
+ """
+
+
+def all_menu(
+ account_name: str | None = None,
+ *,
+ initially_open: bool = False,
+) -> str:
+ """Render Amazon's persistent All navigation as a usable modal drawer.
+
+ The ordinary links remain real server destinations. JavaScript only changes
+ how the menu is revealed, so ``/gp/site-directory`` remains the no-script
+ fallback for both All triggers.
+ """
+
+ short_name = account_name.strip().split()[0] if account_name and account_name.strip() else ""
+ account_href = (
+ "/gp/css/homepage.html"
+ if short_name
+ else "/ap/signin?openid.return_to=%2Fgp%2Fcss%2Fhomepage.html"
+ )
+ greeting = f"Hello, {escape(short_name)}" if short_name else "Hello, sign in"
+ auth_action = (
+ ''
+ if short_name
+ else 'Sign In'
+ )
+ root_class = "nav-drawer-layer is-open" if initially_open else "nav-drawer-layer"
+ hidden = "false" if initially_open else "true"
+ return f"""
+
+
+ {product_section}
+
+ """
+ return layout(
+ f"Amazon.com : {heading}",
+ body,
+ cart_count,
+ search_value=heading,
+ body_class="home-collection-page",
+ account_name=account_name,
+ )
+
+
+def _evidence_placement_label(product: dict[str, Any]) -> str:
+ labels: list[str] = []
+ placements = product.get("placements")
+ if isinstance(placements, list):
+ for placement in placements:
+ if not isinstance(placement, dict):
+ continue
+ label = placement.get("railTitle")
+ if isinstance(label, str) and label and label not in labels:
+ labels.append(label)
+ return " · ".join(labels[:2])
+
+
+def compare_add_form(product: dict[str, Any], *, compact: bool = False) -> str:
+ asin = str(product.get("asin") or "")
+ if not asin or product.get("compare_eligible") is not True:
+ return ""
+ class_name = "compare-add-form compact" if compact else "compare-add-form"
+ label = "Compare" if compact else "Add to compare"
+ safe_asin = escape(asin, quote=True)
+ selected_options = product.get("default_selected_options")
+ option_fields = "".join(
+ f''
+ for option_label, option_value in (
+ selected_options.items()
+ if isinstance(selected_options, dict)
+ else ()
+ )
+ )
+ return f''
+
+
+def search_product_card(
+ product: dict[str, Any], *, result_layout: str = "list"
+) -> str:
+ """Render the common Amazon search-result card for every product source."""
+
+ asin = str(product["asin"])
+ title = str(product["title"])
+ href = product_href(product)
+ rating = str(product.get("rating") or "")
+ reviews = product.get("reviews")
+ reviews_display = str(product.get("reviews_display") or "")
+ if not reviews_display and isinstance(reviews, int) and reviews > 0:
+ reviews_display = f"{reviews:,}"
+ rating_markup = (
+ f''
+ f'{escape(rating)} ★★★★★ '
+ f'({escape(reviews_display)})'
+ if rating and reviews_display
+ else f'Customer reviews'
+ )
+ sponsored = (
+ 'Sponsored'
+ if product.get("sponsored")
+ else ""
+ )
+ product_format = product.get("format")
+ format_markup = (
+ f'
{escape(str(product_format))}
'
+ if isinstance(product_format, str) and product_format
+ else ""
+ )
+ badge = str(product.get("badge") or "")
+ badge_markup = (
+ f'{escape(badge)}' if badge else ""
+ )
+ placement = _evidence_placement_label(product)
+ placement_markup = (
+ f'
Featured in {escape(placement)}
'
+ if placement
+ else ""
+ )
+ availability = str(product.get("availability") or "")
+ availability_markup = (
+ f'
{escape(availability)}
' if availability else ""
+ )
+ if result_layout == "grid":
+ # Grid cards reserve the same two information rows for every product.
+ # Source titles, availability and placement copy vary considerably; the
+ # stable slots keep the buying controls aligned without truncating the
+ # product identity above them.
+ grid_availability_markup = (
+ f'
+
+ """
+ return layout(
+ f"Amazon.com: {content['label']}",
+ body,
+ cart_count,
+ search_value="",
+ body_class=f"department-landing-page department-{slug}-page",
+ account_name=account_name,
+ active_department=slug,
+ )
+
+
+def search_results_page(
+ page: SearchPage,
+ cart_count: int,
+ account_name: str | None = None,
+ *,
+ available_brands: Iterable[str] = (),
+ available_facets: Mapping[str, Any] | None = None,
+ result_layout: str = "list",
+ department_rail_products: Iterable[dict[str, Any]] = (),
+) -> str:
+ """Render one server-refined Amazon search page."""
+
+ request = page.request
+ if _is_default_department_landing(request):
+ return department_landing_page(
+ page,
+ cart_count,
+ account_name,
+ rail_products=department_rail_products,
+ )
+ safe_query = escape(request.query)
+ department = SOURCE_DEPARTMENT_BY_SLUG.get(request.department)
+ department_slug = str(department["slug"]) if department is not None else ""
+ start = (page.page - 1) * page.page_size + 1 if page.total else 0
+ end = start + len(page.items) - 1 if page.items else 0
+ if department is not None and not request.query:
+ context = f'in {escape(str(department["title"]))}'
+ else:
+ context = f'for "{safe_query}"'
+ summary = f"{start}-{end} of {page.total} results {context}" if page.total else f"0 results {context}"
+
+ if result_layout not in {"list", "grid"}:
+ raise ValueError(f"unsupported search result layout: {result_layout}")
+ result_markup = [
+ search_product_card(dict(hit.product), result_layout=result_layout)
+ for hit in page.items
+ ]
+
+ if result_markup:
+ heading = escape(str(department["title"])) if department is not None else "Results"
+ results = f"""
+
+
{heading}
+
Browse products and buying options.
+ {''.join(result_markup)}
+ {_search_pagination(page)}
+
+ """
+ else:
+ has_refinements = bool(
+ request.brands
+ or request.min_price_minor is not None
+ or request.max_price_minor is not None
+ or request.rating is not None
+ or request.availability is not None
+ )
+ if department is not None and not request.query:
+ empty_heading = f'No results in {escape(str(department["title"]))}'
+ else:
+ empty_heading = f'No results for “{safe_query}”'
+ if has_refinements:
+ action = (
+ f'Clear filters'
+ )
+ elif request.department != DEFAULT_SEARCH_DEPARTMENT and request.query:
+ action = (
+ f'Search all departments'
+ )
+ else:
+ action = 'Return to Amazon home'
+ results = f"""
+
+
{empty_heading}
+
Try removing a filter, checking your spelling, or using fewer words.
{_search_refinements(request, available_brands, available_facets or {})}{results}
+
+ """
+ return layout(
+ f"Amazon.com : {request.query or (department or {}).get('title', 'Search')}",
+ body,
+ cart_count,
+ search_value=request.query,
+ body_class="search-page",
+ account_name=account_name,
+ active_department=request.department,
+ )
+
+
+def site_directory_page(
+ sections: list[dict[str, Any]],
+ cart_count: int,
+ account_name: str | None = None,
+) -> str:
+ """Render the All trigger's no-script destination as the same open drawer.
+
+ Amazon's All control is a navigation drawer rather than a product-results
+ page. Keeping the server fallback in that state prevents a missed script
+ interception, refresh, or copied URL from changing page families.
+ """
+
+ del sections
+ body = """
+
+
All Amazon departments
+
+
+
+ """
+ return layout(
+ "Amazon.com - All departments",
+ body,
+ cart_count,
+ body_class="site-directory-page",
+ account_name=account_name,
+ all_menu_open=True,
+ )
+
+
+def generic_add_to_cart_form(
+ product: dict[str, Any],
+ *,
+ quantity_max: int = 30,
+ quantity_id: str | None = None,
+ button_class: str = "",
+ selected_options: dict[str, str] | None = None,
+) -> str:
+ """Render the ordinary commerce form used outside the strict T7 journey."""
+
+ asin = escape(str(product["asin"]), quote=True)
+ field_id = quantity_id or f"quantity-{asin.lower()}"
+ limit = max(1, min(int(quantity_max), 30))
+ options = "".join(
+ f''
+ for quantity in range(1, limit + 1)
+ )
+ extra_button_class = f" {button_class}" if button_class else ""
+ option_fields = "".join(
+ f''
+ for label, value in (selected_options or {}).items()
+ )
+ return f"""
+
+ """
+
+
+def wishlist_add_form(
+ product: dict[str, Any],
+ selected_options: dict[str, str] | None = None,
+ *,
+ css_class: str = "add-to-list-form",
+) -> str:
+ """Render the PDP entry point while keeping Wishlist views decoupled.
+
+ The lazy import avoids a module cycle: ``wishlist_views`` reuses the global
+ Amazon layout, money, and option-markup helpers from this module.
+ """
+
+ from wishlist_views import wishlist_entry_form
+
+ defaults = product.get("default_selected_options")
+ selection = (
+ {str(label): str(value) for label, value in defaults.items()}
+ if selected_options is None and isinstance(defaults, dict)
+ else dict(selected_options or {})
+ )
+ return wishlist_entry_form(
+ product,
+ selection,
+ css_class=css_class,
+ )
+
+
+def _deals_filter_url(
+ filters: dict[str, Any], **overrides: Any
+) -> str:
+ state: dict[str, Any] = {
+ "theme": filters.get("theme") or "",
+ "department": filters.get("department") or "",
+ "brand": list(filters.get("brands") or ()),
+ "rating": filters.get("rating") or "",
+ "minPrice": filters.get("min_price_text") or "",
+ "maxPrice": filters.get("max_price_text") or "",
+ "minDiscount": filters.get("min_discount_text") or "",
+ "maxDiscount": filters.get("max_discount_text") or "",
+ "dealType": filters.get("deal_type") or "",
+ }
+ state.update(overrides)
+ pairs: list[tuple[str, str]] = []
+ for key in (
+ "theme",
+ "department",
+ "rating",
+ "minPrice",
+ "maxPrice",
+ "minDiscount",
+ "maxDiscount",
+ "dealType",
+ ):
+ value = state.get(key)
+ if isinstance(value, str) and value:
+ pairs.append((key, value))
+ raw_brands = state.get("brand")
+ if isinstance(raw_brands, (list, tuple)):
+ pairs.extend(
+ ("brand", str(brand)) for brand in raw_brands if str(brand)
+ )
+ query = urlencode(pairs, doseq=True)
+ return "/gp/goldbox/" + (f"?{query}" if query else "")
+
+
+def _deals_quick_add_form(product: dict[str, Any]) -> str:
+ asin = escape(str(product["asin"]), quote=True)
+ label = escape(f"Add {product['title']} to cart", quote=True)
+ return f"""
+
+ """
+
+
+def deals_product_card(
+ product: dict[str, Any], filters: dict[str, Any] | None = None
+) -> str:
+ """Render one product in the Deals page family."""
+
+ active_filters = filters or {}
+ asin = escape(str(product["asin"]), quote=True)
+ title = escape(str(product["title"]))
+ href = escape(product_href(product), quote=True)
+ review_href = escape(product_review_href(product), quote=True)
+ image_path = escape(str(product["image_path"]), quote=True)
+ price = money(int(product["price_minor"]), str(product["currency"]))
+ brand = str(product.get("brand") or "").strip()
+ brand_markup = (
+ f'{escape(brand)}'
+ if brand
+ else ""
+ )
+ rating = str(product.get("rating") or "").strip()
+ reviews = product.get("reviews")
+ rating_markup = ""
+ if rating and isinstance(reviews, int) and reviews > 0:
+ rating_markup = (
+ f''
+ f'{escape(rating)}★★★★★{reviews:,}'
+ )
+ discount = product.get("discount_percent")
+ list_price = product.get("list_price_minor")
+ discount_markup = ""
+ reference_markup = ""
+ if (
+ isinstance(list_price, int)
+ and not isinstance(list_price, bool)
+ and list_price > int(product["price_minor"])
+ ):
+ reference_label = escape(
+ str(product.get("reference_price_label") or "List price")
+ )
+ reference_markup = (
+ f'
' if capacity_buttons else "")
+ if primary_option_value
+ else ""
+ )
+ choice_groups_markup = ""
+ raw_choice_groups = detail.get("choice_groups", [])
+ option_spec = product.get("option_spec")
+ if not raw_choice_groups and isinstance(option_spec, (list, tuple)):
+ raw_choice_groups = [
+ {
+ "label": str(group["label"]),
+ "value": str(group["default"]),
+ "options": [str(value) for value in group["options"]],
+ "mode": "buttons",
+ }
+ for group in option_spec
+ if isinstance(group, Mapping)
+ and group.get("label")
+ and group.get("default")
+ and isinstance(group.get("options"), (list, tuple))
+ ]
+ for group in raw_choice_groups:
+ if not isinstance(group, dict):
+ continue
+ group_label = str(group.get("label", ""))
+ group_value = str(group.get("value", ""))
+ group_options = group.get("options", [])
+ if not group_label or not group_value or not isinstance(group_options, list):
+ continue
+ if group.get("mode") == "select":
+ select_options = "".join(
+ f''
+ for option in group_options
+ if isinstance(option, str) and option
+ )
+ if select_options:
+ choice_groups_markup += (
+ f'
'
+ )
+ else:
+ # A direct PDP may establish that a product currently has no reviews
+ # without establishing a rating. Do not manufacture stars or an
+ # aggregate from the local-review system in that case.
+ source_review_copy = detail.get("source_review_copy")
+ rating_markup = (
+ f'
The price and availability of items at Amazon.com are subject to change. The Cart is a temporary place to store a list of your items and reflects each item's most recent price. Learn more Do you have a gift card or promotional code? We'll ask you to enter your claim code when it's time to pay.
Sign inContinue shopping
+ """
+ return layout(f"Amazon.com - {title}", body, cart_count, body_class="boundary-page", account_name=account_name)
+
+
+def customer_service_page(
+ cart_count: int,
+ account_name: str | None = None,
+ *,
+ help_query: str = "",
+) -> str:
+ """Render a navigable support hub instead of a generic boundary card."""
+
+ account_href = (
+ "/gp/css/homepage.html"
+ if account_name
+ else "/ap/signin?openid.return_to=%2Fgp%2Fcss%2Fhomepage.html"
+ )
+ topics = (
+ (
+ "📦",
+ "Your Orders",
+ "Track a package, inspect a placed order, or review its delivery status.",
+ "/gp/css/order-history",
+ "order package tracking purchase",
+ ),
+ (
+ "↩",
+ "Returns & refunds",
+ "Find return and replacement guidance, then open the relevant order.",
+ RETURNS_REPLACEMENTS_HREF,
+ "return refund replacement exchange",
+ ),
+ (
+ "🚚",
+ "Shipping & delivery",
+ "Compare delivery choices and learn where shipping charges are shown.",
+ SHIPPING_POLICIES_HREF,
+ "shipping delivery rate charge address singapore",
+ ),
+ (
+ "👤",
+ "Manage your account",
+ "Sign in, review account access, and update the checkout address you use.",
+ account_href,
+ "account sign in login password address",
+ ),
+ (
+ "🎁",
+ "Gift Cards & gifts",
+ "Open Gift Cards or browse gift ideas from the marketplace departments.",
+ GIFT_CARDS_HREF,
+ "gift card balance redeem present",
+ ),
+ (
+ "🛒",
+ "Cart & checkout",
+ "Review your cart before selecting an address, delivery, and payment method.",
+ "/gp/cart/view.html",
+ "cart checkout payment buy",
+ ),
+ )
+
+ def topic_card(topic: tuple[str, str, str, str, str], css_class: str) -> str:
+ icon, title, copy, href, _ = topic
+ return f"""
+
+ {icon}
+ {escape(title)}{escape(copy)}
+
+ """
+
+ normalized_query = " ".join(help_query.split())[:160]
+ search_results = ""
+ if normalized_query:
+ terms = tuple(term.lower() for term in normalized_query.split() if term)
+ matches = tuple(
+ topic
+ for topic in topics
+ if any(
+ term in f"{topic[1]} {topic[2]} {topic[4]}".lower()
+ for term in terms
+ )
+ )
+ if matches:
+ result_cards = "".join(topic_card(topic, "help-search-result") for topic in matches)
+ search_results = f"""
+
+
Help results for “{escape(normalized_query)}”
+
{result_cards}
+
+ """
+ else:
+ search_results = f"""
+
+
No exact help result for “{escape(normalized_query)}”
+
Try a shorter search, or choose one of the help topics below.
+
+ """
+
+ topic_cards = "".join(topic_card(topic, "help-topic-card") for topic in topics)
+ greeting = f"Hello, {escape(account_name.split()[0])}." if account_name else "Hello."
+ body = f"""
+
+
+
{greeting}
What can we help you with?
+
+
+ {search_results}
+
+
Some things you can do here
+
{topic_cards}
+
+
+
Need help with an order?
Open Your Orders for order-specific delivery and payment details.
+ Go to Your Orders
+
+
+ """
+ return layout(
+ "Amazon Customer Service",
+ body,
+ cart_count,
+ body_class="help-page customer-service-page",
+ account_name=account_name,
+ )
+
+
+def shipping_policies_page(
+ cart_count: int,
+ account_name: str | None = None,
+) -> str:
+ """Describe the delivery choices that the checkout backend actually supports."""
+
+ body = f"""
+
+
+
+
+
+
Shipping Rates & Policies
+
Shipping availability and charges are shown before an order is placed. Product pages show offer-specific delivery information when it is available.
+
Delivery choices at checkout
Standard deliveryFREE
Included in the supported checkout flow.
Expedited delivery$12.99
A faster delivery choice available during checkout.
+
Delivering to {escape(current_delivery_label())}
The storefront currently shows offers for delivery to {escape(current_delivery_label())}. Change the delivery location from the header, then select the full shipping address while checking out.
+
+ """
+ return layout(
+ "Amazon.com Help: Shipping Rates & Policies",
+ body,
+ cart_count,
+ body_class="help-page help-article-page shipping-policies-page",
+ account_name=account_name,
+ )
+
+
+def conditions_of_use_page(
+ cart_count: int,
+ account_name: str | None = None,
+) -> str:
+ """State the terms that actually govern this local storefront.
+
+ The source article describes a real marketplace. Restating it here would
+ claim obligations this clone cannot carry, so this page describes the local
+ storefront truthfully instead and says plainly that it is not the real one.
+ """
+
+ body = f"""
+
+
+
+
+
+
Conditions of Use
+
These conditions govern this local storefront only.
+
What this storefront is
This is a self-contained storefront that serves every page, image, and script from its own server. It is not operated by Amazon.com, Inc., and using it creates no relationship with that company.
+
Orders and payments
Orders placed here are recorded in this storefront's own database. No goods are dispatched, no money moves, and no payment instrument is charged. Card details entered during checkout are sandbox values handled by a local test gateway.
+
Your account
An account created here exists only in this storefront and is not shared with any other site. You may stop using it at any time; see Privacy Notice for what is stored.
+
Catalog content
Product titles, images, prices, and reviews are captured reference material shown to reproduce a shopping interface. They are not offers, and prices are not honoured.
+
+ """
+ return layout(
+ "Amazon.com Help: Conditions of Use",
+ body,
+ cart_count,
+ body_class="help-page help-article-page conditions-of-use-page",
+ account_name=account_name,
+ )
+
+
+def privacy_notice_page(
+ cart_count: int,
+ account_name: str | None = None,
+) -> str:
+ """Describe the data this storefront actually stores, and nothing else."""
+
+ body = f"""
+
+
+
+
+
+
Privacy Notice
+
Everything this storefront records stays on this storefront.
+
What is stored
A browser session identifier, and — if you create an account — an email address, a display name, a password hash, and the delivery location, cart, wish lists, orders, and reviews belonging to that account.
+
What is not stored
Passwords are never stored in readable form. Verification codes are stored only as hashes and expire. No payment instrument is stored: checkout uses sandbox values handled by a local test gateway.
+
Where it goes
Nowhere. This storefront makes no requests to other sites while you browse, sets no third-party cookies, and runs no analytics or advertising trackers. Verification email is written to a local outbox rather than delivered, unless this deployment has been explicitly configured otherwise.
+
Retention
Storefront data lives in a single local database and is rebuilt from a fixed seed whenever the storefront is reset, which discards accounts and their contents.
+
+ """
+ return layout(
+ "Amazon.com Help: Privacy Notice",
+ body,
+ cart_count,
+ body_class="help-page help-article-page privacy-notice-page",
+ account_name=account_name,
+ )
+
+
+def returns_replacements_page(
+ cart_count: int,
+ account_name: str | None = None,
+) -> str:
+ """Provide a useful path from return help to the shopper's real orders."""
+
+ order_action = "View Your Orders" if account_name else "Sign in to view orders"
+ body = f"""
+
+
+
+
+
+
Returns & Replacements
+
Start with Your Orders so the available action stays tied to the correct order and delivery state. This clone provides a local return-and-refund simulation; it does not create a real label, shipment, or money movement.
+
+
1
Open Your Orders
Sign in and locate the order that contains the item.
+
2
Wait for simulated delivery
The Return items action appears on eligible order details after the local shipment reaches Delivered.
+
3
Submit and track the return
Choose a reason, submit the request, and follow its Requested, Received, and Refunded states from the order.
+
+
Refund timing in this clone
A completed simulated refund record appears only after the local return advances through Received to Refunded. It is a state model only and never contacts a bank or card network.
'
+ status = escape(str(payment.get("status") or "Selected"))
+ label = escape(str(payment.get("method_label") or "Sandbox payment method"))
+ environment = (
+ "Stripe test environment"
+ if str(payment.get("method") or "") == "stripe-test"
+ else "Local simulation"
+ )
+ return f'
{label} {environment} · {status}
'
+
+
+def _simulation_notice(payload: dict[str, Any]) -> str:
+ notice = str(
+ payload.get("simulation_notice")
+ or "This is a local simulation. No real order, payment, shipment, or email is sent outside this workspace."
+ )
+ return f'
Items, quantities, options, or prices changed after the previous '
+ 'payment approval. Review the updated order total and select a sandbox '
+ 'payment method again.
Only this selection will be ordered. Items already in your cart will remain there.
'
+ if str(checkout.get("checkout_mode") or "CART") == "BUY_NOW"
+ else ""
+ )
+ stripe_mode = payment_mode == PAYMENT_MODE_STRIPE_TEST
+ payment = checkout.get("payment")
+ if stripe_mode and not isinstance(payment, dict):
+ payment = {
+ "method": "stripe-test",
+ "method_label": "Stripe test Checkout",
+ "status": (
+ "PENDING"
+ if checkout.get("status") == "PAYMENT_PENDING"
+ else "NOT_STARTED"
+ ),
+ }
+ place_action = (
+ "/gp/buy/stripe-checkout" if stripe_mode else "/gp/buy/place-order"
+ )
+ place_label = (
+ "Retry Stripe test Checkout"
+ if stripe_mode and checkout.get("status") == "PAYMENT_PENDING"
+ else "Pay with Stripe test Checkout"
+ if stripe_mode
+ else "Place your order"
+ )
+ place_copy = (
+ "You will continue to Stripe's hosted test page. The order is created "
+ "only after the server verifies a paid test Session."
+ if stripe_mode
+ else "By placing your order, you agree to this local simulation. No real charge is created."
+ )
+ body = f"""
+
+ {_checkout_steps("review")}
+
+
+ """
+ return _checkout_layout("Amazon Checkout - Review your order", body, cart_count, account_name, body_class="checkout-review-page")
+
+
+def stripe_payment_status_page(
+ checkout: dict[str, Any],
+ cart_count: int,
+ account_name: str | None,
+ *,
+ session_id: str,
+ state: str,
+ cancelled: bool,
+) -> str:
+ safe_session_id = escape(session_id, quote=True)
+ normalized_state = str(state or "unpaid").casefold()
+ if normalized_state == "unavailable":
+ heading = "Stripe status is temporarily unavailable"
+ detail = (
+ "No order was created from this page. Your frozen checkout remains "
+ "locked so you can refresh safely when the test service is available."
+ )
+ elif normalized_state == "mismatch":
+ heading = "We could not verify this Stripe Session"
+ detail = (
+ "The Session did not match the server-owned amount, currency, "
+ "account, or frozen cart. No order was created."
+ )
+ elif cancelled:
+ heading = "You returned from Stripe test Checkout"
+ detail = (
+ "The Session is not paid. Expire it below to unlock the checkout, "
+ "or return to Stripe and complete the test payment."
+ )
+ else:
+ heading = "Stripe test payment is pending"
+ detail = (
+ "No order exists yet. Refreshing is safe; only a verified paid "
+ "Session can create the order."
+ )
+ cancel_form = (
+ '"
+ if normalized_state not in {"mismatch"}
+ else ""
+ )
+ refresh_href = (
+ "/gp/buy/stripe-return?"
+ + urlencode({"session_id": session_id, **({"cancelled": "1"} if cancelled else {})})
+ )
+ body = f"""
+
+ {_checkout_steps("payment")}
+