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
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
"""Lowe's offline clone — site business schema, catalog, cart and orders.

This module owns everything Lowe's-specific that touches SQLite. The generic
account / session / mail / payment tables are owned by the vendored
``websitebench.site_backend`` and ``websitebench.local_clone_auth`` runtimes in
the *same* bound database file, opened only through
``backend/site_backend_integration.py``.

Contract wiring (``backend/runtime.json``):

* ``database.migration_hook`` -> :func:`migration_hook`
* ``database.seed_hook``      -> :func:`seed_hook`

Both hooks are idempotent and re-runnable, and :func:`ensure_ready` applies the
same work on an already-bound database so a schema addition still lands after
the lifecycle has recorded the one-shot hook.

Determinism: there is no wall clock and no randomness anywhere in this module.
Row identities come from explicit seed ids or from SQLite rowids that restart
after a reset, and every timestamp is :data:`FROZEN_CLOCK_UTC`. Two identical
operation sequences produce identical rows, which
``tests/test_backend_accounts.py::test_reset_restores_a_deterministic_snapshot``
asserts by comparing :func:`state_snapshot` output across a reset.

Payment boundary: the clone never accepts a card number, CVV, expiry, bank or
wallet credential. The only client-supplied payment input is an opaque
``scenario_id`` drawn from the frozen ``local-sandbox`` scenario list; owner,
amount, currency and fingerprint are all derived server-side from the persisted
cart.
"""

from __future__ import annotations

import hashlib
import json
import re
import sqlite3
import threading
from contextlib import closing, contextmanager
from pathlib import Path
from typing import Any, Iterable, Iterator, Mapping, Sequence

from websitebench.local_clone_auth import LocalAuthStore
from websitebench.site_backend import SiteBackend

from backend import seed_data
from backend.site_backend_integration import open_site_services

SITE_ID = "lowes"
CURRENCY = "USD"

# One frozen clock for the whole clone (the day the source observation was
# recorded, UTC). Never call a real clock here.
FROZEN_CLOCK_UTC = "2026-08-20T12:00:00Z"

PICKUP_HOLD_DAYS = 3
FREE_DELIVERY_THRESHOLD_CENTS = 4500
STANDARD_DELIVERY_CENTS = 1999
BULKY_DELIVERY_CENTS = 7999
MAX_LINE_QUANTITY = 99
PAGE_SIZE = 12

SORT_OPTIONS: tuple[tuple[str, str], ...] = (
    ("relevance", "Best Match"),
    ("top-sellers", "Top Sellers"),
    ("price-low", "Price: Low to High"),
    ("price-high", "Price: High to Low"),
    ("rating", "Top Rated"),
    ("savings", "Biggest Savings"),
)
SORT_IDS = frozenset(key for key, _ in SORT_OPTIONS)

FULFILLMENTS = ("pickup", "delivery")

# Sales-tax basis points by shipping state. A frozen local table, not a rate
# service: the clone must never call out.
TAX_BASIS_POINTS: dict[str, int] = {
    "AZ": 560,
    "CA": 950,
    "CO": 290,
    "FL": 600,
    "GA": 400,
    "IL": 625,
    "MI": 600,
    "NC": 475,
    "NJ": 663,
    "NV": 685,
    "NY": 800,
    "OH": 575,
    "PA": 600,
    "TN": 700,
    "TX": 825,
    "VA": 530,
    "WA": 650,
}
DEFAULT_TAX_BASIS_POINTS = 700

US_STATES: tuple[str, ...] = (
    "AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "DC", "FL", "GA", "HI",
    "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN",
    "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH",
    "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA",
    "WV", "WI", "WY",
)

# Any key that looks like a stored payment credential is refused before it can
# reach a business table, mirroring the mandate's "never receive or store card
# number, CVV, expiry, bank or wallet credentials" rule.
_PAYMENT_KEY_RE = re.compile(
    r"(?i)(card|cc[-_]?(num|number|exp)|cvv|cvc|\bpan\b|iban|routing"
    r"|account[-_]?number|expir|security[-_]?code|payment[-_]?(method|token)"
    r"|stripe|bank|wallet)"
)
_SERVER_PAYMENT_FACT_KEYS = frozenset(
    {
        "adapter",
        "amountminor",
        "attemptid",
        "currency",
        "fingerprint",
        "flowid",
        "owner",
        "providerreference",
        "providersessionid",
        "subtotalcents",
        "totalcents",
    }
)


class PaymentFieldRejected(ValueError):
    """A card/payment-like key reached a business input path."""


class CheckoutError(ValueError):
    """Checkout input failed server-side validation."""

    def __init__(self, errors: Mapping[str, str]) -> None:
        super().__init__("checkout validation failed")
        self.errors = dict(errors)


def reject_payment_keys(payload: Mapping[str, Any]) -> None:
    for key in payload:
        normalized = re.sub(r"[^a-z0-9]", "", str(key).casefold())
        if _PAYMENT_KEY_RE.search(str(key)) or normalized in _SERVER_PAYMENT_FACT_KEYS:
            raise PaymentFieldRejected(
                f"payment-like field {key!r} is outside this clone's scope"
            )


# ---------------------------------------------------------------------------
# schema
# ---------------------------------------------------------------------------

