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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
"""Stateful, source-grounded, fully local H Mart grocery clone."""

from __future__ import annotations

import json
import os
import re
import secrets
import sqlite3
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles

from backend.hmart_schema import move_owner_state, owner_key
from backend.site_backend_integration import open_site_services
from websitebench.local_clone_auth.store import AuthError
from hmart_mail import configuration as mail_configuration, deliver as deliver_mail, MailUnavailable

SITE_ID = "hmart"
DISPLAY_NAME = "H Mart"
ROOT = Path(__file__).resolve().parent
STATIC = ROOT / "static"
MAIL_WORKER = secrets.token_urlsafe(32)
BACKEND, AUTH = open_site_services(mail_worker_token=MAIL_WORKER)
AUTH.seed_account(
    subject_id="customer-demo",
    email="demo@hmart.local",
    display_name="Mina Park",
    password="Hmart123!",
)
COOKIE = BACKEND.session_cookie

app = FastAPI(title=DISPLAY_NAME)
app.mount("/static", StaticFiles(directory=STATIC), name="static")

ZIP_LOCATIONS = {
    "0": "nj-edison",
    "1": "nyc-ktown",
    "7": "tx-plano",
    "9": "ca-san-jose",
}


def _now() -> str:
    return datetime.now(UTC).isoformat().replace("+00:00", "Z")


def _text(value: Any, name: str, minimum: int = 1, maximum: int = 240) -> str:
    if not isinstance(value, str):
        raise HTTPException(422, f"{name} is required")
    normalized = " ".join(value.split())
    if not minimum <= len(normalized) <= maximum:
        raise HTTPException(422, f"{name} must contain {minimum} to {maximum} characters")
    return normalized


def _cookie(response: Any, token: str) -> None:
    response.set_cookie(
        key=COOKIE["name"],
        value=token,
        path="/",
        httponly=bool(COOKIE["httponly"]),
        secure=bool(COOKIE["secure"]),
        samesite=str(COOKIE["samesite"]).lower(),
        max_age=30 * 24 * 60 * 60,
    )


@app.middleware("http")
async def session_middleware(request: Request, call_next: Any) -> Any:
    if request.url.path.startswith("/static/") or request.url.path == "/healthz":
        return await call_next(request)
    supplied = request.cookies.get(COOKIE["name"])
    token, session = AUTH.ensure_session(supplied)
    request.state.session_token = token
    request.state.session = session
    response = await call_next(request)
    replacement = getattr(request.state, "replacement_session_token", token)
    if replacement != supplied:
        _cookie(response, replacement)
    return response


def _session(request: Request) -> tuple[str, dict[str, Any]]:
    return request.state.session_token, request.state.session


def _owner(request: Request) -> str:
    token, session = _session(request)
    account = session.get("account")
    if account:
        return owner_key("account", account["subject_id"])
    return owner_key("session", AUTH.session_owner_digest(token))


def _require_account(request: Request) -> tuple[str, dict[str, Any]]:
    _, session = _session(request)
    account = session.get("account")
    if not account:
        raise HTTPException(401, "Sign in to use this account feature")
    return owner_key("account", account["subject_id"]), account


def _ensure_state(connection: sqlite3.Connection, owner: str) -> sqlite3.Row:
    connection.execute("INSERT OR IGNORE INTO hmart_session_state(owner) VALUES(?)", (owner,))
    return connection.execute(
        "SELECT * FROM hmart_session_state WHERE owner=?", (owner,)
    ).fetchone()


def _product(row: sqlite3.Row) -> dict[str, Any]:
    value = dict(row)
    if value["country"].startswith("{{"):
        value["country"] = ""
    value["image"] = value["image_path"]
    value["price"] = round(value["price_cents"] / 100, 2)
    value["list_price"] = round(value["list_price_cents"] / 100, 2)
    if "location_available" in row.keys():
        value["available"] = bool(value.pop("location_available"))
        value["availability_count"] = int(value.pop("location_availability_count"))
    else:
        value["available"] = bool(value["available"])
    return value


