File size: 25,789 Bytes
09a1836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
709
710
711
712
713
714
715
"""Business schema, migrations and deterministic seed for the llbean clone.

The catalog rows come from source-observed evidence captured with Playwright in
the Mac Chrome session (see ``materials/llbean/scope/notes/``). Review bodies,
store rows, accounts, addresses and orders are synthetic fixtures: the source
never exposed them in a form this clone may persist.
"""

from __future__ import annotations

import hashlib
import json
import sqlite3
from pathlib import Path
from typing import Any

SEED_DIR = Path(__file__).resolve().parents[1] / "data" / "seed"

# Colour buckets are the 13 facet values observed on the source category page.
COLOR_BUCKETS: dict[str, tuple[str, ...]] = {
    "Black": ("black", "carbon", "onyx", "jet"),
    "Blue": ("blue", "navy", "teal", "indigo", "denim", "nautical", "mallard"),
    "Brown": ("brown", "bark", "chocolate", "coffee", "walnut", "espresso"),
    "Gray": ("gray", "grey", "graphite", "granite", "slate", "mineral", "charcoal"),
    "Green": ("green", "olive", "sage", "moss", "spruce", "forest", "fatigue"),
    "Orange": ("orange", "rust", "blaze", "burnt", "apricot"),
    "Pink": ("pink", "rose", "blush", "coral"),
    "Purple": ("purple", "plum", "violet", "lilac"),
    "Red": ("red", "crimson", "cardinal", "scarlet", "burgundy", "wine"),
    "Tan": ("tan", "khaki", "sand", "camel", "oatmeal", "wheat", "putty", "stone"),
    "White": ("white", "cream", "ivory", "natural", "bone"),
    "Yellow": ("yellow", "gold", "mustard", "honey", "citron"),
    "Multicolor": ("plaid", "print", "multi", "stripe", "camo", "tartan", "buffalo"),
}

# Brand names observed in the source Brand facet.
KNOWN_BRANDS = (
    "L.L.Bean",
    "Anglers Image",
    "Anglers Sport Group",
    "Boyt",
    "Buck",
    "Buff",
    "Byer of Maine",
    "Camelbak",
    "Clic",
    "Darn Tough",
    "ENO",
    "ExOfficio",
    "Fishpond",
    "Flip Focal",
    "Garmin",
    "Gear Keeper",
    "Hydro Flask",
    "Leatherman",
    "Nalgene",
    "Osprey",
    "Smartwool",
    "Thule",
    "Yeti",
)

# Price bands are the nine bands observed in the source Price facet.
PRICE_BANDS: tuple[tuple[str, float, float], ...] = (
    ("$0 to $30", 0.0, 30.0),
    ("$30 to $50", 30.0, 50.0),
    ("$50 to $75", 50.0, 75.0),
    ("$75 to $100", 75.0, 100.0),
    ("$100 to $150", 100.0, 150.0),
    ("$150 to $250", 150.0, 250.0),
    ("$250 to $500", 250.0, 500.0),
    ("$500 to $1000", 500.0, 1000.0),
    ("$1000 to $5000", 1000.0, 5000.0),
)

# The Sale collection filters by discount depth, as the source's "% Off" facet does.
PERCENT_OFF_BANDS: tuple[tuple[str, int, int], ...] = (
    ("20% Off & More", 20, 1000),
    ("30% Off & More", 30, 1000),
    ("40% Off & More", 40, 1000),
    ("50% Off & More", 50, 1000),
)

SORT_FIELDS: dict[str, str] = {
    "relevance": "Recommended",
    "price_low_high": "Price: Low to High",
    "price_high_low": "Price: High to Low",
    "bestselling": "Bestselling",
    "newest": "Newest",
    "rating": "Customer Rating",
}

VIEW_COUNT = 48