_MIGRATIONS: tuple[tuple[str, tuple[str, ...]], ...] = (
    (
        "0001_catalog",
        (
            """
            CREATE TABLE IF NOT EXISTS lowes_categories (
                id TEXT PRIMARY KEY,
                label TEXT NOT NULL,
                position INTEGER NOT NULL,
                art_light TEXT NOT NULL,
                art_dark TEXT NOT NULL
            )
            """,
            """
            CREATE TABLE IF NOT EXISTS lowes_products (
                id INTEGER PRIMARY KEY,
                slug TEXT NOT NULL UNIQUE,
                title TEXT NOT NULL,
                brand TEXT NOT NULL,
                category_id TEXT NOT NULL REFERENCES lowes_categories (id),
                price_cents INTEGER NOT NULL CHECK (price_cents > 0),
                was_cents INTEGER CHECK (was_cents IS NULL OR was_cents > price_cents),
                rating REAL NOT NULL CHECK (rating >= 0 AND rating <= 5),
                review_count INTEGER NOT NULL CHECK (review_count >= 0),
                badge TEXT,
                model_number TEXT NOT NULL,
                keywords TEXT NOT NULL,
                stock INTEGER NOT NULL CHECK (stock >= 0),
                pickup_today INTEGER NOT NULL CHECK (pickup_today IN (0, 1)),
                free_delivery INTEGER NOT NULL CHECK (free_delivery IN (0, 1)),
                delivery_days INTEGER NOT NULL CHECK (delivery_days > 0),
                specs_json TEXT NOT NULL,
                summary TEXT NOT NULL
            )
            """,
            "CREATE INDEX IF NOT EXISTS idx_lowes_products_category"
            " ON lowes_products (category_id)",
            """
            CREATE TABLE IF NOT EXISTS lowes_stores (
                id TEXT PRIMARY KEY,
                name TEXT NOT NULL,
                city TEXT NOT NULL,
                state TEXT NOT NULL,
                zip TEXT NOT NULL,
                closes_at TEXT NOT NULL,
                position INTEGER NOT NULL
            )
            """,
        ),
    ),
    (
        "0002_cart",
        (
            """
            CREATE TABLE IF NOT EXISTS lowes_cart_items (
                id INTEGER PRIMARY KEY,
                owner_digest TEXT NOT NULL,
                product_id INTEGER NOT NULL
                    REFERENCES lowes_products (id) ON DELETE CASCADE,
                quantity INTEGER NOT NULL CHECK (quantity BETWEEN 1 AND 99),
                fulfillment TEXT NOT NULL
                    CHECK (fulfillment IN ('pickup', 'delivery')),
                store_id TEXT REFERENCES lowes_stores (id),
                unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents > 0),
                unit_was_cents INTEGER,
                created_at TEXT NOT NULL,
                updated_at TEXT NOT NULL,
                UNIQUE (owner_digest, product_id, fulfillment)
            )
            """,
            "CREATE INDEX IF NOT EXISTS idx_lowes_cart_owner"
            " ON lowes_cart_items (owner_digest)",
        ),
    ),
    (
        "0003_orders",
        (
            """
            CREATE TABLE IF NOT EXISTS lowes_orders (
                id INTEGER PRIMARY KEY,
                order_number TEXT NOT NULL UNIQUE,
                owner_digest TEXT NOT NULL,
                account_id TEXT,
                email TEXT NOT NULL,
                customer_name TEXT NOT NULL,
                fulfillment TEXT NOT NULL
                    CHECK (fulfillment IN ('pickup', 'delivery')),
                store_id TEXT REFERENCES lowes_stores (id),
                address_json TEXT,
                subtotal_cents INTEGER NOT NULL CHECK (subtotal_cents >= 0),
                savings_cents INTEGER NOT NULL CHECK (savings_cents >= 0),
                delivery_cents INTEGER NOT NULL CHECK (delivery_cents >= 0),
                tax_cents INTEGER NOT NULL CHECK (tax_cents >= 0),
                total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
                currency TEXT NOT NULL,
                fingerprint TEXT NOT NULL,
                payment_flow_id TEXT NOT NULL UNIQUE,
                payment_attempt_id TEXT NOT NULL UNIQUE,
                scenario_id TEXT NOT NULL,
                mail_id TEXT UNIQUE,
                status TEXT NOT NULL CHECK (status IN ('placed')),
                created_at TEXT NOT NULL
            )
            """,
            "CREATE INDEX IF NOT EXISTS idx_lowes_orders_owner"
            " ON lowes_orders (owner_digest)",
            """
            CREATE TABLE IF NOT EXISTS lowes_order_items (
                id INTEGER PRIMARY KEY,
                order_id INTEGER NOT NULL
                    REFERENCES lowes_orders (id) ON DELETE CASCADE,
                product_id INTEGER NOT NULL,
                title TEXT NOT NULL,
                brand TEXT NOT NULL,
                slug TEXT NOT NULL,
                quantity INTEGER NOT NULL CHECK (quantity > 0),
                unit_price_cents INTEGER NOT NULL CHECK (unit_price_cents > 0),
                line_total_cents INTEGER NOT NULL CHECK (line_total_cents > 0),
                fulfillment TEXT NOT NULL
            )
            """,
            "CREATE INDEX IF NOT EXISTS idx_lowes_order_items_order"
            " ON lowes_order_items (order_id)",
        ),
    ),
)


def _apply_migrations(connection: sqlite3.Connection) -> list[str]:
    """Apply every pending site migration inside the caller's connection.

    Uses individual ``execute`` calls rather than ``executescript`` because the
    lifecycle hook runs inside an open ``BEGIN IMMEDIATE`` transaction and
    ``executescript`` would commit it.
    """

    connection.execute(
        """
        CREATE TABLE IF NOT EXISTS lowes_schema_migrations (
            migration_id TEXT PRIMARY KEY,
            applied_at TEXT NOT NULL
        )
        """
    )
    applied = {
        str(row[0])
        for row in connection.execute(
            "SELECT migration_id FROM lowes_schema_migrations"
        )
    }
    newly: list[str] = []
    for migration_id, statements in _MIGRATIONS:
        if migration_id in applied:
            continue
        for statement in statements:
            connection.execute(statement)
        connection.execute(
            "INSERT INTO lowes_schema_migrations (migration_id, applied_at)"
            " VALUES (?, ?)",
            (migration_id, FROZEN_CLOCK_UTC),
        )
        newly.append(migration_id)
    return newly


def _seed_catalog(connection: sqlite3.Connection) -> None:
    """Insert the frozen catalog. Idempotent and order-stable."""

    for category in seed_data.CATEGORIES:
        connection.execute(
            "INSERT OR REPLACE INTO lowes_categories"
            " (id, label, position, art_light, art_dark) VALUES (?, ?, ?, ?, ?)",
            (
                category["id"],
                category["label"],
                category["position"],
                category["art"][0],
                category["art"][1],
            ),
        )
    for store in seed_data.STORES:
        connection.execute(
            "INSERT OR REPLACE INTO lowes_stores"
            " (id, name, city, state, zip, closes_at, position)"
            " VALUES (?, ?, ?, ?, ?, ?, ?)",
            (
                store["id"],
                store["name"],
                store["city"],
                store["state"],
                store["zip"],
                store["closes_at"],
                store["position"],
            ),
        )
    for product in seed_data.PRODUCTS:
        connection.execute(
            "INSERT OR REPLACE INTO lowes_products"
            " (id, slug, title, brand, category_id, price_cents, was_cents,"
            "  rating, review_count, badge, model_number, keywords, stock,"
            "  pickup_today, free_delivery, delivery_days, specs_json, summary)"
            " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            (
                product["id"],
                product["slug"],
                product["title"],
                product["brand"],
                product["category_id"],
                product["price_cents"],
                product["was_cents"],
                product["rating"],
                product["review_count"],
                product["badge"],
                product["model_number"],
                product["keywords"],
                product["stock"],
                product["pickup_today"],
                product["free_delivery"],
                product["delivery_days"],
                json.dumps(product["specs"], sort_keys=False, separators=(",", ":")),
                product["summary"],
            ),
        )