def _cart(connection: sqlite3.Connection, owner: str) -> dict[str, Any]:
    state = _ensure_state(connection, owner)
    rows = connection.execute(
        """SELECT c.quantity,c.substitution,p.*,
        COALESCE(li.available,0) AS location_available,
        COALESCE(li.availability_count,0) AS location_availability_count,
        v.variant_id AS selected_variant_id,v.label AS variant_label,
        v.unit_count AS variant_unit_count,v.price_cents AS variant_price_cents,
        v.list_price_cents AS variant_list_price_cents
        FROM hmart_cart c
        JOIN hmart_products p ON p.product_id=c.product_id
        LEFT JOIN hmart_product_locations li ON li.product_id=p.product_id
          AND li.location_id=?
        JOIN hmart_product_variants v ON v.variant_id=COALESCE(
          c.variant_id,(SELECT variant_id FROM hmart_product_variants
          WHERE product_id=p.product_id AND is_default=1)
        )
        WHERE c.owner=? ORDER BY p.name""",
        (state["location_id"], owner),
    ).fetchall()
    items: list[dict[str, Any]] = []
    subtotal = 0
    for row in rows:
        item = _product(row)
        item["quantity"] = int(row["quantity"])
        item["substitution"] = row["substitution"]
        item["variant_id"] = row["selected_variant_id"]
        item["variant_label"] = row["variant_label"]
        item["variant_unit_count"] = row["variant_unit_count"]
        item["price_cents"] = row["variant_price_cents"]
        item["list_price_cents"] = row["variant_list_price_cents"]
        item["price"] = round(row["variant_price_cents"] / 100, 2)
        item["list_price"] = round(row["variant_list_price_cents"] / 100, 2)
        item["line_total_cents"] = row["variant_price_cents"] * row["quantity"]
        item["available"] = bool(
            item["available"]
            and item["availability_count"]
            >= item["variant_unit_count"] * item["quantity"]
        )
        subtotal += item["line_total_cents"]
        items.append(item)
    coupon = None
    discount = 0
    if state["coupon_code"]:
        coupon = connection.execute(
            "SELECT * FROM hmart_coupons WHERE code=?", (state["coupon_code"],)
        ).fetchone()
        if coupon and coupon["state"] == "eligible" and subtotal >= coupon["minimum_cents"]:
            discount = min(subtotal, int(coupon["discount_cents"]))
    fee = {"pickup": 0, "delivery": 699, "shipping": 999}[state["fulfillment"]]
    return {
        "items": items,
        "item_count": sum(item["quantity"] for item in items),
        "subtotal_cents": subtotal,
        "discount_cents": discount,
        "fulfillment_fee_cents": fee,
        "total_cents": max(0, subtotal - discount + fee),
        "coupon": dict(coupon) if coupon else None,
        "fulfillment": {
            "method": state["fulfillment"],
            "slot": state["fulfillment_slot"],
        },
    }


def _rotation(connection: sqlite3.Connection, old_digest: str, new_digest: str) -> None:
    account = connection.execute(
        """SELECT a.subject_id FROM local_auth_sessions s
        JOIN local_auth_accounts a ON a.account_id=s.account_id
        WHERE s.session_digest=?""",
        (new_digest,),
    ).fetchone()
    new_owner = (
        owner_key("account", account["subject_id"])
        if account
        else owner_key("session", new_digest)
    )
    move_owner_state(connection, owner_key("session", old_digest), new_owner)


def _location_id_for_postal(postal_code: str) -> str | None:
    return ZIP_LOCATIONS.get(postal_code[0]) if postal_code else None


@app.get("/healthz")
def healthz() -> dict[str, object]:
    return {
        "ok": True,
        "site_id": SITE_ID,
        "database": BACKEND.lifecycle.health()["status"],
        "remote_runtime_requests": "forbidden",
    }