SCHEMA = """
CREATE TABLE IF NOT EXISTS categories (
    cat_id      INTEGER PRIMARY KEY,
    name        TEXT NOT NULL,
    slug        TEXT,
    parent_id   INTEGER,
    depth       INTEGER NOT NULL DEFAULT 0,
    nav_order   INTEGER NOT NULL DEFAULT 0,
    kind        TEXT NOT NULL DEFAULT 'category',
    tile_image  TEXT,
    tile_alt    TEXT
);
CREATE TABLE IF NOT EXISTS products (
    product_id     TEXT PRIMARY KEY,
    slug           TEXT,
    name           TEXT NOT NULL,
    item_number    TEXT,
    brand          TEXT NOT NULL DEFAULT 'L.L.Bean',
    description    TEXT,
    material       TEXT,
    price_low      REAL NOT NULL,
    price_high     REAL NOT NULL,
    list_price     REAL NOT NULL,
    sale_price     REAL,
    on_sale        INTEGER NOT NULL DEFAULT 0,
    is_new         INTEGER NOT NULL DEFAULT 0,
    rating         REAL,
    review_count   INTEGER NOT NULL DEFAULT 0,
    availability   TEXT NOT NULL DEFAULT 'InStock',
    low_inventory  INTEGER NOT NULL DEFAULT 0,
    color_count    INTEGER NOT NULL DEFAULT 0,
    gender         TEXT,
    percent_off    INTEGER NOT NULL DEFAULT 0,
    grid_image     TEXT,
    grid_image_alt TEXT,
    position       INTEGER NOT NULL DEFAULT 0,
    breadcrumb     TEXT NOT NULL DEFAULT '[]'
);
CREATE TABLE IF NOT EXISTS product_categories (
    product_id TEXT NOT NULL,
    cat_id     INTEGER NOT NULL,
    PRIMARY KEY (product_id, cat_id)
);
CREATE TABLE IF NOT EXISTS product_images (
    product_id TEXT NOT NULL,
    idx        INTEGER NOT NULL,
    asset      TEXT NOT NULL,
    caption    TEXT,
    PRIMARY KEY (product_id, idx)
);
CREATE TABLE IF NOT EXISTS product_colors (
    product_id TEXT NOT NULL,
    idx        INTEGER NOT NULL,
    name       TEXT NOT NULL,
    bucket     TEXT,
    swatch     TEXT,
    price      REAL,
    PRIMARY KEY (product_id, idx)
);
CREATE TABLE IF NOT EXISTS product_sizes (
    product_id TEXT NOT NULL,
    idx        INTEGER NOT NULL,
    name       TEXT NOT NULL,
    in_stock   INTEGER NOT NULL DEFAULT 1,
    PRIMARY KEY (product_id, idx)
);
CREATE TABLE IF NOT EXISTS reviews (
    review_id    INTEGER PRIMARY KEY AUTOINCREMENT,
    product_id   TEXT NOT NULL,
    rating       INTEGER NOT NULL,
    title        TEXT NOT NULL,
    body         TEXT NOT NULL,
    author       TEXT NOT NULL,
    location     TEXT,
    created_at   TEXT NOT NULL,
    helpful      INTEGER NOT NULL DEFAULT 0,
    not_helpful  INTEGER NOT NULL DEFAULT 0,
    synthetic    INTEGER NOT NULL DEFAULT 1
);
CREATE TABLE IF NOT EXISTS carts (
    cart_id    TEXT PRIMARY KEY,
    owner_key  TEXT NOT NULL UNIQUE,
    created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS cart_items (
    item_id    INTEGER PRIMARY KEY AUTOINCREMENT,
    cart_id    TEXT NOT NULL,
    product_id TEXT NOT NULL,
    color      TEXT,
    size       TEXT,
    qty        INTEGER NOT NULL DEFAULT 1,
    unit_price REAL NOT NULL,
    saved      INTEGER NOT NULL DEFAULT 0,
    added_at   TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS addresses (
    address_id  INTEGER PRIMARY KEY AUTOINCREMENT,
    owner       TEXT NOT NULL,
    label       TEXT,
    first_name  TEXT NOT NULL,
    last_name   TEXT NOT NULL,
    street1     TEXT NOT NULL,
    street2     TEXT,
    city        TEXT NOT NULL,
    state       TEXT NOT NULL,
    postal      TEXT NOT NULL,
    country     TEXT NOT NULL DEFAULT 'United States',
    phone       TEXT,
    is_default  INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS orders (
    order_id     TEXT PRIMARY KEY,
    owner        TEXT NOT NULL,
    order_number TEXT NOT NULL UNIQUE,
    last_name    TEXT NOT NULL,
    postal       TEXT NOT NULL,
    placed_at    TEXT NOT NULL,
    status       TEXT NOT NULL,
    subtotal     REAL NOT NULL,
    shipping     REAL NOT NULL DEFAULT 0,
    tax          REAL NOT NULL DEFAULT 0,
    total        REAL NOT NULL,
    payment_ref  TEXT
);
CREATE TABLE IF NOT EXISTS order_items (
    order_item_id INTEGER PRIMARY KEY AUTOINCREMENT,
    order_id      TEXT NOT NULL,
    product_id    TEXT NOT NULL,
    name          TEXT NOT NULL,
    color         TEXT,
    size          TEXT,
    qty           INTEGER NOT NULL,
    unit_price    REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS stores (
    store_id   INTEGER PRIMARY KEY,
    name       TEXT NOT NULL,
    street     TEXT NOT NULL,
    city       TEXT NOT NULL,
    state      TEXT NOT NULL,
    postal     TEXT NOT NULL,
    phone      TEXT NOT NULL,
    hours      TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS wishlist_items (
    wish_id    INTEGER PRIMARY KEY AUTOINCREMENT,
    owner      TEXT NOT NULL,
    product_id TEXT NOT NULL,
    added_at   TEXT NOT NULL,
    UNIQUE (owner, product_id)
);
CREATE TABLE IF NOT EXISTS gift_cards (
    code      TEXT PRIMARY KEY,
    pin       TEXT NOT NULL,
    balance   REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS promotions (
    code       TEXT PRIMARY KEY,
    kind       TEXT NOT NULL,
    amount     REAL NOT NULL,
    label      TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS cart_promotions (
    cart_id TEXT NOT NULL,
    code    TEXT NOT NULL,
    PRIMARY KEY (cart_id, code)
);
CREATE TABLE IF NOT EXISTS catalog_requests (
    request_id INTEGER PRIMARY KEY AUTOINCREMENT,
    first_name TEXT NOT NULL,
    last_name  TEXT NOT NULL,
    email      TEXT NOT NULL,
    street1    TEXT NOT NULL,
    city       TEXT NOT NULL,
    state      TEXT NOT NULL,
    postal     TEXT NOT NULL,
    created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS email_prefs (
    owner       TEXT PRIMARY KEY,
    subscribed  INTEGER NOT NULL DEFAULT 1,
    frequency   TEXT NOT NULL DEFAULT 'weekly',
    catalog_opt INTEGER NOT NULL DEFAULT 1
);
CREATE TABLE IF NOT EXISTS nav_menu (
    row_id     INTEGER PRIMARY KEY AUTOINCREMENT,
    top_label  TEXT NOT NULL,
    kind       TEXT NOT NULL,
    position   INTEGER NOT NULL,
    depth      INTEGER NOT NULL,
    label      TEXT NOT NULL,
    cat_id     INTEGER,
    slug       TEXT,
    is_group   INTEGER NOT NULL DEFAULT 0,
    group_label TEXT
);
CREATE TABLE IF NOT EXISTS category_facets (
    cat_id   INTEGER NOT NULL,
    position INTEGER NOT NULL,
    facet    TEXT NOT NULL,
    PRIMARY KEY (cat_id, facet)
);
CREATE TABLE IF NOT EXISTS lander_sections (
    section_id INTEGER PRIMARY KEY AUTOINCREMENT,
    cat_id     INTEGER NOT NULL,
    position   INTEGER NOT NULL,
    heading    TEXT,
    prose      TEXT,
    view_all_cat_id INTEGER,
    view_all_slug   TEXT
);
CREATE TABLE IF NOT EXISTS lander_items (
    item_id    INTEGER PRIMARY KEY AUTOINCREMENT,
    section_id INTEGER NOT NULL,
    position   INTEGER NOT NULL,
    label      TEXT NOT NULL,
    cat_id     INTEGER,
    slug       TEXT,
    blurb      TEXT,
    asset      TEXT,
    alt        TEXT,
    external   INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS home_sections (
    section_id  INTEGER PRIMARY KEY AUTOINCREMENT,
    key         TEXT NOT NULL UNIQUE,
    kind        TEXT NOT NULL,
    position    INTEGER NOT NULL,
    heading     TEXT,
    sub         TEXT,
    cta_label   TEXT,
    cta_cat_id  INTEGER,
    cta_slug    TEXT
);
CREATE TABLE IF NOT EXISTS home_items (
    item_id    INTEGER PRIMARY KEY AUTOINCREMENT,
    section_id INTEGER NOT NULL,
    position   INTEGER NOT NULL,
    label      TEXT NOT NULL,
    cat_id     INTEGER,
    slug       TEXT,
    blurb      TEXT,
    asset      TEXT,
    alt        TEXT
);
CREATE TABLE IF NOT EXISTS recently_viewed (
    owner      TEXT NOT NULL,
    product_id TEXT NOT NULL,
    viewed_at  TEXT NOT NULL,
    PRIMARY KEY (owner, product_id)
);
CREATE TABLE IF NOT EXISTS content_pages (
    cat_id INTEGER PRIMARY KEY,
    name   TEXT NOT NULL,
    blurb  TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_pc_cat ON product_categories(cat_id);
CREATE INDEX IF NOT EXISTS idx_ci_cart ON cart_items(cart_id);
CREATE INDEX IF NOT EXISTS idx_rev_product ON reviews(product_id);
CREATE INDEX IF NOT EXISTS idx_oi_order ON order_items(order_id);
"""