def migration_hook(connection: sqlite3.Connection) -> None:
    """Runtime-declared migration hook (``backend.store:migration_hook``)."""

    _apply_migrations(connection)


def seed_hook(connection: sqlite3.Connection) -> None:
    """Runtime-declared seed hook (``backend.store:seed_hook``)."""

    _apply_migrations(connection)
    _seed_catalog(connection)


# ---------------------------------------------------------------------------
# services
# ---------------------------------------------------------------------------

_SERVICES_LOCK = threading.Lock()
_SERVICES: tuple[SiteBackend, LocalAuthStore] | None = None


def services() -> tuple[SiteBackend, LocalAuthStore]:
    global _SERVICES
    with _SERVICES_LOCK:
        if _SERVICES is None:
            backend, auth = open_site_services()
            ensure_ready(backend.lifecycle.database_path)
            _SERVICES = (backend, auth)
        return _SERVICES


def close_services() -> None:
    """Drop the cached pair so a test can re-open against a fresh database."""

    global _SERVICES
    with _SERVICES_LOCK:
        _SERVICES = None


def database_path() -> Path:
    return services()[0].lifecycle.database_path


def _connect(path: Path) -> sqlite3.Connection:
    # Autocommit at the driver level so every write path owns an explicit
    # ``BEGIN IMMEDIATE``; the vendored payment/mail APIs require a caller
    # transaction that is genuinely open.
    connection = sqlite3.connect(str(path), timeout=30, isolation_level=None)
    connection.row_factory = sqlite3.Row
    connection.execute("PRAGMA foreign_keys = ON")
    connection.execute("PRAGMA busy_timeout = 30000")
    return connection


def connect() -> sqlite3.Connection:
    return _connect(database_path())


@contextmanager
def transaction(connection: sqlite3.Connection) -> Iterator[sqlite3.Connection]:
    connection.execute("BEGIN IMMEDIATE")
    try:
        yield connection
    except BaseException:
        if connection.in_transaction:
            connection.execute("ROLLBACK")
        raise
    else:
        if connection.in_transaction:
            connection.execute("COMMIT")


def ensure_ready(path: Path) -> None:
    """Apply pending migrations and seed rows on an already-bound database."""

    with closing(_connect(path)) as connection, transaction(connection):
        _apply_migrations(connection)
        empty = (
            connection.execute("SELECT COUNT(*) FROM lowes_products").fetchone()[0] == 0
        )
        if empty:
            _seed_catalog(connection)


def reset() -> dict[str, Any]:
    """Deterministically restore the seeded state in one transaction."""

    backend, auth = services()

    def _site_reset(connection: sqlite3.Connection) -> None:
        for table in (
            "lowes_order_items",
            "lowes_orders",
            "lowes_cart_items",
            "lowes_products",
            "lowes_stores",
            "lowes_categories",
        ):
            connection.execute(f"DELETE FROM {table}")
        # No site table uses AUTOINCREMENT, so clearing the rows also restarts
        # the implicit rowid counters and order numbers stay reproducible.
        _apply_migrations(connection)
        _seed_catalog(connection)
        backend.lifecycle.reset_embedded(connection, confirm_site_id=SITE_ID)

    auth.reset_site_state(site_reset=_site_reset, seed_accounts=[])
    return {"reset": True, "site_id": SITE_ID, "seed_id": seed_data.SEED_ID}


def state_snapshot() -> dict[str, Any]:
    """A stable, comparable projection of every site-owned table."""

    with closing(connect()) as connection:
        snapshot: dict[str, Any] = {}
        for table, order in (
            ("lowes_categories", "position, id"),
            ("lowes_stores", "position, id"),
            ("lowes_products", "id"),
            ("lowes_cart_items", "owner_digest, product_id, fulfillment"),
            ("lowes_orders", "id"),
            ("lowes_order_items", "id"),
        ):
            rows = connection.execute(
                f"SELECT * FROM {table} ORDER BY {order}"
            ).fetchall()
            snapshot[table] = [dict(row) for row in rows]
        return snapshot


# ---------------------------------------------------------------------------
# catalog reads
# ---------------------------------------------------------------------------


def _product_public(row: sqlite3.Row) -> dict[str, Any]:
    return {
        "id": int(row["id"]),
        "slug": str(row["slug"]),
        "title": str(row["title"]),
        "brand": str(row["brand"]),
        "category_id": str(row["category_id"]),
        "price_cents": int(row["price_cents"]),
        "was_cents": int(row["was_cents"]) if row["was_cents"] is not None else None,
        "rating": float(row["rating"]),
        "review_count": int(row["review_count"]),
        "badge": row["badge"],
        "model_number": str(row["model_number"]),
        "keywords": str(row["keywords"]),
        "stock": int(row["stock"]),
        "pickup_today": bool(row["pickup_today"]),
        "free_delivery": bool(row["free_delivery"]),
        "delivery_days": int(row["delivery_days"]),
        "specs": json.loads(row["specs_json"]),
        "summary": str(row["summary"]),
        "url": f"/pd/{row['slug']}/{int(row['id'])}",
    }


def categories() -> list[dict[str, Any]]:
    with closing(connect()) as connection:
        return [
            dict(row)
            for row in connection.execute(
                "SELECT * FROM lowes_categories ORDER BY position, id"
            )
        ]


def stores() -> list[dict[str, Any]]:
    with closing(connect()) as connection:
        return [
            dict(row)
            for row in connection.execute(
                "SELECT * FROM lowes_stores ORDER BY position, id"
            )
        ]


def get_store(store_id: str | None) -> dict[str, Any] | None:
    if not store_id:
        return None
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT * FROM lowes_stores WHERE id = ?", (store_id,)
        ).fetchone()
        return dict(row) if row is not None else None


