File size: 25,503 Bytes
a6ab5dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
"""Columbia Sportswear offline clone.

Serves the source-observed route families over the locally captured catalog and
a deterministic SQLite-backed cart. No request ever leaves this process.
"""

from __future__ import annotations

import sys
from pathlib import Path

SITE_DIR = Path(__file__).resolve().parent / "site"
if str(SITE_DIR) not in sys.path:
    sys.path.insert(0, str(SITE_DIR))

from fastapi import FastAPI, Form, Request  # noqa: E402
from fastapi.responses import HTMLResponse, RedirectResponse  # noqa: E402
from fastapi.staticfiles import StaticFiles  # noqa: E402
from fastapi.templating import Jinja2Templates  # noqa: E402

import grid  # noqa: E402
import json  # noqa: E402
import render  # noqa: E402
from catalog import SORT_OPTIONS, get_catalog  # noqa: E402
from session import CartService, session_id_for  # noqa: E402

SITE_ID = "columbia"
DISPLAY_NAME = "Columbia Sportswear"
ROOT = Path(__file__).resolve().parent

app = FastAPI(title=DISPLAY_NAME)
app.mount("/static", StaticFiles(directory=ROOT / "static"), name="static")
templates = Jinja2Templates(directory=str(ROOT / "templates"))
templates.env.globals["min"] = min


class _LazyCatalog:
    """Build the captured catalog on first use rather than at import.

    The index is a pure function of ``data/*.json`` and every read path reaches
    it through attribute access, so deferring construction changes no response.
    It keeps the ~0.3 s parse out of the runtime's start-to-health window, which
    a lifecycle restart pays inside a fixed harness budget.
    """

    __slots__ = ("_catalog",)

    def __init__(self) -> None:
        self._catalog = None

    def _resolve(self):
        if self._catalog is None:
            self._catalog = get_catalog()
        return self._catalog

    def __getattr__(self, name: str):
        return getattr(self._resolve(), name)


catalog = _LazyCatalog()
carts = CartService(catalog)

# Source-observed category carousel on the Women grid, with the CMS artwork the
# source itself serves for each tile.
_VISNAV_PATH = ROOT / "data" / "plp-visnav.json"


def _visnav_tiles(rows):
    tiles = []
    for row in rows:
        asset = ROOT / "static" / "assets" / "cms" / f"{row['asset']}.webp"
        tiles.append(
            {
                "label": row["label"],
                "url": row["href"],
                "image": f"/static/assets/cms/{row['asset']}.webp" if asset.exists() else None,
            }
        )
    return tiles


VISNAV = (
    {
        category_id: _visnav_tiles(rows)
        for category_id, rows in json.loads(_VISNAV_PATH.read_text()).items()
    }
    if _VISNAV_PATH.exists()
    else {}
)


# One of the source's rotating Amplience campaign strings, captured from the
# promotional bar above the header.
PROMO_BAR = "Want Extra Savings On Sale Styles?"

# Stylesheet fingerprint so an edited sheet is never served from a stale cache.
ASSET_VERSION = str(
    max(
        int(path.stat().st_mtime)
        for path in (ROOT / "static" / "css").glob("*.css")
    )
)


def _shell(request: Request) -> dict[str, object]:
    session_id = session_id_for(request)
    return {
        "request": request,
        "cart_count": carts.item_count(session_id),
        "session_id": session_id,
        "promo_bar": PROMO_BAR,
        "asset_version": ASSET_VERSION,
        # The source pins the header differently by page family: category and
        # search grids use a sticky header under a 56px promotional bar, while
        # the home page and PDP use a fixed header offset 72px from the top.
        "header_mode": "fixed",
    }


def _with_cookie(response, request: Request, session_id: str):
    if request.cookies.get(CartService.COOKIE) != session_id:
        response.set_cookie(
            CartService.COOKIE, session_id, httponly=True, samesite="lax", path="/"
        )
    return response


@app.get("/healthz")
def healthz() -> dict[str, object]:
    return {"ok": True, "site_id": SITE_ID, "products": len(catalog.products)}