def migrate(connection: sqlite3.Connection) -> None:
    """Create the business schema. Safe to run repeatedly.

    Statements run one at a time on purpose: ``executescript`` commits the
    caller's open transaction, which breaks the backend lifecycle contract.
    """

    for statement in SCHEMA.split(";"):
        if statement.strip():
            connection.execute(statement)


def _load(name: str) -> Any:
    return json.loads((SEED_DIR / name).read_text(encoding="utf-8"))


def _color_bucket(name: str) -> str | None:
    lowered = name.lower()
    for bucket, needles in COLOR_BUCKETS.items():
        if any(needle in lowered for needle in needles):
            return bucket
    return None


GENDER_CRUMBS = {
    "Women's": "Women's",
    "Men's": "Men's",
    "Kids'": "Kids'",
    "Baby": "Kids'",
    "Toddler": "Kids'",
    "Girls'": "Kids'",
    "Boys'": "Kids'",
}


def _gender_for(breadcrumb: list[str], name: str) -> str | None:
    """Gender comes from the breadcrumb the source renders on the product page."""

    for crumb in breadcrumb:
        for needle, label in GENDER_CRUMBS.items():
            if needle.lower() in crumb.lower():
                return label
    for needle, label in GENDER_CRUMBS.items():
        if name.lower().startswith(needle.lower()):
            return label
    return None