def all_products() -> list[dict[str, Any]]:
    with closing(connect()) as connection:
        return [
            _product_public(row)
            for row in connection.execute("SELECT * FROM lowes_products ORDER BY id")
        ]


def get_product(product_id: int) -> dict[str, Any] | None:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT * FROM lowes_products WHERE id = ?", (product_id,)
        ).fetchone()
        return _product_public(row) if row is not None else None


def products_by_ids(product_ids: Sequence[int]) -> list[dict[str, Any]]:
    if not product_ids:
        return []
    placeholders = ",".join("?" for _ in product_ids)
    with closing(connect()) as connection:
        rows = connection.execute(
            f"SELECT * FROM lowes_products WHERE id IN ({placeholders})",
            tuple(product_ids),
        ).fetchall()
    by_id = {int(row["id"]): _product_public(row) for row in rows}
    return [by_id[pid] for pid in product_ids if pid in by_id]


def brands() -> list[str]:
    with closing(connect()) as connection:
        return [
            str(row[0])
            for row in connection.execute(
                "SELECT DISTINCT brand FROM lowes_products ORDER BY brand"
            )
        ]


# ---------------------------------------------------------------------------
# search
# ---------------------------------------------------------------------------

_TOKEN_RE = re.compile(r"[a-z0-9]+")


def _tokens(text: str) -> list[str]:
    return _TOKEN_RE.findall(text.casefold())


def _relevance(product: Mapping[str, Any], category_label: str, tokens: Sequence[str]) -> int:
    if not tokens:
        return 0
    title = product["title"].casefold()
    brand = product["brand"].casefold()
    keywords = product["keywords"].casefold()
    category = category_label.casefold()
    score = 0
    for token in tokens:
        hit = 0
        if token in title:
            hit += 6
            if title.startswith(token):
                hit += 3
        if token in brand:
            hit += 4
        if token in keywords:
            hit += 3
        if token in category:
            hit += 2
        if token in product["model_number"].casefold():
            hit += 2
        if hit == 0:
            return 0  # every token must match somewhere
        score += hit
    return score