@app.get("/", response_class=HTMLResponse)
def home(request: Request):
    context = _shell(request)
    featured = catalog.products_in("newArrivals") or catalog.products_in("women")
    context.update(
        page_title="Outerwear, Sportswear & Footwear | Columbia Sportswear",
        heading="New & Trending",
        tiles=_tiles(featured[:12]),
        promo_tiles=_home_tiles(),
        hero=HERO,
        banner_before=BANNERS[0],
        banner_after=BANNERS[1],
        cards=[dict(card, image=_cms(card["asset"])) for card in CARDS],
    )
    response = templates.TemplateResponse(request, "home.html", context)
    return _with_cookie(response, request, context["session_id"])


def _tiles(products, enable_compare: bool = False, promo_label: str | None = None):
    rows = []
    for position, product in enumerate(products, start=1):
        variant = product.variants[0] if product.variants else None
        primary, hover = render.tile_images(product, variant)
        rows.append(
            {
                "product": product,
                "variant": variant,
                "primary": primary,
                "hover": hover,
                "price": render.price_block(product),
                "position": position,
                "enable_compare": enable_compare,
                "promo_label": promo_label if product.is_sale else None,
            }
        )
    return rows


def _cms(asset: str, ext: str = "webp") -> str | None:
    path = ROOT / "static" / "assets" / "cms" / f"{asset}.{ext}"
    return f"/static/assets/cms/{asset}.{ext}" if path.exists() else None


# Source-observed homepage content. Copy is transcribed from the captured page;
# artwork is the CMS asset the source itself serves for each slot.
HERO = {
    "image": _cms("Q3_2026_WeHeart_Toolkit_Hero"),
    "lockup": _cms("SummerSale_Icon_Final_v2", "svg"),
    "heading": "MEMBERS NOW GET EXTRA 30%",
    "subheading": (
        "We can\u2019t make summer longer, but can give you extra savings on gear "
        "up to 50% off. Terms apply."
    ),
    "cta": "Shop Sale",
    "url": "/c/sale/",
}

BANNERS = [
    {
        "image": _cms("9-08_COL_US_S26_HP_Back_to_School_MomentsBan_Youth_V6"),
        "heading": "BACK TO SCHOOL",
        "body": "Get ready for next semester with new styles that pass the vibe check.",
        "cta": "Shop Now",
        "url": "/c/back-to-school/",
    },
    {
        "image": _cms("8-10_ROC_MomensBan_DG"),
        "heading": "THE ROC\u2122 PANT",
        "body": (
            "Elevate your everyday comfort with our versatile and rugged "
            "bestselling ROC\u2122 pants."
        ),
        "cta": "Shop Men",
        "url": "/c/roc/",
    },
]

CARDS = [
    {"asset": "8-10_2686468_COL_US_HP_AmazeSweats_Subhero", "heading": "Sweat Sets",
     "body": "Soft, comfortable, effortless. Everything you could want in a sweat set.",
     "url": "/c/sweatsets/"},
    {"asset": "8-27_COL_US_HP_We_Heart_LukeCombs_Subhero",
     "heading": "Luke Combs Stage Edition Bahama\u2122 Shirt",
     "body": "Get a custom version of our iconic PFG shirt.",
     "url": "/p/mens-pfg-bahama-ii-luke-combs-short-sleeve-shirt-2194741.html"},
    {"asset": "8-10_2686468_COL_US_HP_FallNA_DG_Subhero", "heading": "New Arrivals",
     "body": "More drops all season.", "url": "/c/new-arrivals/"},
    {"asset": "7-30_COL_CA_S26_HP_Run_Subhero", "heading": "All Gas, Great Brakes",
     "body": "Go further faster with the Konos Speed Trail ATR\u2019s trail-ready "
             "cushioning and traction.",
     "url": "/c/trailrunning/"},
    {"asset": "6-30_COL_US_S26_HP_SummerTech_M_Subhero", "heading": "Cool & UV Protected",
     "body": "Get gear with built-in cooling and sun protection built to beat the heat.",
     "url": "/c/sun-protection/"},
    {"asset": "8-27_COL_US_HP_We_Heart_AmazePuff_Style_Subhero_v2",
     "heading": "Amaze Puff\u2122 Is Back", "body": "The bestseller, now in new colors.",
     "url": "/c/amaze-collection/"},
]