def _brand_for(name: str) -> str:
    for brand in KNOWN_BRANDS:
        if brand == "L.L.Bean":
            continue
        if brand.lower() in name.lower():
            return brand
    return "L.L.Bean"


def _stable_int(*parts: str) -> int:
    digest = hashlib.sha256("|".join(parts).encode("utf-8")).hexdigest()
    return int(digest[:8], 16)


REVIEW_TEMPLATES = (
    (5, "Exactly what I wanted", "Held up through a full season of use and still looks new. Sizing was true to the chart."),
    (5, "Buy it once", "Well made and thoughtfully designed. The details are where this one earns its price."),
    (4, "Very good, one small note", "Quality is excellent. I would prefer one more pocket, but that is a minor thing."),
    (4, "Solid everyday pick", "Comfortable and durable. Colour matches the product photos closely."),
    (3, "Good but runs large", "The material is nice. I sized down and it fit much better."),
    (2, "Not for me", "The fit was not right for my build and the fabric was heavier than I expected."),
    (1, "Disappointed", "Arrived with a loose seam. Returns were straightforward but I expected better."),
)

AUTHORS = (
    ("Casco Bay Hiker", "Portland, ME"),
    ("Trailhead Sam", "Burlington, VT"),
    ("Northwoods Reader", "Duluth, MN"),
    ("Coastal Walker", "Camden, ME"),
    ("Weekend Paddler", "Ithaca, NY"),
    ("Frost Hollow", "Berlin, NH"),
    ("Granite Stater", "Concord, NH"),
)