def search(
    *,
    query: str = "",
    category_ids: Sequence[str] = (),
    brand_names: Sequence[str] = (),
    min_price_cents: int | None = None,
    max_price_cents: int | None = None,
    min_rating: float | None = None,
    pickup_today: bool = False,
    free_delivery: bool = False,
    sort: str = "relevance",
    page: int = 1,
    page_size: int = PAGE_SIZE,
) -> dict[str, Any]:
    """Server-side search: token filter, facet filters, sort, then paginate.

    The catalog is small and frozen, so ranking runs in Python over the rows
    SQLite already narrowed. Ordering is fully deterministic: every comparison
    ends with the product id so ties never depend on row order.
    """

    if sort not in SORT_IDS:
        sort = "relevance"
    page_size = max(1, min(48, int(page_size)))

    clauses: list[str] = []
    parameters: list[Any] = []
    if category_ids:
        clauses.append(
            "category_id IN (" + ",".join("?" for _ in category_ids) + ")"
        )
        parameters.extend(category_ids)
    if brand_names:
        clauses.append("brand IN (" + ",".join("?" for _ in brand_names) + ")")
        parameters.extend(brand_names)
    if min_price_cents is not None:
        clauses.append("price_cents >= ?")
        parameters.append(int(min_price_cents))
    if max_price_cents is not None:
        clauses.append("price_cents <= ?")
        parameters.append(int(max_price_cents))
    if min_rating is not None:
        clauses.append("rating >= ?")
        parameters.append(float(min_rating))
    if pickup_today:
        clauses.append("pickup_today = 1")
    if free_delivery:
        clauses.append("free_delivery = 1")
    where = (" WHERE " + " AND ".join(clauses)) if clauses else ""

    with closing(connect()) as connection:
        rows = connection.execute(
            f"SELECT * FROM lowes_products{where} ORDER BY id", tuple(parameters)
        ).fetchall()
        labels = {
            str(row["id"]): str(row["label"])
            for row in connection.execute("SELECT id, label FROM lowes_categories")
        }

    tokens = _tokens(query)
    scored: list[tuple[int, dict[str, Any]]] = []
    for row in rows:
        product = _product_public(row)
        score = _relevance(product, labels.get(product["category_id"], ""), tokens)
        if tokens and score == 0:
            continue
        scored.append((score, product))

    if sort == "price-low":
        scored.sort(key=lambda item: (item[1]["price_cents"], item[1]["id"]))
    elif sort == "price-high":
        scored.sort(key=lambda item: (-item[1]["price_cents"], item[1]["id"]))
    elif sort == "rating":
        scored.sort(
            key=lambda item: (-item[1]["rating"], -item[1]["review_count"], item[1]["id"])
        )
    elif sort == "top-sellers":
        scored.sort(key=lambda item: (-item[1]["review_count"], item[1]["id"]))
    elif sort == "savings":
        scored.sort(
            key=lambda item: (
                -((item[1]["was_cents"] or item[1]["price_cents"]) - item[1]["price_cents"]),
                item[1]["id"],
            )
        )
    else:
        scored.sort(key=lambda item: (-item[0], -item[1]["review_count"], item[1]["id"]))

    total = len(scored)
    page_count = max(1, (total + page_size - 1) // page_size)
    page = max(1, min(int(page), page_count))
    start = (page - 1) * page_size
    window = [product for _, product in scored[start : start + page_size]]

    facet_categories: dict[str, int] = {}
    facet_brands: dict[str, int] = {}
    for _, product in scored:
        facet_categories[product["category_id"]] = (
            facet_categories.get(product["category_id"], 0) + 1
        )
        facet_brands[product["brand"]] = facet_brands.get(product["brand"], 0) + 1

    return {
        "query": query,
        "total": total,
        "page": page,
        "page_size": page_size,
        "page_count": page_count,
        "first_index": start + 1 if total else 0,
        "last_index": min(start + page_size, total),
        "sort": sort,
        "products": window,
        "facet_categories": facet_categories,
        "facet_brands": facet_brands,
    }


def suggest(query: str, *, limit: int = 8) -> dict[str, Any]:
    """Autocomplete groups: matching products, then matching categories."""

    text = query.strip()
    if len(text) < 2:
        return {"query": text, "groups": []}
    tokens = _tokens(text)
    with closing(connect()) as connection:
        rows = connection.execute("SELECT * FROM lowes_products ORDER BY id").fetchall()
        category_rows = connection.execute(
            "SELECT * FROM lowes_categories ORDER BY position, id"
        ).fetchall()
    labels = {str(row["id"]): str(row["label"]) for row in category_rows}

    ranked: list[tuple[int, dict[str, Any]]] = []
    for row in rows:
        product = _product_public(row)
        score = _relevance(product, labels.get(product["category_id"], ""), tokens)
        if score:
            ranked.append((score, product))
    ranked.sort(key=lambda item: (-item[0], -item[1]["review_count"], item[1]["id"]))

    product_items = [
        {
            "label": product["title"],
            "href": product["url"],
            "kind": "product",
            "price_cents": product["price_cents"],
        }
        for _, product in ranked[:limit]
    ]
    category_items = [
        {
            "label": str(row["label"]),
            "href": f"/search?category={row['id']}",
            "kind": "category",
        }
        for row in category_rows
        if any(token in str(row["label"]).casefold() for token in tokens)
    ][:4]

    keyword_items = [
        {"label": term, "href": f"/search?q={term.replace(' ', '+')}", "kind": "keyword"}
        for term in seed_data.RECOMMENDED_SEARCHES
        if any(token in term.casefold() for token in tokens)
    ][:4]

    groups = []
    if keyword_items:
        groups.append({"label": "Suggested searches", "items": keyword_items})
    if product_items:
        groups.append({"label": "Products", "items": product_items})
    if category_items:
        groups.append({"label": "Departments", "items": category_items})
    return {"query": text, "groups": groups}


# ---------------------------------------------------------------------------
# cart
# ---------------------------------------------------------------------------


def owner_token(session_digest: str) -> str:
    """Payment owner identity derived from the server-side session digest."""

    return f"session:{session_digest}"


def _cart_rows(connection: sqlite3.Connection, owner_digest: str) -> list[sqlite3.Row]:
    return connection.execute(
        "SELECT c.*, p.slug, p.title, p.brand, p.category_id, p.rating,"
        "       p.review_count, p.free_delivery, p.delivery_days, p.stock,"
        "       p.pickup_today AS product_pickup_today"
        " FROM lowes_cart_items AS c"
        " JOIN lowes_products AS p ON p.id = c.product_id"
        " WHERE c.owner_digest = ?"
        " ORDER BY c.id",
        (owner_digest,),
    ).fetchall()


def _cart_public(rows: Iterable[sqlite3.Row]) -> dict[str, Any]:
    items: list[dict[str, Any]] = []
    subtotal = 0
    savings = 0
    units = 0
    needs_delivery = False
    all_free_delivery = True
    for row in rows:
        quantity = int(row["quantity"])
        unit = int(row["unit_price_cents"])
        line_total = unit * quantity
        was = int(row["unit_was_cents"]) if row["unit_was_cents"] is not None else None
        subtotal += line_total
        units += quantity
        if was is not None:
            savings += (was - unit) * quantity
        if str(row["fulfillment"]) == "delivery":
            needs_delivery = True
            if not int(row["free_delivery"]):
                all_free_delivery = False
        items.append(
            {
                "item_id": int(row["id"]),
                "product_id": int(row["product_id"]),
                "slug": str(row["slug"]),
                "title": str(row["title"]),
                "brand": str(row["brand"]),
                "quantity": quantity,
                "fulfillment": str(row["fulfillment"]),
                "store_id": row["store_id"],
                "unit_price_cents": unit,
                "unit_was_cents": was,
                "line_total_cents": line_total,
                "delivery_days": int(row["delivery_days"]),
                "free_delivery": bool(row["free_delivery"]),
                "url": f"/pd/{row['slug']}/{int(row['product_id'])}",
            }
        )
    return {
        "items": items,
        "count": len(items),
        "units": units,
        "subtotal_cents": subtotal,
        "savings_cents": savings,
        "needs_delivery": needs_delivery,
        "all_free_delivery": all_free_delivery,
    }


def get_cart(owner_digest: str) -> dict[str, Any]:
    with closing(connect()) as connection:
        return _cart_public(_cart_rows(connection, owner_digest))


def cart_units(owner_digest: str) -> int:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT COALESCE(SUM(quantity), 0) FROM lowes_cart_items"
            " WHERE owner_digest = ?",
            (owner_digest,),
        ).fetchone()
    return int(row[0])


def add_to_cart(
    owner_digest: str,
    *,
    product_id: int,
    quantity: int = 1,
    fulfillment: str = "pickup",
    store_id: str | None = None,
) -> dict[str, Any]:
    if fulfillment not in FULFILLMENTS:
        raise CheckoutError({"fulfillment": "Choose store pickup or delivery."})
    quantity = max(1, min(MAX_LINE_QUANTITY, int(quantity)))
    with closing(connect()) as connection, transaction(connection):
        product = connection.execute(
            "SELECT * FROM lowes_products WHERE id = ?", (product_id,)
        ).fetchone()
        if product is None:
            raise CheckoutError({"product": "That product is not in this catalog."})
        if fulfillment == "pickup" and not int(product["pickup_today"]):
            raise CheckoutError(
                {"fulfillment": "This item is not available for store pickup."}
            )
        resolved_store = store_id if fulfillment == "pickup" else None
        if resolved_store is None and fulfillment == "pickup":
            resolved_store = seed_data.DEFAULT_STORE_ID
        existing = connection.execute(
            "SELECT id, quantity FROM lowes_cart_items"
            " WHERE owner_digest = ? AND product_id = ? AND fulfillment = ?",
            (owner_digest, product_id, fulfillment),
        ).fetchone()
        if existing is None:
            connection.execute(
                "INSERT INTO lowes_cart_items"
                " (owner_digest, product_id, quantity, fulfillment, store_id,"
                "  unit_price_cents, unit_was_cents, created_at, updated_at)"
                " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
                (
                    owner_digest,
                    product_id,
                    quantity,
                    fulfillment,
                    resolved_store,
                    int(product["price_cents"]),
                    product["was_cents"],
                    FROZEN_CLOCK_UTC,
                    FROZEN_CLOCK_UTC,
                ),
            )
        else:
            merged = min(MAX_LINE_QUANTITY, int(existing["quantity"]) + quantity)
            connection.execute(
                "UPDATE lowes_cart_items SET quantity = ?, updated_at = ?"
                " WHERE id = ?",
                (merged, FROZEN_CLOCK_UTC, int(existing["id"])),
            )
        rows = _cart_rows(connection, owner_digest)
    return _cart_public(rows)