@app.get("/api/bootstrap")
def bootstrap(
    request: Request,
    query: str = "",
    category: str = "",
    brand: str = "",
    country: str = "",
    storage: str = "",
    on_sale: bool = False,
    sort: str = "best-sellers",
    offset: int = 0,
    limit: int = 30,
) -> dict[str, Any]:
    owner = _owner(request)
    limit, offset = max(1, min(limit, 240)), max(0, offset)
    clauses: list[str] = []
    params: list[Any] = []
    if query.strip():
        term = f"%{query.strip()[:80]}%"
        clauses.append("(p.name LIKE ? OR p.brand LIKE ? OR p.category LIKE ? OR p.description LIKE ?)")
        params.extend([term, term, term, term])
    if category.strip():
        clauses.append("p.category=?")
        params.append(category.strip()[:120])
    if brand.strip():
        clauses.append("p.brand=?")
        params.append(brand.strip()[:120])
    if country.strip():
        clauses.append("p.country=?")
        params.append(country.strip()[:80])
    if storage.strip():
        clauses.append("p.storage=?")
        params.append(storage.strip()[:80])
    if on_sale:
        clauses.append("p.list_price_cents > p.price_cents")
    where = f"WHERE {' AND '.join(clauses)}" if clauses else ""
    order = {
        "best-sellers": "location_available DESC, p.list_price_cents > p.price_cents DESC, p.rowid",
        "price-low": "p.price_cents, p.name",
        "price-high": "p.price_cents DESC, p.name",
        "name": "p.name",
        "newest": "p.rowid DESC",
    }.get(sort, "location_available DESC, p.rowid")
    with BACKEND.lifecycle.connection() as connection:
        state = dict(_ensure_state(connection, owner))
        total = connection.execute(
            f"SELECT COUNT(*) FROM hmart_products p {where}", params
        ).fetchone()[0]
        rows = connection.execute(
            f"""SELECT p.*,COALESCE(li.available,0) AS location_available,
            COALESCE(li.availability_count,0) AS location_availability_count
            FROM hmart_products p LEFT JOIN hmart_product_locations li
            ON li.product_id=p.product_id AND li.location_id=?
            {where} ORDER BY {order} LIMIT ? OFFSET ?""",
            [state["location_id"], *params, limit, offset],
        ).fetchall()
        state["address"] = json.loads(state["address_json"]) if state["address_json"] else None
        location = dict(connection.execute(
            "SELECT * FROM hmart_locations WHERE location_id=?", (state["location_id"],)
        ).fetchone())
        location["fulfillment"] = json.loads(location.pop("fulfillment_json"))
        location["slots"] = json.loads(location.pop("slots_json"))
        favorites = {
            row["product_id"] for row in connection.execute(
                "SELECT product_id FROM hmart_favorites WHERE owner=?", (owner,)
            )
        }
        return {
            "site_id": SITE_ID,
            "session": request.state.session,
            "demo_account": {"email": "demo@hmart.local", "password": "Hmart123!"},
            "state": state,
            "location": location,
            "locations": [
                {
                    **dict(row),
                    "fulfillment": json.loads(row["fulfillment_json"]),
                    "slots": json.loads(row["slots_json"]),
                }
                for row in connection.execute("SELECT * FROM hmart_locations")
            ],
            "categories": [dict(row) for row in connection.execute(
                """SELECT category,COUNT(*) AS count FROM hmart_products
                GROUP BY category ORDER BY count DESC,category LIMIT 24"""
            )],
            "brands": [dict(row) for row in connection.execute(
                """SELECT brand,COUNT(*) AS count FROM hmart_products WHERE brand <> ''
                GROUP BY brand ORDER BY count DESC,brand LIMIT 24"""
            )],
            "countries": [dict(row) for row in connection.execute(
                """SELECT country,COUNT(*) AS count FROM hmart_products
                WHERE country <> '' GROUP BY country ORDER BY count DESC,country"""
            )],
            "storage_options": [dict(row) for row in connection.execute(
                """SELECT storage,COUNT(*) AS count FROM hmart_products
                WHERE storage <> '' GROUP BY storage ORDER BY count DESC,storage"""
            )],
            "products": [_product(row) for row in rows],
            "product_total": total,
            "favorite_product_ids": sorted(favorites),
            "cart": _cart(connection, owner),
            "coupons": [dict(row) for row in connection.execute("SELECT * FROM hmart_coupons")],
        }


@app.get("/api/products/{slug}")
def product_detail(request: Request, slug: str) -> dict[str, Any]:
    owner = _owner(request)
    with BACKEND.lifecycle.connection() as connection:
        state = _ensure_state(connection, owner)
        row = connection.execute(
            """SELECT p.*,COALESCE(li.available,0) AS location_available,
            COALESCE(li.availability_count,0) AS location_availability_count
            FROM hmart_products p LEFT JOIN hmart_product_locations li
            ON li.product_id=p.product_id AND li.location_id=? WHERE p.slug=?""",
            (state["location_id"], slug),
        ).fetchone()
        if row is None:
            raise HTTPException(404, "Product not found")
        value = _product(row)
        value["in_favorites"] = connection.execute(
            "SELECT 1 FROM hmart_favorites WHERE owner=? AND product_id=?",
            (owner, row["product_id"]),
        ).fetchone() is not None
        value["reviews"] = [
            {"name": "Verified local shopper", "rating": 5, "title": "Pantry favorite",
             "body": "A deterministic review fixture used only by this offline clone."},
            {"name": "H Mart local sandbox", "rating": 4, "title": "Reliable staple",
             "body": "Review behavior stays local and repeatable."},
        ]
        value["variants"] = [
            {
                **dict(variant),
                "price": round(variant["price_cents"] / 100, 2),
                "list_price": round(variant["list_price_cents"] / 100, 2),
                "available": bool(value["available"])
                and value["availability_count"] >= variant["unit_count"],
            }
            for variant in connection.execute(
                """SELECT * FROM hmart_product_variants
                WHERE product_id=? ORDER BY is_default DESC,unit_count""",
                (row["product_id"],),
            )
        ]
        return value