SEED_STORES = (
    (1, "Freeport Flagship Store", "95 Main Street", "Freeport", "ME", "04033", "(877) 755-2326", "Open 24 hours"),
    (2, "Portland Store", "375 Riverside Street", "Portland", "ME", "04103", "(207) 470-1200", "9:00 AM - 8:00 PM"),
    (3, "South Portland Store", "200 Running Hill Road", "South Portland", "ME", "04106", "(207) 253-9500", "9:00 AM - 9:00 PM"),
    (4, "Burlington Store", "49 Church Street", "Burlington", "VT", "05401", "(802) 448-3800", "10:00 AM - 7:00 PM"),
    (5, "Nashua Store", "310 Daniel Webster Highway", "Nashua", "NH", "03060", "(603) 546-5100", "10:00 AM - 8:00 PM"),
    (6, "Marlborough Store", "601 Donald Lynch Boulevard", "Marlborough", "MA", "01752", "(508) 251-3000", "10:00 AM - 8:00 PM"),
    (7, "Yonkers Store", "2500 Central Park Avenue", "Yonkers", "NY", "10710", "(914) 573-2000", "10:00 AM - 8:00 PM"),
    (8, "King of Prussia Store", "160 North Gulph Road", "King of Prussia", "PA", "19406", "(610) 337-4400", "10:00 AM - 8:00 PM"),
    (9, "Columbia Store", "6151 Little River Turnpike", "Alexandria", "VA", "22312", "(703) 941-3400", "10:00 AM - 8:00 PM"),
    (10, "Glenview Store", "1931 Tower Drive", "Glenview", "IL", "60026", "(847) 400-2100", "10:00 AM - 8:00 PM"),
)

SEED_PROMOTIONS = (
    ("BEAN20", "percent", 20.0, "20% off your order"),
    ("SHIPFREE", "shipping", 0.0, "Free standard shipping"),
    ("TRAIL10", "amount", 10.0, "$10 off your order"),
)

SEED_GIFT_CARDS = (
    ("6006000000000001", "1234", 75.00),
    ("6006000000000002", "5678", 0.00),
)