def update_cart_item(
    owner_digest: str, *, item_id: int, quantity: int
) -> dict[str, Any]:
    quantity = int(quantity)
    with closing(connect()) as connection, transaction(connection):
        owned = connection.execute(
            "SELECT id FROM lowes_cart_items WHERE id = ? AND owner_digest = ?",
            (item_id, owner_digest),
        ).fetchone()
        if owned is None:
            raise CheckoutError({"item": "That cart line is not yours."})
        if quantity <= 0:
            connection.execute("DELETE FROM lowes_cart_items WHERE id = ?", (item_id,))
        else:
            connection.execute(
                "UPDATE lowes_cart_items SET quantity = ?, updated_at = ? WHERE id = ?",
                (min(MAX_LINE_QUANTITY, quantity), FROZEN_CLOCK_UTC, item_id),
            )
        rows = _cart_rows(connection, owner_digest)
    return _cart_public(rows)


def set_cart_item_fulfillment(
    owner_digest: str, *, item_id: int, fulfillment: str, store_id: str | None = None
) -> dict[str, Any]:
    if fulfillment not in FULFILLMENTS:
        raise CheckoutError({"fulfillment": "Choose store pickup or delivery."})
    with closing(connect()) as connection, transaction(connection):
        line = connection.execute(
            "SELECT c.*, p.pickup_today FROM lowes_cart_items AS c"
            " JOIN lowes_products AS p ON p.id = c.product_id"
            " WHERE c.id = ? AND c.owner_digest = ?",
            (item_id, owner_digest),
        ).fetchone()
        if line is None:
            raise CheckoutError({"item": "That cart line is not yours."})
        if fulfillment == "pickup" and not int(line["pickup_today"]):
            raise CheckoutError(
                {"fulfillment": "This item is not available for store pickup."}
            )
        duplicate = connection.execute(
            "SELECT id, quantity FROM lowes_cart_items"
            " WHERE owner_digest = ? AND product_id = ? AND fulfillment = ? AND id <> ?",
            (owner_digest, int(line["product_id"]), fulfillment, item_id),
        ).fetchone()
        resolved_store = (
            (store_id or str(line["store_id"] or seed_data.DEFAULT_STORE_ID))
            if fulfillment == "pickup"
            else None
        )
        if duplicate is not None:
            merged = min(
                MAX_LINE_QUANTITY, int(duplicate["quantity"]) + int(line["quantity"])
            )
            connection.execute(
                "UPDATE lowes_cart_items SET quantity = ?, updated_at = ? WHERE id = ?",
                (merged, FROZEN_CLOCK_UTC, int(duplicate["id"])),
            )
            connection.execute("DELETE FROM lowes_cart_items WHERE id = ?", (item_id,))
        else:
            connection.execute(
                "UPDATE lowes_cart_items SET fulfillment = ?, store_id = ?,"
                " updated_at = ? WHERE id = ?",
                (fulfillment, resolved_store, FROZEN_CLOCK_UTC, item_id),
            )
        rows = _cart_rows(connection, owner_digest)
    return _cart_public(rows)


def remove_cart_item(owner_digest: str, *, item_id: int) -> dict[str, Any]:
    return update_cart_item(owner_digest, item_id=item_id, quantity=0)


def clear_cart(owner_digest: str) -> None:
    with closing(connect()) as connection, transaction(connection):
        connection.execute(
            "DELETE FROM lowes_cart_items WHERE owner_digest = ?", (owner_digest,)
        )


def migrate_owner(
    connection: sqlite3.Connection, old_digest: str, new_digest: str
) -> None:
    """Move an anonymous cart onto the rotated authenticated session.

    Registered as ``session_rotation_callback`` so the move happens inside the
    same auth transaction that revokes the old session and creates the new one.
    """

    if old_digest == new_digest:
        return
    for row in connection.execute(
        "SELECT id, product_id, quantity, fulfillment FROM lowes_cart_items"
        " WHERE owner_digest = ? ORDER BY id",
        (old_digest,),
    ).fetchall():
        duplicate = connection.execute(
            "SELECT id, quantity FROM lowes_cart_items"
            " WHERE owner_digest = ? AND product_id = ? AND fulfillment = ?",
            (new_digest, int(row["product_id"]), str(row["fulfillment"])),
        ).fetchone()
        if duplicate is None:
            connection.execute(
                "UPDATE lowes_cart_items SET owner_digest = ?, updated_at = ?"
                " WHERE id = ?",
                (new_digest, FROZEN_CLOCK_UTC, int(row["id"])),
            )
        else:
            merged = min(
                MAX_LINE_QUANTITY, int(duplicate["quantity"]) + int(row["quantity"])
            )
            connection.execute(
                "UPDATE lowes_cart_items SET quantity = ?, updated_at = ? WHERE id = ?",
                (merged, FROZEN_CLOCK_UTC, int(duplicate["id"])),
            )
            connection.execute(
                "DELETE FROM lowes_cart_items WHERE id = ?", (int(row["id"]),)
            )


# ---------------------------------------------------------------------------
# pricing
# ---------------------------------------------------------------------------


def _round_half_up(value: float) -> int:
    return int(value + 0.5)


def price_cart(
    cart: Mapping[str, Any], *, fulfillment: str, state: str | None
) -> dict[str, Any]:
    subtotal = int(cart["subtotal_cents"])
    if fulfillment == "pickup":
        delivery = 0
    elif subtotal >= FREE_DELIVERY_THRESHOLD_CENTS and cart["all_free_delivery"]:
        delivery = 0
    elif cart["all_free_delivery"]:
        delivery = STANDARD_DELIVERY_CENTS
    else:
        delivery = BULKY_DELIVERY_CENTS
    basis = TAX_BASIS_POINTS.get((state or "").upper(), DEFAULT_TAX_BASIS_POINTS)
    tax = _round_half_up((subtotal + delivery) * basis / 10000)
    return {
        "subtotal_cents": subtotal,
        "savings_cents": int(cart["savings_cents"]),
        "delivery_cents": delivery,
        "tax_cents": tax,
        "tax_basis_points": basis,
        "total_cents": subtotal + delivery + tax,
        "currency": CURRENCY,
    }