@app.put("/api/location")
async def set_location(request: Request) -> dict[str, Any]:
    body, owner = await request.json(), _owner(request)
    postal = _text(body.get("postal_code"), "postal_code", 5, 10)
    if not re.fullmatch(r"[0-9]{5}(?:-[0-9]{4})?", postal):
        raise HTTPException(422, "Enter a valid US postal code")
    mode = body.get("fulfillment", "shipping")
    if mode not in {"shipping", "delivery", "pickup"}:
        raise HTTPException(422, "Unknown fulfillment option")
    location_id = _location_id_for_postal(postal)
    if location_id is None:
        raise HTTPException(
            422, "This ZIP code is outside the local demo service areas"
        )
    with BACKEND.lifecycle.connection(transaction=True) as connection:
        location = connection.execute(
            "SELECT * FROM hmart_locations WHERE location_id=?", (location_id,)
        ).fetchone()
        modes = json.loads(location["fulfillment_json"])
        if mode not in modes:
            raise HTTPException(422, "Fulfillment option is unavailable at this location")
        slots = json.loads(location["slots_json"])[mode]
        slot = body.get("slot") or slots[0]
        if slot not in slots:
            raise HTTPException(422, "Unknown fulfillment time slot")
        _ensure_state(connection, owner)
        connection.execute(
            """UPDATE hmart_session_state SET postal_code=?,location_id=?,fulfillment=?,
            fulfillment_slot=?,checkout_step='basket' WHERE owner=?""",
            (postal, location_id, mode, slot, owner),
        )
    return {
        "ok": True,
        "postal_code": postal,
        "location_id": location_id,
        "fulfillment": mode,
        "slot": slot,
    }


@app.post("/api/cart/{product_id}")
async def add_cart(request: Request, product_id: str) -> dict[str, Any]:
    body, owner = await request.json(), _owner(request)
    quantity = body.get("quantity", 1)
    if type(quantity) is not int or not 1 <= quantity <= 99:
        raise HTTPException(422, "Quantity must be 1 to 99")
    with BACKEND.lifecycle.connection(transaction=True) as connection:
        state = _ensure_state(connection, owner)
        product = connection.execute(
            """SELECT p.available,p.max_per_order,COALESCE(li.available,0) AS location_available,
            COALESCE(li.availability_count,0) AS location_availability_count
            FROM hmart_products p LEFT JOIN hmart_product_locations li
            ON li.product_id=p.product_id AND li.location_id=? WHERE p.product_id=?""",
            (state["location_id"], product_id),
        ).fetchone()
        if product is None:
            raise HTTPException(404, "Product not found")
        if not product["available"] or not product["location_available"]:
            raise HTTPException(409, "This item is unavailable at the selected location")
        if quantity > product["max_per_order"]:
            raise HTTPException(409, f"Maximum quantity is {product['max_per_order']}")
        variant_id = body.get("variant_id")
        if variant_id is None:
            variant = connection.execute(
                """SELECT * FROM hmart_product_variants
                WHERE product_id=? AND is_default=1""", (product_id,)
            ).fetchone()
        else:
            variant = connection.execute(
                """SELECT * FROM hmart_product_variants
                WHERE product_id=? AND variant_id=?""", (product_id, variant_id)
            ).fetchone()
        if variant is None:
            raise HTTPException(422, "Unknown product variant")
        available_quantity = product["location_availability_count"] // variant["unit_count"]
        existing = connection.execute(
            "SELECT quantity,variant_id FROM hmart_cart WHERE owner=? AND product_id=?",
            (owner, product_id),
        ).fetchone()
        if existing and existing["variant_id"] != variant["variant_id"]:
            raise HTTPException(409, "Your cart already has a different pack option. Remove it before adding this option.")
        resulting_quantity = quantity + (existing["quantity"] if existing else 0)
        if resulting_quantity > product["max_per_order"]:
            raise HTTPException(409, f"Maximum quantity is {product['max_per_order']}")
        if resulting_quantity > available_quantity:
            raise HTTPException(409, "This pack option is unavailable at the selected location")
        substitution = body.get("substitution", state["substitution_default"])
        if substitution not in {"best-match", "refund", "specific"}:
            raise HTTPException(422, "Unknown substitution preference")
        connection.execute(
            """INSERT INTO hmart_cart(owner,product_id,variant_id,quantity,substitution)
            VALUES(?,?,?,?,?) ON CONFLICT(owner,product_id) DO UPDATE SET
            quantity=MIN(?,hmart_cart.quantity+excluded.quantity),
            variant_id=excluded.variant_id,
            substitution=excluded.substitution""",
            (
                owner, product_id, variant["variant_id"], quantity, substitution,
                product["max_per_order"],
            ),
        )
        return _cart(connection, owner)