def seed(connection: sqlite3.Connection) -> None:
    """Seed deterministic catalog data. Idempotent."""

    migrate(connection)
    if connection.execute("SELECT COUNT(*) FROM products").fetchone()[0]:
        return

    categories = _load("categories.json")
    tiles = _load("category_tiles.json")
    connection.executemany(
        "INSERT OR REPLACE INTO categories"
        " (cat_id, name, slug, parent_id, depth, nav_order, kind, tile_image, tile_alt)"
        " VALUES (?,?,?,?,?,?,?,?,?)",
        [
            (
                c["cat_id"],
                c["name"],
                c.get("slug"),
                c.get("parent_id"),
                c.get("depth", 0),
                c.get("nav_order", 0),
                "category",
                (
                    f"/static/img/category/{c['cat_id']}.jpg"
                    if str(c["cat_id"]) in tiles
                    else None
                ),
                (tiles.get(str(c["cat_id"]), {}) or {}).get("alt"),
            )
            for c in categories
        ],
    )

    products = _load("products.json")
    known_categories = {c["cat_id"] for c in categories}
    outdoor_equipment = 29

    for product in products:
        pid = str(product["product_id"])
        name = product["name"]
        low = float(product["price_low"])
        high = float(product["price_high"])
        on_sale = 1 if product.get("on_sale") else 0
        seed_int = _stable_int(pid, name)
        low_inventory = 1 if seed_int % 7 == 0 else 0
        is_new = 1 if seed_int % 5 == 0 else 0

        connection.execute(
            "INSERT OR REPLACE INTO products (product_id, slug, name, item_number, brand,"
            " description, material, price_low, price_high, list_price, sale_price, on_sale,"
            " is_new, rating, review_count, availability, low_inventory, color_count,"
            " gender, percent_off, grid_image, grid_image_alt, position, breadcrumb)"
            " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
            (
                pid,
                product.get("slug"),
                name,
                product.get("item_number"),
                _brand_for(name),
                product.get("description"),
                product.get("material"),
                low,
                high,
                float(product.get("list_price") or high),
                product.get("sale_price"),
                on_sale,
                is_new,
                product.get("rating"),
                int(product.get("review_count") or 0),
                product.get("availability") or "InStock",
                low_inventory,
                int(product.get("color_count") or 0),
                _gender_for(product.get("breadcrumb") or [], name),
                (
                    round((1 - low / high) * 100)
                    if on_sale and high
                    else 0
                ),
                f"/static/img/product/{pid}_grid.webp",
                product.get("grid_image_alt") or name,
                int(product.get("position") or 0),
                json.dumps(product.get("breadcrumb") or []),
            ),
        )

        # Category membership comes from the crawl: every category page whose grid
        # listed this product. Falls back to the deepest known breadcrumb name.
        assigned = [c for c in (product.get("categories") or []) if c in known_categories]
        if not assigned:
            for crumb in reversed(product.get("breadcrumb") or []):
                match = connection.execute(
                    "SELECT cat_id FROM categories WHERE name = ? ORDER BY depth DESC LIMIT 1",
                    (crumb,),
                ).fetchone()
                if match and match[0] in known_categories:
                    assigned = [match[0]]
                    break
        for cat_id in assigned or [outdoor_equipment]:
            connection.execute(
                "INSERT OR IGNORE INTO product_categories (product_id, cat_id) VALUES (?,?)",
                (pid, cat_id),
            )

        detail_limit = 5 if product.get("observed_in_grid") else 2
        for idx, image in enumerate(product.get("images") or []):
            if idx >= detail_limit:
                break
            connection.execute(
                "INSERT OR REPLACE INTO product_images (product_id, idx, asset, caption)"
                " VALUES (?,?,?,?)",
                (pid, idx, f"/static/img/product/{pid}_d{idx}.webp", image.get("caption")),
            )

        swatches = product.get("swatches") or []
        colors = product.get("colors") or []
        for idx, color in enumerate(colors):
            swatch_asset = None
            if idx < len(swatches):
                swatch_asset = f"/static/img/swatch/{pid}_s{idx}.webp"
            connection.execute(
                "INSERT OR REPLACE INTO product_colors (product_id, idx, name, bucket, swatch, price)"
                " VALUES (?,?,?,?,?,?)",
                (
                    pid,
                    idx,
                    color,
                    _color_bucket(color),
                    swatch_asset,
                    low if (on_sale and idx == 0) else high,
                ),
            )

        for idx, size in enumerate(product.get("sizes") or []):
            connection.execute(
                "INSERT OR REPLACE INTO product_sizes (product_id, idx, name, in_stock)"
                " VALUES (?,?,?,?)",
                (pid, idx, size, 0 if (seed_int + idx) % 11 == 0 else 1),
            )

        # Synthetic review bodies distributed to match the observed rating.
        target = float(product.get("rating") or 4.5)
        count = min(int(product.get("review_count") or 0), 12)
        for n in range(count):
            template = REVIEW_TEMPLATES[(seed_int + n) % len(REVIEW_TEMPLATES)]
            if n < max(1, int(count * 0.7)):
                template = REVIEW_TEMPLATES[(seed_int + n) % 2]
            author, location = AUTHORS[(seed_int + n) % len(AUTHORS)]
            day = 1 + ((seed_int + n * 7) % 28)
            month = 1 + ((seed_int + n * 3) % 12)
            connection.execute(
                "INSERT INTO reviews (product_id, rating, title, body, author, location,"
                " created_at, helpful, not_helpful, synthetic) VALUES (?,?,?,?,?,?,?,?,?,1)",
                (
                    pid,
                    template[0],
                    template[1],
                    template[2],
                    author,
                    location,
                    f"2026-{month:02d}-{day:02d}",
                    (seed_int + n) % 40,
                    (seed_int + n) % 5,
                ),
            )
        del target

    connection.executemany(
        "INSERT INTO nav_menu (top_label, kind, position, depth, label, cat_id, slug,"
        " is_group, group_label) VALUES (?,?,?,?,?,?,?,?,?)",
        [
            (
                m["top"], m["kind"], m["position"], m["depth"], m["label"],
                m.get("cat_id"), m.get("slug"), m.get("is_group", 0), m.get("group"),
            )
            for m in _load("nav_menu.json")
        ],
    )
    facet_cfg = _load("category_facets.json")
    connection.executemany(
        "INSERT OR REPLACE INTO category_facets (cat_id, position, facet) VALUES (?,?,?)",
        [
            (int(cat_id), position, facet)
            for cat_id, entry in facet_cfg.items()
            for position, facet in enumerate(entry["facets"])
        ],
    )
    home = _load("home.json")
    for position, section in enumerate(home["sections"]):
        cursor = connection.execute(
            "INSERT OR REPLACE INTO home_sections (key, kind, position, heading, sub,"
            " cta_label, cta_cat_id, cta_slug) VALUES (?,?,?,?,?,?,?,?)",
            (
                section["key"], section["kind"], section.get("position", position),
                section.get("heading"), section.get("sub"),
                section.get("cta_label"), section.get("cta_cat_id"), section.get("cta_slug"),
            ),
        )
        connection.executemany(
            "INSERT INTO home_items (section_id, position, label, cat_id, slug, blurb,"
            " asset, alt) VALUES (?,?,?,?,?,?,?,?)",
            [
                (
                    cursor.lastrowid, i, it["label"], it.get("cat_id"), it.get("slug"),
                    it.get("blurb"), it.get("asset"), it.get("alt"),
                )
                for i, it in enumerate(section["items"])
            ],
        )

    for cat_id, lander in _load("landers.json").items():
        for position, section in enumerate(lander["sections"]):
            view_all = section.get("view_all") or {}
            cursor = connection.execute(
                "INSERT INTO lander_sections (cat_id, position, heading, prose,"
                " view_all_cat_id, view_all_slug) VALUES (?,?,?,?,?,?)",
                (
                    int(cat_id), position, section.get("heading"), section.get("prose"),
                    view_all.get("cat_id"), view_all.get("slug"),
                ),
            )
            section_id = cursor.lastrowid
            connection.executemany(
                "INSERT INTO lander_items (section_id, position, label, cat_id, slug,"
                " blurb, asset, alt, external) VALUES (?,?,?,?,?,?,?,?,?)",
                [
                    (
                        section_id, i, it["label"], it.get("cat_id"), it.get("slug"),
                        it.get("blurb"), it.get("asset"), it.get("alt"),
                        1 if it.get("external") else 0,
                    )
                    for i, it in enumerate(section["items"])
                ],
            )
    connection.executemany(
        "INSERT OR REPLACE INTO content_pages (cat_id, name, blurb) VALUES (?,?,?)",
        [(c["cat_id"], c["name"], c["blurb"]) for c in _load("content_pages.json")],
    )
    connection.executemany(
        "INSERT OR REPLACE INTO stores (store_id, name, street, city, state, postal, phone, hours)"
        " VALUES (?,?,?,?,?,?,?,?)",
        SEED_STORES,
    )
    connection.executemany(
        "INSERT OR REPLACE INTO promotions (code, kind, amount, label) VALUES (?,?,?,?)",
        SEED_PROMOTIONS,
    )
    connection.executemany(
        "INSERT OR REPLACE INTO gift_cards (code, pin, balance) VALUES (?,?,?)",
        SEED_GIFT_CARDS,
    )