def _fingerprint(payload: Mapping[str, Any]) -> str:
    canonical = json.dumps(
        payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")
    )
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def _order_number(row_id: int) -> str:
    return f"LWS-{700000 + row_id}"


# ---------------------------------------------------------------------------
# checkout validation
# ---------------------------------------------------------------------------

_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$")
_ZIP_RE = re.compile(r"^\d{5}$")
_NAME_RE = re.compile(r"^[A-Za-z][A-Za-z .'-]{0,59}$")


def _clean(value: Any, limit: int = 120) -> str:
    return " ".join(str(value).split())[:limit] if isinstance(value, str) else ""


def validate_checkout(
    form: Mapping[str, Any], *, cart: Mapping[str, Any], scenario_ids: Sequence[str]
) -> dict[str, Any]:
    reject_payment_keys(form)
    errors: dict[str, str] = {}
    fulfillment = _clean(form.get("fulfillment"), 20) or "pickup"
    if fulfillment not in FULFILLMENTS:
        errors["fulfillment"] = "Choose store pickup or delivery."
        fulfillment = "pickup"

    first_name = _clean(form.get("first_name"), 60)
    last_name = _clean(form.get("last_name"), 60)
    email = _clean(form.get("email"), 200).casefold()
    if not _NAME_RE.match(first_name):
        errors["first_name"] = "Enter a first name."
    if not _NAME_RE.match(last_name):
        errors["last_name"] = "Enter a last name."
    if not _EMAIL_RE.match(email):
        errors["email"] = "Enter a valid email address."

    address: dict[str, str] | None = None
    store_id: str | None = None
    state: str | None = None
    if fulfillment == "delivery":
        address_1 = _clean(form.get("address_1"), 120)
        address_2 = _clean(form.get("address_2"), 120)
        city = _clean(form.get("city"), 80)
        state = _clean(form.get("state"), 2).upper()
        postal = _clean(form.get("zip"), 10)
        if len(address_1) < 4:
            errors["address_1"] = "Enter a street address."
        if len(city) < 2:
            errors["city"] = "Enter a city."
        if state not in US_STATES:
            errors["state"] = "Enter a two-letter US state code."
        if not _ZIP_RE.match(postal):
            errors["zip"] = "Enter a five-digit ZIP code."
        address = {
            "address_1": address_1,
            "address_2": address_2,
            "city": city,
            "state": state,
            "zip": postal,
        }
    else:
        store_id = _clean(form.get("store_id"), 40) or seed_data.DEFAULT_STORE_ID
        known = {store["id"] for store in stores()}
        if store_id not in known:
            errors["store_id"] = "Choose a store for pickup."
        state = next(
            (store["state"] for store in stores() if store["id"] == store_id), None
        )

    scenario_id = _clean(form.get("scenario_id"), 80)
    if scenario_id not in set(scenario_ids):
        errors["scenario_id"] = "Choose a local sandbox payment scenario."

    if not cart["items"]:
        errors["cart"] = "Your cart is empty."
    if fulfillment == "delivery" and not cart["items"]:
        errors.setdefault("cart", "Your cart is empty.")

    if errors:
        raise CheckoutError(errors)
    return {
        "fulfillment": fulfillment,
        "first_name": first_name,
        "last_name": last_name,
        "customer_name": f"{first_name} {last_name}",
        "email": email,
        "address": address,
        "store_id": store_id,
        "state": state,
        "scenario_id": scenario_id,
    }


# ---------------------------------------------------------------------------
# checkout
# ---------------------------------------------------------------------------