# Source-observed promotional cell injected into the category grid after the
# third product tile.
GRID_PROMO = {
    "image": _cms("Q3_WeHeart_CA_Toolkit_Main_Gridbanner_LO"),
    "heading": "MEMBERS GET EXTRA 30%",
    "body": "On our Annual Summer Sale.",
    "cta": "Shop Now",
    "url": "/c/sale/",
}


def _home_tiles():
    # Source-observed homepage visual-nav tiles.
    return [
        {"label": "Men", "url": "/c/mens/"},
        {"label": "Women", "url": "/c/womens/"},
        {"label": "Kids", "url": "/c/kids/"},
        {"label": "Shoes", "url": "/c/footwear/"},
        {"label": "Accessories", "url": "/c/accessories/"},
        {"label": "Bags & Gear", "url": "/c/equipment/"},
        {"label": "Sale", "url": "/c/sale/"},
    ]


def _breadcrumb(category):
    trail = []
    current = category
    seen = set()
    while current is not None and current.id not in seen:
        seen.add(current.id)
        trail.append(current)
        parent_id = current.parent
        current = catalog.categories.get(parent_id) if parent_id else None
        if current is not None and current.id == "root":
            break
    trail.reverse()
    crumbs = [{"name": "Home", "url": "/"}]
    for node in trail:
        if node.id == "root" or not node.name:
            continue
        is_last = node is trail[-1]
        crumbs.append({"name": node.name, "url": None if is_last else node.url})
    return crumbs


def _siblings(category):
    """The source shows a category's own children when it has any, and falls
    back to its siblings on a leaf grid (observed on /c/womens/ vs
    /c/fleece-jackets/)."""
    own = _menu_children(category)
    if own:
        return own
    parent = catalog.categories.get(category.parent) if category.parent else None
    if parent is None:
        return []
    out = []
    for child_id in parent.children:
        child = catalog.categories.get(child_id)
        if not child or not child.show_in_menu or not child.url:
            continue
        out.append({"name": child.name, "url": child.url, "current": child.id == category.id})
    return out if len(out) > 1 else []


def _menu_children(category):
    out = []
    for child_id in category.children:
        child = catalog.categories.get(child_id)
        if not child or not child.show_in_menu or not child.url:
            continue
        # `alturl_*` entries are navigation aliases of a sibling that is already
        # in this row, so the source's pill row does not repeat them.
        if child.id.startswith("alturl_"):
            continue
        out.append({"name": child.name, "url": child.url, "current": False})
    return out


@app.get("/c/{slug:path}", response_class=HTMLResponse)
def category_page(slug: str, request: Request):
    url = f"/c/{slug}"
    if not url.endswith("/"):
        url += "/"
    category = catalog.category_by_url(url)
    if category is None:
        return _not_found(request)

    params = request.query_params
    selected = grid.parse_refine(params.getlist("refine"))
    sort_id = params.get("sort", "featured-new")
    try:
        page_size = max(int(params.get("pagesize", grid.PAGE_SIZE)), 1)
    except ValueError:
        page_size = grid.PAGE_SIZE

    result = grid.build(catalog.products_in(category.id), selected, sort_id, page_size)
    context = _shell(request)
    heading = _category_heading(category)
    context.update(
        page_title=category.page_title or f"{category.name} | Columbia Sportswear",
        meta_description=category.description,
        heading=heading,
        breadcrumb=_breadcrumb(category),
        # The source omits the breadcrumb on a top-level grid such as
        # /c/womens/ and shows it on a leaf grid such as /c/fleece-jackets/.
        show_breadcrumb=category.depth > 1,
        siblings=_siblings(category),
        visnav=VISNAV.get(category.id),
        result=result,
        tiles=_tiles(result.products, category.enable_compare, "Extra 30% Off Applied"),
        sort_options=SORT_OPTIONS,
        header_mode="sticky",
        grid_promo=GRID_PROMO,
        base_path=url,
        selected_any=any(selected.values()),
        q=None,
        more_url=_page_url(url, params, result.next_page_size),
        all_url=_page_url(url, params, result.total),
    )
    response = templates.TemplateResponse(request, "grid.html", context)
    return _with_cookie(response, request, context["session_id"])