@app.patch("/api/cart/{product_id}")
async def update_cart(request: Request, product_id: str) -> dict[str, Any]:
    body, owner = await request.json(), _owner(request)
    quantity, substitution = body.get("quantity"), body.get("substitution")
    variant_id = body.get("variant_id")
    if quantity is not None and (type(quantity) is not int or not 1 <= quantity <= 99):
        raise HTTPException(422, "Quantity must be 1 to 99")
    if substitution is not None and substitution not in {"best-match", "refund", "specific"}:
        raise HTTPException(422, "Unknown substitution preference")
    with BACKEND.lifecycle.connection(transaction=True) as connection:
        row = connection.execute(
            """SELECT p.max_per_order,p.product_id,p.available,
            c.quantity AS current_quantity,
            COALESCE(c.variant_id,(SELECT variant_id FROM hmart_product_variants
              WHERE product_id=p.product_id AND is_default=1)) AS current_variant_id,
            COALESCE(li.available,0) AS location_available,
            COALESCE(li.availability_count,0) AS location_availability_count
            FROM hmart_cart c JOIN hmart_products p ON p.product_id=c.product_id
            JOIN hmart_session_state s ON s.owner=c.owner
            LEFT JOIN hmart_product_locations li ON li.product_id=p.product_id
              AND li.location_id=s.location_id
            WHERE c.owner=? AND c.product_id=?""",
            (owner, product_id),
        ).fetchone()
        if row is None:
            raise HTTPException(404, "Cart item not found")
        requested_quantity = quantity if quantity is not None else row["current_quantity"]
        requested_variant_id = (
            variant_id if variant_id is not None else row["current_variant_id"]
        )
        variant = connection.execute(
            """SELECT variant_id,unit_count FROM hmart_product_variants
            WHERE product_id=? AND variant_id=?""",
            (product_id, requested_variant_id),
        ).fetchone()
        if variant is None:
            raise HTTPException(422, "Unknown product variant")
        if quantity is not None or variant_id is not None:
            if requested_quantity > row["max_per_order"]:
                raise HTTPException(409, f"Maximum quantity is {row['max_per_order']}")
            if (
                not row["available"]
                or not row["location_available"]
                or requested_quantity * variant["unit_count"]
                > row["location_availability_count"]
            ):
                raise HTTPException(409, "Requested option exceeds local availability")
        connection.execute(
            """UPDATE hmart_cart SET quantity=?,variant_id=?,
            substitution=COALESCE(?,substitution) WHERE owner=? AND product_id=?""",
            (requested_quantity, requested_variant_id, substitution, owner, product_id),
        )
        return _cart(connection, owner)


@app.delete("/api/cart/{product_id}")
def remove_cart(request: Request, product_id: str) -> dict[str, Any]:
    owner = _owner(request)
    with BACKEND.lifecycle.connection(transaction=True) as connection:
        connection.execute(
            "DELETE FROM hmart_cart WHERE owner=? AND product_id=?", (owner, product_id)
        )
        return _cart(connection, owner)


@app.post("/api/favorites/{product_id}")
def toggle_favorite(request: Request, product_id: str) -> dict[str, Any]:
    owner, _ = _require_account(request)
    with BACKEND.lifecycle.connection(transaction=True) as connection:
        if connection.execute(
            "SELECT 1 FROM hmart_products WHERE product_id=?", (product_id,)
        ).fetchone() is None:
            raise HTTPException(404, "Product not found")
        existing = connection.execute(
            "SELECT 1 FROM hmart_favorites WHERE owner=? AND product_id=?",
            (owner, product_id),
        ).fetchone()
        if existing:
            connection.execute(
                "DELETE FROM hmart_favorites WHERE owner=? AND product_id=?",
                (owner, product_id),
            )
        else:
            connection.execute(
                "INSERT INTO hmart_favorites(owner,product_id) VALUES(?,?)",
                (owner, product_id),
            )
    return {"ok": True, "active": not bool(existing)}


@app.post("/api/coupon")
async def apply_coupon(request: Request) -> dict[str, Any]:
    body, owner = await request.json(), _owner(request)
    code = _text(body.get("code"), "code", 1, 40).upper()
    with BACKEND.lifecycle.connection(transaction=True) as connection:
        coupon = connection.execute(
            "SELECT * FROM hmart_coupons WHERE code=?", (code,)
        ).fetchone()
        if coupon is not None and coupon["state"] == "expired":
            raise HTTPException(409, "This coupon has expired")
        if coupon is None or coupon["state"] != "eligible":
            raise HTTPException(409, "This coupon is not eligible")
        cart = _cart(connection, owner)
        if cart["subtotal_cents"] < coupon["minimum_cents"]:
            raise HTTPException(409, "Basket does not meet the coupon minimum")
        connection.execute(
            "UPDATE hmart_session_state SET coupon_code=? WHERE owner=?", (code, owner)
        )
        return _cart(connection, owner)