def place_order(
    owner_digest: str,
    checkout: Mapping[str, Any],
    *,
    account_id: str | None = None,
) -> dict[str, Any]:
    """Run one payment attempt and, on approval, persist the order atomically.

    The payment approval is consumed inside the same SQLite transaction that
    writes the order snapshot and empties the cart, so no approval can be
    replayed against a second order and no order can exist without a consumed
    approval.
    """

    backend, _auth = services()
    cart = get_cart(owner_digest)
    if not cart["items"]:
        raise CheckoutError({"cart": "Your cart is empty."})

    fulfillment = str(checkout["fulfillment"])
    totals = price_cart(cart, fulfillment=fulfillment, state=checkout.get("state"))
    owner = owner_token(owner_digest)
    snapshot = {
        "site_id": SITE_ID,
        "fulfillment": fulfillment,
        "store_id": checkout.get("store_id"),
        "state": checkout.get("state"),
        "email": checkout["email"],
        "lines": [
            {
                "product_id": item["product_id"],
                "quantity": item["quantity"],
                "unit_price_cents": item["unit_price_cents"],
                "fulfillment": item["fulfillment"],
            }
            for item in cart["items"]
        ],
        "subtotal_cents": totals["subtotal_cents"],
        "delivery_cents": totals["delivery_cents"],
        "tax_cents": totals["tax_cents"],
        "total_cents": totals["total_cents"],
        "currency": CURRENCY,
    }
    fingerprint = _fingerprint(snapshot)
    scenario_id = str(checkout["scenario_id"])

    with closing(connect()) as connection:
        connection.execute("BEGIN IMMEDIATE")
        try:
            existing = connection.execute(
                "SELECT * FROM lowes_orders WHERE owner_digest = ? AND fingerprint = ?",
                (owner_digest, fingerprint),
            ).fetchone()
            if existing is not None:
                connection.execute("COMMIT")
                return {
                    "placed": True,
                    "already": True,
                    "order": get_order(str(existing["order_number"])),
                }

            flow = backend.payments.create_intent(
                owner=owner,
                amount_minor=totals["total_cents"],
                currency=CURRENCY,
                fingerprint=fingerprint,
                idempotency_key=f"lowes.flow:{fingerprint[:40]}",
                connection=connection,
            )
            attempt = backend.payments.attempt(
                flow_id=flow["flow_id"],
                owner=owner,
                amount_minor=totals["total_cents"],
                currency=CURRENCY,
                fingerprint=fingerprint,
                scenario_id=scenario_id,
                idempotency_key=f"lowes.attempt:{fingerprint[:32]}:{scenario_id}",
                connection=connection,
            )
            if attempt["status"] != "APPROVED":
                connection.execute("COMMIT")
                return {
                    "placed": False,
                    "already": False,
                    "payment": _payment_public(flow, attempt),
                    "totals": totals,
                }

            consumed = backend.payments.consume_approval(
                connection,
                flow_id=flow["flow_id"],
                owner=owner,
                amount_minor=totals["total_cents"],
                currency=CURRENCY,
                fingerprint=fingerprint,
            )
            cursor = connection.execute(
                "INSERT INTO lowes_orders"
                " (order_number, owner_digest, account_id, email, customer_name,"
                "  fulfillment, store_id, address_json, subtotal_cents,"
                "  savings_cents, delivery_cents, tax_cents, total_cents, currency,"
                "  fingerprint, payment_flow_id, payment_attempt_id, scenario_id,"
                "  status, created_at)"
                " VALUES ('', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,"
                "         'placed', ?)",
                (
                    owner_digest,
                    account_id,
                    checkout["email"],
                    checkout["customer_name"],
                    fulfillment,
                    checkout.get("store_id"),
                    json.dumps(checkout.get("address"), sort_keys=True)
                    if checkout.get("address")
                    else None,
                    totals["subtotal_cents"],
                    totals["savings_cents"],
                    totals["delivery_cents"],
                    totals["tax_cents"],
                    totals["total_cents"],
                    CURRENCY,
                    fingerprint,
                    flow["flow_id"],
                    consumed["attempt_id"],
                    scenario_id,
                    FROZEN_CLOCK_UTC,
                ),
            )
            order_id = int(cursor.lastrowid)
            order_number = _order_number(order_id)
            connection.execute(
                "UPDATE lowes_orders SET order_number = ? WHERE id = ?",
                (order_number, order_id),
            )
            for item in cart["items"]:
                connection.execute(
                    "INSERT INTO lowes_order_items"
                    " (order_id, product_id, title, brand, slug, quantity,"
                    "  unit_price_cents, line_total_cents, fulfillment)"
                    " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
                    (
                        order_id,
                        item["product_id"],
                        item["title"],
                        item["brand"],
                        item["slug"],
                        item["quantity"],
                        item["unit_price_cents"],
                        item["line_total_cents"],
                        item["fulfillment"],
                    ),
                )
            connection.execute(
                "DELETE FROM lowes_cart_items WHERE owner_digest = ?", (owner_digest,)
            )
            mail = backend.mail.enqueue(
                "order-confirmation",
                checkout["email"],
                {
                    "order_number": order_number,
                    "customer_name": checkout["customer_name"],
                    "total_display": money(totals["total_cents"]),
                    "currency": CURRENCY,
                    "fulfillment_summary": _fulfillment_summary(checkout),
                    "hold_days": str(PICKUP_HOLD_DAYS),
                },
                idempotency_key=f"lowes.mail:{order_number}",
                simulation=True,
                connection=connection,
            )
            connection.execute(
                "UPDATE lowes_orders SET mail_id = ? WHERE id = ?",
                (mail["mail_id"], order_id),
            )
            connection.execute("COMMIT")
        except Exception:
            if connection.in_transaction:
                connection.execute("ROLLBACK")
            raise
    return {"placed": True, "already": False, "order": get_order(order_number)}


def _fulfillment_summary(checkout: Mapping[str, Any]) -> str:
    if checkout["fulfillment"] == "pickup":
        store = get_store(checkout.get("store_id"))
        return f"store pickup at {store['name']}" if store else "store pickup"
    address = checkout.get("address") or {}
    return f"delivery to {address.get('city', '')} {address.get('state', '')}".strip()


def _payment_public(flow: Mapping[str, Any], attempt: Mapping[str, Any]) -> dict[str, Any]:
    return {
        "flow_id": flow["flow_id"],
        "attempt_id": attempt["attempt_id"],
        "status": attempt["status"],
        "scenario_id": attempt["scenario_id"],
        "amount_minor": int(attempt["amount_minor"]),
        "currency": attempt["currency"],
        "is_simulation": True,
    }


def get_order(order_number: str) -> dict[str, Any] | None:
    with closing(connect()) as connection:
        row = connection.execute(
            "SELECT * FROM lowes_orders WHERE order_number = ?", (order_number,)
        ).fetchone()
        if row is None:
            return None
        items = connection.execute(
            "SELECT * FROM lowes_order_items WHERE order_id = ? ORDER BY id",
            (int(row["id"]),),
        ).fetchall()
        mail = None
        if row["mail_id"]:
            mail_row = connection.execute(
                "SELECT mail_id, purpose, status, is_simulation"
                " FROM websitebench_mail_jobs WHERE mail_id = ?",
                (row["mail_id"],),
            ).fetchone()
            mail = dict(mail_row) if mail_row is not None else None
        flow = connection.execute(
            "SELECT status FROM websitebench_payment_flows WHERE flow_id = ?",
            (row["payment_flow_id"],),
        ).fetchone()
    order = dict(row)
    order["address"] = json.loads(order["address_json"]) if order["address_json"] else None
    order["items"] = [dict(item) for item in items]
    order["mail"] = mail
    order["payment_status"] = str(flow["status"]) if flow is not None else None
    order["store"] = get_store(order["store_id"])
    return order


def orders_for_owner(owner_digest: str, account_id: str | None = None) -> list[dict[str, Any]]:
    with closing(connect()) as connection:
        if account_id:
            rows = connection.execute(
                "SELECT order_number FROM lowes_orders"
                " WHERE owner_digest = ? OR account_id = ? ORDER BY id DESC",
                (owner_digest, account_id),
            ).fetchall()
        else:
            rows = connection.execute(
                "SELECT order_number FROM lowes_orders"
                " WHERE owner_digest = ? ORDER BY id DESC",
                (owner_digest,),
            ).fetchall()
    return [order for order in (get_order(str(row[0])) for row in rows) if order]


def payment_scenarios() -> list[dict[str, str]]:
    backend, _auth = services()
    return [dict(item) for item in backend.config.payments["local_sandbox"]["scenarios"]]


# ---------------------------------------------------------------------------
# formatting helpers shared with the view layer
# ---------------------------------------------------------------------------


def money(cents: int) -> str:
    return f"{cents // 100:,}.{cents % 100:02d}"


def money_parts(cents: int) -> tuple[str, str]:
    return f"{cents // 100:,}", f"{cents % 100:02d}"