# Headings observed directly on the source category pages. Everywhere else the
# source derives the h1 from its SEO page title minus the brand suffix, which
# matched every page checked (for example /c/fleece-jackets/ -> "Fleece Jackets").
OBSERVED_HEADINGS = {"women": "Shop All Women\u2019s"}
BRAND_SUFFIX = " | Columbia Sportswear"


def _category_heading(category) -> str:
    observed = OBSERVED_HEADINGS.get(category.id)
    if observed:
        return observed
    title = category.page_title or ""
    if title.endswith(BRAND_SUFFIX):
        return title[: -len(BRAND_SUFFIX)]
    return category.name or ""


def _page_url(base: str, params, page_size: int) -> str:
    pairs = [(key, value) for key, value in params.multi_items() if key != "pagesize"]
    pairs.append(("pagesize", str(page_size)))
    from urllib.parse import urlencode

    return f"{base}?{urlencode(pairs)}"


@app.get("/search/", response_class=HTMLResponse)
@app.get("/search", response_class=HTMLResponse)
def search_page(request: Request):
    params = request.query_params
    query = (params.get("q") or "").strip()
    matches = catalog.search(query) if query else []

    # The source redirects a query that names a category straight to that grid.
    if query:
        target = _category_for_query(query)
        if target is not None:
            return RedirectResponse(target.url, status_code=302)

    selected = grid.parse_refine(params.getlist("refine"))
    sort_id = params.get("sort", "featured-new")
    try:
        page_size = max(int(params.get("pagesize", grid.PAGE_SIZE)), 1)
    except ValueError:
        page_size = grid.PAGE_SIZE

    result = grid.build(matches, selected, sort_id, page_size)
    context = _shell(request)
    context.update(
        page_title=f"{query} | Columbia Sportswear" if query else "Search | Columbia Sportswear",
        heading=query,
        breadcrumb=None,
        show_breadcrumb=False,
        siblings=None,
        visnav=None,
        result=result,
        tiles=_tiles(result.products, False, "Extra 30% Off Applied"),
        sort_options=SORT_OPTIONS,
        header_mode="sticky",
        grid_promo=GRID_PROMO,
        base_path="/search/",
        selected_any=any(selected.values()),
        q=query,
        more_url=_page_url("/search/", params, result.next_page_size),
        all_url=_page_url("/search/", params, result.total),
    )
    response = templates.TemplateResponse(request, "grid.html", context)
    return _with_cookie(response, request, context["session_id"])


def _category_for_query(query: str):
    from catalog import _normalize

    wanted = _normalize(query)
    for category in catalog.categories.values():
        if not category.url or not catalog.category_products.get(category.id):
            continue
        names = {category.name or "", _category_heading(category)}
        if any(_normalize(name) == wanted for name in names if name):
            return category
    return None


@app.get("/p/{slug}", response_class=HTMLResponse)
def product_page(slug: str, request: Request):
    url = f"/p/{slug}"
    product = catalog.by_url.get(url)
    if product is None:
        # The source resolves a PDP by its trailing product id and treats the
        # slug as cosmetic, so recover the product that way before 404ing.
        import re

        match = re.search(r"-(\d+)\.html$", url)
        product = catalog.products.get(match.group(1)) if match else None
        if product is None:
            return _not_found(request)
        return RedirectResponse(product.url, status_code=302)

    params = request.query_params
    color_code = params.get("color")
    variant = product.variant_for_color(color_code)
    if variant is not None and color_code != (variant.color_code or ""):
        target = f"{product.url}?color={variant.color_code}"
        if params.get("size"):
            target += f"&size={params['size']}"
        return RedirectResponse(target, status_code=302)

    selected_size = params.get("size")
    if variant and selected_size and selected_size not in variant.sizes:
        selected_size = None

    gallery = [render.slide(media) for media in (variant.images if variant else [])]
    gallery = [item for item in gallery if item]
    swatches = {
        option.color_code: render.media_url(option.primary_image)
        for option in product.variants
    }
    # The source lists the selected colour first, then the remaining variants.
    ordered_variants = (
        [variant] + [v for v in product.variants if v is not variant]
        if variant is not None
        else list(product.variants)
    )
    price = render.price_block(product)
    unit = product.sale_price if product.sale_price is not None else product.min_price

    context = _shell(request)
    context.update(
        page_title=f"{product.name} | Columbia",
        meta_description=product.pitch,
        product=product,
        variant=variant,
        selected_size=selected_size,
        gallery=gallery,
        poster=next((item["src"] for item in gallery if item["kind"] == "image"), None),
        swatches=swatches,
        ordered_variants=ordered_variants,
        price=price,
        points=int(unit * 10) if unit else None,
        collection=_collection_for(product),
        breadcrumb=_pdp_breadcrumb(product),
        parent_category=_pdp_parent(product),
    )
    response = templates.TemplateResponse(request, "pdp.html", context)
    return _with_cookie(response, request, context["session_id"])