@app.delete("/api/coupon")
def remove_coupon(request: Request) -> dict[str, Any]:
    owner = _owner(request)
    with BACKEND.lifecycle.connection(transaction=True) as connection:
        _ensure_state(connection, owner)
        connection.execute(
            "UPDATE hmart_session_state SET coupon_code=NULL WHERE owner=?", (owner,)
        )
        return _cart(connection, owner)


@app.post("/api/checkout/review")
async def checkout_review(request: Request) -> dict[str, Any]:
    body, owner = await request.json(), _owner(request)
    address = {
        "name": _text(body.get("name"), "name", 1, 120),
        "street": _text(body.get("street"), "street", 1, 160),
        "city": _text(body.get("city"), "city", 1, 100),
        "region": _text(body.get("region"), "region", 2, 2).upper(),
        "postal_code": _text(body.get("postal_code"), "postal_code", 5, 10),
    }
    if not re.fullmatch(r"[0-9]{5}(?:-[0-9]{4})?", address["postal_code"]):
        raise HTTPException(422, "Enter a valid US postal code")
    with BACKEND.lifecycle.connection(transaction=True) as connection:
        state = _ensure_state(connection, owner)
        if not state["postal_code"] or not state["fulfillment_slot"]:
            raise HTTPException(
                409, "Select a local service area and fulfillment time before checkout"
            )
        address_location_id = _location_id_for_postal(address["postal_code"])
        location = connection.execute(
            "SELECT * FROM hmart_locations WHERE location_id=?", (state["location_id"],)
        ).fetchone()
        if (
            address_location_id is None
            or address_location_id != state["location_id"]
            or address["region"] != location["region"]
        ):
            raise HTTPException(
                409,
                "Address ZIP and state must match the selected local service area",
            )
        cart = _cart(connection, owner)
        if not cart["items"]:
            raise HTTPException(409, "Add an item before checkout")
        unavailable = [item["name"] for item in cart["items"] if not item["available"]]
        if unavailable:
            raise HTTPException(
                409,
                "Remove unavailable items before checkout: " + ", ".join(unavailable),
            )
        connection.execute(
            """UPDATE hmart_session_state SET address_json=?,checkout_step='review'
            WHERE owner=?""", (json.dumps(address), owner)
        )
    return {
        "ok": True,
        "address": address,
        "cart": cart,
        "items": cart["items"],
        "fulfillment": cart["fulfillment"],
        "safe_stop": "Review only — no order was submitted",
    }


@app.post("/api/checkout/submit")
def checkout_submit() -> None:
    raise HTTPException(409, "Order submission is intentionally unavailable")


@app.post("/api/auth/sign-in")
async def sign_in(request: Request) -> dict[str, Any]:
    body = await request.json()
    token, _ = _session(request)
    try:
        result = AUTH.sign_in(
            token,
            email=_text(body.get("email"), "email", 1, 254),
            password=_text(body.get("password"), "password", 8, 128),
            session_rotation_callback=_rotation,
        )
    except AuthError as exc:
        raise HTTPException(401, "Credentials are invalid") from exc
    request.state.replacement_session_token = result["session_token"]
    request.state.session = AUTH.resolve_session(result["session_token"])
    return {"ok": True, "account": result["account"]}


@app.post("/api/auth/sign-out")
def sign_out(request: Request) -> dict[str, Any]:
    token, _ = _session(request)
    AUTH.sign_out(token)
    replacement, session = AUTH.ensure_session(None)
    request.state.replacement_session_token = replacement
    request.state.session = session
    return {"ok": True}


@app.post("/api/auth/register")
async def register(request: Request) -> dict[str, Any]:
    body = await request.json()
    token, _ = _session(request)
    try:
        email = _text(body.get("email"), "email", 1, 254)
        display_name = _text(body.get("display_name"), "display_name", 1, 120)
        password = _text(body.get("password"), "password", 8, 128)
        mail_configuration()
        result = AUTH.start_registration(
            token,
            email=email, display_name=display_name, password=password,
        )
        deliver_mail(AUTH, token, "registration", MAIL_WORKER)
        return {"accepted": True, "message": "Check the trial browser inbox for your registration code"}
    except MailUnavailable as exc:
        raise HTTPException(503, str(exc)) from exc
    except AuthError as exc:
        raise HTTPException(409, str(exc)) from exc