def _collection_for(product):
    for path in product.category_path:
        leaf = path.split(">")[-1]
        category = catalog.categories.get(leaf)
        if category and category.name and "Collection" in category.name:
            return category.name
    return None


def _pdp_parent(product):
    """The source's PDP card links back to the product's leaf category."""
    crumbs = _pdp_breadcrumb(product) or []
    for crumb in reversed(crumbs):
        if crumb.get("url") and crumb["url"] != "/":
            return crumb
    return None


def _pdp_breadcrumb(product):
    best = None
    for path in product.category_path:
        parts = path.split(">")
        if len(parts) < 2:
            continue
        leaf = catalog.categories.get(parts[-1])
        if leaf and leaf.show_in_menu and leaf.name:
            if best is None or len(parts) > best[0]:
                best = (len(parts), parts)
    if best is None:
        return None
    crumbs = [{"name": "Home", "url": "/"}]
    for part in best[1]:
        category = catalog.categories.get(part)
        if category and category.name and category.url:
            crumbs.append({"name": category.name, "url": category.url})
    crumbs.append({"name": product.name, "url": None})
    return crumbs


@app.get("/cart", response_class=HTMLResponse)
def cart_page(request: Request, promo_error: str | None = None):
    context = _shell(request)
    view = carts.view(context["session_id"])
    context.update(view, promo_error=promo_error)
    response = templates.TemplateResponse(request, "cart.html", context)
    return _with_cookie(response, request, context["session_id"])


@app.post("/cart/add")
def cart_add(
    request: Request,
    product_id: str = Form(...),
    variant_id: str = Form(None),
    color_code: str = Form(None),
    size: str = Form(None),
    quantity: int = Form(1),
):
    session_id = session_id_for(request)
    product = catalog.products.get(product_id)
    if product is None:
        return _redirect("/cart", request, session_id)
    if not size:
        target = f"{product.url}?color={color_code}&error=size" if color_code else product.url
        return _redirect(target, request, session_id)
    carts.add(session_id, product_id, variant_id, color_code, size, max(quantity, 1))
    return _redirect("/cart", request, session_id)


@app.post("/cart/update")
def cart_update(request: Request, line_id: int = Form(...), quantity: int = Form(...)):
    session_id = session_id_for(request)
    carts.set_quantity(session_id, line_id, quantity)
    return _redirect("/cart", request, session_id)


@app.post("/cart/remove")
def cart_remove(request: Request, line_id: int = Form(...)):
    session_id = session_id_for(request)
    carts.remove(session_id, line_id)
    return _redirect("/cart", request, session_id)


@app.post("/cart/save")
def cart_save(request: Request, line_id: int = Form(...)):
    session_id = session_id_for(request)
    carts.set_saved(session_id, line_id, True)
    return _redirect("/cart", request, session_id)


@app.post("/cart/move")
def cart_move(request: Request, line_id: int = Form(...)):
    session_id = session_id_for(request)
    carts.set_saved(session_id, line_id, False)
    return _redirect("/cart", request, session_id)