@app.get("/api/auth/local-inbox/{purpose}")
def local_inbox(request: Request, purpose: str) -> dict[str, Any]:
    raise HTTPException(404, "Read verification mail in the trial browser inbox")


@app.post("/api/auth/register/verify")
async def register_verify(request: Request) -> dict[str, Any]:
    body = await request.json()
    token, _ = _session(request)
    try:
        AUTH.verify_registration_code(token, _text(body.get("code"), "code", 6, 6))
        result = AUTH.complete_registration(
            token,
            subject_factory=lambda _connection, _account: (
                "customer-" + secrets.token_hex(8)
            ),
            session_rotation_callback=_rotation,
        )
    except AuthError as exc:
        raise HTTPException(409, str(exc)) from exc
    request.state.replacement_session_token = result["session_token"]
    request.state.session = AUTH.resolve_session(result["session_token"])
    return {"ok": True, "account": result["account"]}


@app.post("/api/auth/recovery")
async def recovery(request: Request) -> dict[str, Any]:
    body = await request.json()
    token, _ = _session(request)
    try:
        email = _text(body.get("email"), "email", 1, 254)
        mail_configuration()
        result = AUTH.start_password_reset(
            token,
            email=email,
            restart_invalid_flow=True,
        )
    except MailUnavailable as exc:
        raise HTTPException(503, str(exc)) from exc
    except AuthError as exc:
        raise HTTPException(429, str(exc)) from exc
    try:
        deliver_mail(AUTH, token, "password-reset", MAIL_WORKER)
    except MailUnavailable:
        # The public response must not enumerate whether the recipient exists.
        pass
    return {"accepted": True, "message": result.get("message", "Check the trial browser inbox")}


@app.post("/api/auth/recovery/verify")
async def recovery_verify(request: Request) -> dict[str, Any]:
    body = await request.json()
    token, _ = _session(request)
    try:
        AUTH.verify_password_reset_code(
            token, _text(body.get("code"), "code", 6, 6)
        )
    except AuthError as exc:
        raise HTTPException(409, str(exc)) from exc
    return {"ok": True, "state": "verified"}


@app.post("/api/auth/recovery/complete")
async def recovery_complete(request: Request) -> dict[str, Any]:
    body = await request.json()
    token, _ = _session(request)
    try:
        replacement = AUTH.complete_password_reset(
            token,
            new_password=_text(body.get("new_password"), "new_password", 8, 128),
            session_rotation_callback=_rotation,
        )
    except AuthError as exc:
        raise HTTPException(409, str(exc)) from exc
    session = AUTH.resolve_session(replacement)
    if session is None or session.get("account") is None:  # pragma: no cover
        raise RuntimeError("password reset did not create an authenticated session")
    request.state.replacement_session_token = replacement
    request.state.session = session
    return {"ok": True, "account": session["account"]}


@app.get("/api/orders")
def orders(request: Request) -> dict[str, Any]:
    owner, _ = _require_account(request)
    with BACKEND.lifecycle.connection() as connection:
        rows = [dict(row) for row in connection.execute(
            "SELECT * FROM hmart_orders WHERE owner=? ORDER BY placed_at DESC", (owner,)
        )]
        for order in rows:
            order["items"] = [dict(item) for item in connection.execute(
                """SELECT oi.*,p.name,p.image_path FROM hmart_order_items oi
                JOIN hmart_products p ON p.product_id=oi.product_id WHERE oi.order_id=?""",
                (order["order_id"],),
            )]
        return {"orders": rows}


@app.get("/api/orders/{order_id}")
def order_details(request: Request, order_id: str) -> dict[str, Any]:
    owner, _ = _require_account(request)
    with BACKEND.lifecycle.connection() as connection:
        order = connection.execute(
            "SELECT * FROM hmart_orders WHERE owner=? AND order_id=?",
            (owner, order_id),
        ).fetchone()
        if order is None:
            raise HTTPException(404, "Order not found")
        value = dict(order)
        value["items"] = [
            dict(item)
            for item in connection.execute(
                """SELECT oi.*,p.name,p.image_path FROM hmart_order_items oi
                JOIN hmart_products p ON p.product_id=oi.product_id
                WHERE oi.order_id=? ORDER BY p.name""",
                (order_id,),
            )
        ]
        return {"order": value}


@app.post("/api/orders/{order_id}/reorder")
def reorder(request: Request, order_id: str) -> dict[str, Any]:
    owner, _ = _require_account(request)
    with BACKEND.lifecycle.connection(transaction=True) as connection:
        if connection.execute(
            "SELECT 1 FROM hmart_orders WHERE owner=? AND order_id=?", (owner, order_id)
        ).fetchone() is None:
            raise HTTPException(404, "Order not found")
        state = _ensure_state(connection, owner)
        added_items: list[str] = []
        skipped_items: list[dict[str, str]] = []
        for item in connection.execute(
            """SELECT oi.product_id,oi.quantity,p.name,p.max_per_order,
            COALESCE(li.available,0) AS location_available,
            COALESCE(li.availability_count,0) AS location_availability_count
            FROM hmart_order_items oi JOIN hmart_products p
            ON p.product_id=oi.product_id
            LEFT JOIN hmart_product_locations li ON li.product_id=p.product_id
              AND li.location_id=? WHERE oi.order_id=?""",
            (state["location_id"], order_id),
        ):
            if not item["location_available"]:
                skipped_items.append(
                    {"product_id": item["product_id"], "name": item["name"], "reason": "unavailable"}
                )
                continue
            variant = connection.execute(
                """SELECT variant_id FROM hmart_product_variants
                WHERE product_id=? AND is_default=1""", (item["product_id"],)
            ).fetchone()
            connection.execute(
                """INSERT INTO hmart_cart(owner,product_id,variant_id,quantity) VALUES(?,?,?,?)
                ON CONFLICT(owner,product_id) DO UPDATE SET
                quantity=MIN(?,?,hmart_cart.quantity+excluded.quantity),
                variant_id=excluded.variant_id""",
                (
                    owner,
                    item["product_id"],
                    variant["variant_id"],
                    min(
                        item["quantity"],
                        item["max_per_order"],
                        item["location_availability_count"],
                    ),
                    item["max_per_order"],
                    item["location_availability_count"],
                ),
            )
            added_items.append(item["product_id"])
        return {
            **_cart(connection, owner),
            "added_items": added_items,
            "skipped_items": skipped_items,
        }


@app.get("/api/support")
def support_cases(request: Request) -> dict[str, Any]:
    owner, _ = _require_account(request)
    with BACKEND.lifecycle.connection() as connection:
        return {"cases": [dict(row) for row in connection.execute(
            "SELECT * FROM hmart_support_cases WHERE owner=? ORDER BY created_at DESC",
            (owner,),
        )]}


@app.post("/api/support")
async def create_support_case(request: Request) -> dict[str, Any]:
    body, (owner, _) = await request.json(), _require_account(request)
    case_id = f"CASE-HM-{secrets.token_hex(4).upper()}"
    with BACKEND.lifecycle.connection(transaction=True) as connection:
        connection.execute(
            """INSERT INTO hmart_support_cases(
            case_id,owner,subject,detail,status,created_at,is_simulation
            ) VALUES(?,?,?,?,?,?,1)""",
            (
                case_id, owner, _text(body.get("subject"), "subject", 1, 160),
                _text(body.get("detail"), "detail", 1, 1000), "open", _now(),
            ),
        )
    return {"ok": True, "case_id": case_id, "status": "open", "external_message_sent": False}


@app.get("/", include_in_schema=False)
def index() -> FileResponse:
    return FileResponse(STATIC / "index.html")


@app.get("/{slug}/p", include_in_schema=False)
def product_page(slug: str) -> FileResponse:
    with BACKEND.lifecycle.connection() as connection:
        exists = connection.execute(
            "SELECT 1 FROM hmart_products WHERE slug=?", (slug,)
        ).fetchone()
    return FileResponse(STATIC / "index.html", status_code=200 if exists else 404)


@app.get("/orders/{order_id}", include_in_schema=False)
def order_page(order_id: str) -> FileResponse:
    with BACKEND.lifecycle.connection() as connection:
        exists = connection.execute(
            "SELECT 1 FROM hmart_orders WHERE order_id=?", (order_id,)
        ).fetchone()
    return FileResponse(STATIC / "index.html", status_code=200 if exists else 404)


@app.get("/{path:path}", include_in_schema=False)
def spa(path: str, request: Request) -> FileResponse:
    source_search = (
        "/" not in path
        and bool(request.query_params.get("_q"))
        and request.query_params.get("map") == "ft"
    )
    allowed = (
        path in {
            "search", "cart", "checkout", "favorites", "orders", "support",
            "account/registration", "account/recovery",
        }
        or path.startswith("category/")
        or source_search
    )
    return FileResponse(STATIC / "index.html", status_code=200 if allowed else 404)


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        app,
        host="127.0.0.1",
        port=int(os.environ.get("PORT", "4174")),
        log_level="warning",
    )