@app.post("/cart/promo")
def cart_promo(request: Request, code: str = Form("")):
    session_id = session_id_for(request)
    applied = carts.apply_promo(session_id, code)
    target = "/cart" if applied else "/cart?promo_error=That+promo+code+is+not+valid."
    return _redirect(target, request, session_id)


@app.post("/cart/promo/clear")
def cart_promo_clear(request: Request):
    session_id = session_id_for(request)
    carts.clear_promo(session_id)
    return _redirect("/cart", request, session_id)


def _redirect(target: str, request: Request, session_id: str):
    response = RedirectResponse(target, status_code=303)
    return _with_cookie(response, request, session_id)


def _not_found(request: Request):
    context = _shell(request)
    context.update(page_title="Page Not Found | Columbia Sportswear", heading="Page Not Found", body=None)
    response = templates.TemplateResponse(request, "content.html", context, status_code=404)
    return _with_cookie(response, request, context["session_id"])


# Content routes observed in the source header, footer and mega-menu. Copy for
# these pages was not captured, so they render structurally and are reported as
# `inferred` rather than presented as source-observed.
CONTENT_ROUTES = {
    "/t/accessibility/": "Accessibility Statement",
    "/t/product-care/": "Product Care",
    "/t/tech/": "Product Technology",
    "/t/responsibility/": "Corporate Responsibility",
    "/t/drops/": "Special-Edition Collections",
    "/t/ambassadors/": "Elite Athletes & Ambassadors",
    "/t/business-partner/": "Wholesale",
    "/t/giftcards/": "Gift Cards",
    "/t/coupons/": "Special Deals",
    "/t/discount-programs/": "ID.me Verification",
    "/t/size-fit/": "Size Guides",
    "/t/legal/terms-of-use/": "Terms of Use",
    "/t/legal/terms-of-sale/": "Terms of Sale",
    "/t/legal/privacy-policy/": "Privacy Policy",
    "/t/legal/cgr-terms/": "Rewards Terms and Conditions",
    "/t/legal/ugc-terms/": "User Generated Content Terms of Use",
    "/t/legal/do-not-sell-my-information/": "Do Not Sell or Share My Information",
    "/our-story/": "Our Story",
    "/careers/": "Careers",
    "/warranty/": "Warranty",
    "/order-returns/": "Returns",
    "/stores/": "Find a Store",
    "/rewardsprogram/": "Columbia Greater Rewards",
    "/outdoor-guide.html": "Tough Mother Outdoor Guide",
    "/pro": "Pro Program",
    "/pfg/": "PFG Fishing",
    "/featured/": "Explore",
    "/on/demandware.store/Sites-Columbia_US-Site/en_US/Login-Show": "Log In or Join For Free",
}


@app.get("/t/{path:path}", response_class=HTMLResponse)
def content_route(path: str, request: Request):
    return _content(f"/t/{path}" if path.endswith("/") else f"/t/{path}/", request)


for _route in list(CONTENT_ROUTES):
    if _route.startswith("/t/"):
        continue

    def _make(route: str):
        def handler(request: Request):
            return _content(route, request)

        return handler

    app.add_api_route(_route, _make(_route), methods=["GET"], response_class=HTMLResponse)


def _content(route: str, request: Request):
    heading = CONTENT_ROUTES.get(route)
    if heading is None:
        return _not_found(request)
    context = _shell(request)
    context.update(
        page_title=f"{heading} | Columbia Sportswear", heading=heading, body=None
    )
    response = templates.TemplateResponse(request, "content.html", context)
    return _with_cookie(response, request, context["session_id"])


@app.get("/account", response_class=HTMLResponse)
@app.get("/account/orders", response_class=HTMLResponse)
def account(request: Request):
    """Account surfaces were blocked by the source's bot protection during
    capture, so they are structural-only and reported as `inferred`."""
    context = _shell(request)
    context.update(
        page_title="My Account | Columbia Sportswear", heading="My Account", body=None
    )
    response = templates.TemplateResponse(request, "content.html", context)
    return _with_cookie(response, request, context["session_id"])


@app.post("/checkout")
def checkout(request: Request):
    """Checkout terminates in the local sandbox; no payment path exists here."""
    session_id = session_id_for(request)
    return _redirect("/cart", request, session_id)