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

import json
import os
import re
import sqlite3
import hashlib
import hmac
import secrets
import shutil
from datetime import datetime, timedelta, timezone
from http.cookies import CookieError, SimpleCookie
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse
from zoneinfo import ZoneInfo

ROOT = Path(__file__).resolve().parent
if "WEBSITEBENCH_SITE_BACKEND_DATABASE" not in os.environ:
    data_dir = Path(
        os.environ.get("WEBSITEBENCH_DATA_DIR")
        or os.environ.get("DATA_DIR")
        or f"/tmp/websitebench-breakoutgames-2-{os.getuid()}"
    ).resolve()
    data_dir.mkdir(parents=True, exist_ok=True)
    database_path = data_dir / "breakoutgames-2.sqlite3"
    if database_path.exists() and database_path.stat().st_size == 0:
        stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
        database_path.rename(data_dir / f"breakoutgames-2.invalid-empty-{stamp}.sqlite3")
    os.environ["WEBSITEBENCH_SITE_BACKEND_DATABASE"] = str(database_path)
# These imports must follow deployment database-path initialization above.
from backend.site_backend_integration import open_site_services  # noqa: E402
from websitebench.local_clone_auth import (  # noqa: E402
    AuthConflict,
    AuthError,
    AuthRejected,
    AuthValidationError,
)

backend, _auth = open_site_services()
DB = backend.lifecycle.database_path
with sqlite3.connect(DB) as con:
    con.execute("PRAGMA journal_mode=WAL")
    con.execute("PRAGMA foreign_keys=ON")
    con.execute("CREATE TABLE IF NOT EXISTS booking_interest (id INTEGER PRIMARY KEY, location TEXT NOT NULL, room TEXT NOT NULL, party_size INTEGER NOT NULL, visit_date TEXT NOT NULL, created_at TEXT DEFAULT CURRENT_TIMESTAMP)")
    con.execute("""CREATE TABLE IF NOT EXISTS local_draft (
        id INTEGER PRIMARY KEY, kind TEXT NOT NULL, fingerprint TEXT NOT NULL UNIQUE,
        payload_json TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'draft',
        created_at TEXT DEFAULT CURRENT_TIMESTAMP
    )""")
    con.execute("""CREATE TABLE IF NOT EXISTS gift_card_plan (
        id INTEGER PRIMARY KEY, fingerprint TEXT NOT NULL UNIQUE, location TEXT NOT NULL,
        amount_cents INTEGER NOT NULL, recipient_name TEXT NOT NULL DEFAULT '',
        status TEXT NOT NULL DEFAULT 'review', created_at TEXT DEFAULT CURRENT_TIMESTAMP
    )""")
    con.execute("""CREATE TABLE IF NOT EXISTS local_booking (
        id INTEGER PRIMARY KEY, location_id TEXT NOT NULL, room_id TEXT NOT NULL,
        party_size INTEGER NOT NULL, visit_date TEXT NOT NULL, time_slot TEXT NOT NULL,
        unit_price_cents INTEGER NOT NULL, total_cents INTEGER NOT NULL,
        idempotency_key TEXT NOT NULL UNIQUE, confirmation_code TEXT NOT NULL UNIQUE,
        manage_token_hash TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'confirmed',
        created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
    )""")
    columns = {row[1] for row in con.execute("PRAGMA table_info(local_booking)")}
    booking_columns = {
        "account_id": "TEXT",
        "package_id": "TEXT NOT NULL DEFAULT 'standard'",
        "customer_name": "TEXT NOT NULL DEFAULT ''",
        "customer_email": "TEXT NOT NULL DEFAULT ''",
        "customer_phone": "TEXT NOT NULL DEFAULT ''",
        "special_requests": "TEXT NOT NULL DEFAULT ''",
        "payment_scenario": "TEXT NOT NULL DEFAULT 'sandbox-approved'",
    }
    for name, declaration in booking_columns.items():
        if name not in columns:
            con.execute(f"ALTER TABLE local_booking ADD COLUMN {name} {declaration}")
    con.execute("""CREATE UNIQUE INDEX IF NOT EXISTS one_active_booking_per_slot
        ON local_booking(location_id, room_id, visit_date, time_slot)
        WHERE status = 'confirmed'""")
    con.execute("CREATE TABLE IF NOT EXISTS local_profile (account_id TEXT PRIMARY KEY, phone TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)")
    con.execute("CREATE TABLE IF NOT EXISTS local_favorite (owner_key TEXT NOT NULL, location_id TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(owner_key, location_id))")
    con.execute("CREATE TABLE IF NOT EXISTS local_booking_action (id INTEGER PRIMARY KEY, booking_id INTEGER NOT NULL, action TEXT NOT NULL, message TEXT NOT NULL DEFAULT '', rating INTEGER, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY(booking_id) REFERENCES local_booking(id) ON DELETE CASCADE)")


EMAIL = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$")
IDEMPOTENCY_KEY = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{7,127}$")
TORONTO = ZoneInfo("America/Toronto")
UNIT_PRICE_CENTS = 3999
CSRF_SECRET = secrets.token_bytes(32)
LOCATIONS = {
    "pittsburgh": {"id": "pittsburgh", "name": "Pittsburgh", "distance_km": 328.0},
    "columbus": {"id": "columbus", "name": "Columbus", "distance_km": 510.0},
    "cincinnati": {"id": "cincinnati", "name": "Cincinnati", "distance_km": 665.0},
}
BOOKING_ROOMS = {
    "the-kidnapping": {"id": "the-kidnapping", "name": "The Kidnapping", "theme": "thriller", "capacity": 8},
    "mystery-mansion": {"id": "mystery-mansion", "name": "Mystery Mansion", "theme": "horror", "capacity": 8},
}
EXPERIENCES = {
    "pittsburgh": {
        **LOCATIONS["pittsburgh"], "rating": 4.9, "review_count": 1842,
        "price_cents": UNIT_PRICE_CENTS, "themes": ["horror", "thriller"],
        "description": "Private, story-driven escape rooms nearest to Downtown Toronto among this clone's available locations.",
        "pricing": "$39.99 per person; local sandbox total is calculated by the server.",
        "reviews": "4.9 from 1,842 representative local fixture reviews.",
        "policies": "Arrive 15 minutes early. Changes and cancellations remain local sandbox actions.",
        "availability": "Upcoming Saturday evening slots from 7 PM through 9 PM in America/Toronto.",
        "available": True,
    },
    "columbus": {
        **LOCATIONS["columbus"], "rating": 4.8, "review_count": 1230,
        "price_cents": 4299, "themes": ["mystery", "adventure"],
        "description": "Private escape-room experiences in Columbus.",
        "pricing": "$42.99 per person.", "reviews": "4.8 from 1,230 representative local fixture reviews.",
        "policies": "Local sandbox policies only.", "availability": "Evening fixture availability.", "available": True,
    },
    "cincinnati": {
        **LOCATIONS["cincinnati"], "rating": 4.7, "review_count": 940,
        "price_cents": 4599, "themes": ["mystery"],
        "description": "Private escape-room experiences in Cincinnati.",
        "pricing": "$45.99 per person.", "reviews": "4.7 from 940 representative local fixture reviews.",
        "policies": "Local sandbox policies only.", "availability": "Limited fixture availability.", "available": False,
    },
}
PACKAGES = {
    "standard": {"id": "standard", "name": "Standard private room"},
    "private-room": {"id": "private-room", "name": "Private room package"},
}
PAYMENT_SCENARIOS = {
    "sandbox-approved": "approved",
    "sandbox-declined": "declined",
    "sandbox-retry": "retryable",
}
TIME_SLOTS = (
    {"id": "19:00-20:00", "start": "19:00", "end": "20:00"},
    {"id": "20:00-21:00", "start": "20:00", "end": "21:00"},
)
DRAFT_FIELDS = {
    "contact": ("first_name", "last_name", "email", "location", "message"),
    "team-building": ("name", "email", "location", "group_type", "organization", "phone", "max_players", "preferred_start", "preferred_end", "message"),
    "celebration": ("name", "email", "location", "occasion", "party_size", "message"),
    "newsletter": ("email",),
}


def upcoming_saturday():
    today = datetime.now(TORONTO).date()
    offset = (5 - today.weekday()) % 7
    return today + timedelta(days=offset or 7)


def booking_catalog():
    location = {
        **LOCATIONS["pittsburgh"],
        "explanation": (
            "Pittsburgh is the nearest available Breakout Games location to Downtown "
            "Toronto by straight-line distance among the locations in this clone."
        ),
        "candidate_distances_km": {
            key: item["distance_km"] for key, item in LOCATIONS.items()
        },
    }
    return {
        "timezone": "America/Toronto",
        "reference_location": "Downtown Toronto",
        "recommended_location": location,
        "upcoming_saturday": upcoming_saturday().isoformat(),
        "rooms": list(BOOKING_ROOMS.values()),
        "time_slots": list(TIME_SLOTS),
        "packages": list(PACKAGES.values()),
        "payment_scenarios": [
            {"id": key, "outcome": value}
            for key, value in PAYMENT_SCENARIOS.items()
        ],
    }

def validate_selection(data):
    try:
        party_size = int(data.get("party_size", 0))
    except (TypeError, ValueError):
        raise ValueError("Party size must be a whole number.")
    location = LOCATIONS.get(str(data.get("location_id", "")))
    room = BOOKING_ROOMS.get(str(data.get("room_id", "")))
    slot = next((item for item in TIME_SLOTS if item["id"] == data.get("time_slot")), None)
    if not location or location["id"] != "pittsburgh":
        raise ValueError("Choose the recommended Pittsburgh location.")
    if not room or room["theme"] not in {"horror", "thriller"}:
        raise ValueError("Choose a horror or thriller room.")
    if not 2 <= party_size <= room["capacity"]:
        raise ValueError(f"Party size must be between 2 and {room['capacity']}.")
    if str(data.get("visit_date", "")) != upcoming_saturday().isoformat():
        raise ValueError("Choose the upcoming Saturday in America/Toronto.")
    if not slot:
        raise ValueError("Choose an evening time slot between 7 PM and 9 PM.")
    return location, room, slot, party_size


def booking_preview(data):
    location, room, slot, party_size = validate_selection(data)
    package = PACKAGES.get(str(data.get("package_id", "standard")))
    scenario = str(data.get("payment_scenario", "sandbox-approved"))
    if not package:
        raise ValueError("Choose a supported package.")
    if scenario not in PAYMENT_SCENARIOS:
        raise ValueError("Choose a local sandbox payment scenario.")
    customer = {
        "name": str(data.get("customer_name", "")).strip()[:120],
        "email": str(data.get("customer_email", "")).strip()[:254],
        "phone": str(data.get("customer_phone", "")).strip()[:60],
        "special_requests": str(data.get("special_requests", "")).strip()[:1000],
    }
    if customer["email"] and not EMAIL.fullmatch(customer["email"]):
        raise ValueError("Enter a valid customer email address.")
    return {
        "location": location,
        "room": room,
        "party_size": party_size,
        "visit_date": upcoming_saturday().isoformat(),
        "time_slot": slot,
        "timezone": "America/Toronto",
        "unit_price_cents": UNIT_PRICE_CENTS,
        "total_cents": UNIT_PRICE_CENTS * party_size,
        "currency": "USD",
        "sandbox": True,
        "package": package,
        "customer": customer,
        "payment": {
            "adapter": "local-sandbox",
            "scenario": scenario,
            "outcome": PAYMENT_SCENARIOS[scenario],
            "collects_real_payment": False,
        },
    }

def canonical(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True)


def fingerprint(kind, value):
    return hashlib.sha256((kind + ":" + canonical(value)).encode()).hexdigest()


class Handler(SimpleHTTPRequestHandler):
    server_version = "BreakoutLocal/1.0"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=str(ROOT / "static"), **kwargs)

    def end_headers(self):
        self.send_header("Content-Security-Policy", "default-src 'self'; connect-src 'self'; img-src 'self' data:; media-src 'self'; style-src 'self'; script-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'")
        self.send_header("X-Content-Type-Options", "nosniff")
        self.send_header("Referrer-Policy", "no-referrer")
        self.send_header("X-Frame-Options", "DENY")
        super().end_headers()

    def cookie_token(self):
        cookie = SimpleCookie()
        try:
            cookie.load(self.headers.get("Cookie", ""))
        except CookieError:
            return None
        morsel = cookie.get("wb_session")
        return morsel.value if morsel else None

    def session_context(self):
        return _auth.ensure_session(self.cookie_token())

    @staticmethod
    def session_cookie(token):
        return f"wb_session={token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=2592000"

    @staticmethod
    def csrf_token(token):
        return hmac.new(CSRF_SECRET, token.encode(), hashlib.sha256).hexdigest()

    @staticmethod
    def account_id(session):
        account = session.get("account")
        return str(account["account_id"]) if account else None

    def owner_key(self, token, session):
        account_id = self.account_id(session)
        return f"account:{account_id}" if account_id else f"session:{_auth.session_owner_digest(token)}"

    def require_csrf(self):
        token, session = self.session_context()
        supplied = self.headers.get("X-CSRF-Token", "")
        if not hmac.compare_digest(supplied, self.csrf_token(token)):
            self.send_json(
                {"ok": False, "error": "A valid session CSRF token is required."},
                403,
                {"Set-Cookie": self.session_cookie(token)},
            )
            return None
        return token, session

    def search_experiences(self, query):
        term = query.get("q", [""])[0].strip().lower()
        available_only = query.get("available", [""])[0].lower() == "true"
        try:
            max_price = int(query.get("max_price_cents", ["0"])[0])
        except ValueError:
            return self.send_json({"ok": False, "error": "Maximum price must be a whole number."}, 422)
        results = []
        for item in EXPERIENCES.values():
            haystack = " ".join([item["name"], item["description"], *item["themes"]]).lower()
            if term and term not in haystack:
                continue
            if available_only and not item["available"]:
                continue
            if max_price and item["price_cents"] > max_price:
                continue
            results.append(item)
        sort = query.get("sort", ["distance"])[0]
        sort_key = {"distance": "distance_km", "price": "price_cents", "rating": "rating"}.get(sort, "distance_km")
        results.sort(key=lambda item: item[sort_key], reverse=sort == "rating")
        return self.send_json({
            "count": len(results), "results": results,
            "no_results": not results, "return_path": "/experiences",
        })

    def get_availability(self, query):
        location_id = query.get("location_id", [""])[0]
        room_id = query.get("room_id", [""])[0]
        visit_date = query.get("visit_date", [""])[0]
        try:
            party_size = int(query.get("party_size", ["0"])[0])
            parsed_date = datetime.strptime(visit_date, "%Y-%m-%d").date()
        except (TypeError, ValueError):
            return self.send_json({"ok": False, "error": "Provide a valid date and party size."}, 422)
        room = BOOKING_ROOMS.get(room_id)
        if location_id != "pittsburgh" or not room or not 2 <= party_size <= room["capacity"] or parsed_date <= datetime.now(TORONTO).date():
            return self.send_json({"ok": False, "error": "Choose a supported future experience and party size."}, 422)
        with sqlite3.connect(DB) as con:
            taken = {row[0] for row in con.execute(
                "SELECT time_slot FROM local_booking WHERE location_id=? AND room_id=? AND visit_date=? AND status='confirmed'",
                (location_id, room_id, visit_date),
            )}
        return self.send_json({
            "timezone": "America/Toronto", "visit_date": visit_date,
            "party_size": party_size,
            "slots": [{**slot, "available": slot["id"] not in taken} for slot in TIME_SLOTS],
        })
    def do_GET(self):
        parsed = urlparse(self.path)
        path = parsed.path
        query = parse_qs(parsed.query)
        if path in {"/api/health", "/healthz"}:
            return self.send_json({"ok": True, "site_id": "breakoutgames-2"})
        if path == "/api/session":
            token, session = self.session_context()
            return self.send_json(
                {**session, "csrf_token": self.csrf_token(token)},
                headers={"Set-Cookie": self.session_cookie(token)},
            )
        if path == "/api/booking-catalog":
            try:
                party_size = int(query.get("party_size", ["4"])[0])
            except ValueError:
                return self.send_json({"ok": False, "error": "Party size must be a whole number."}, 422)
            if party_size != 4:
                return self.send_json({"ok": False, "error": "This task requires exactly 4 people."}, 422)
            return self.send_json(booking_catalog())
        if path == "/api/experiences":
            return self.search_experiences(query)
        if path.startswith("/api/experiences/"):
            experience = EXPERIENCES.get(path.rsplit("/", 1)[-1])
            return self.send_json(experience) if experience else self.send_json({"ok": False, "error": "Experience not found."}, 404)
        if path == "/api/availability":
            return self.get_availability(query)
        if path == "/api/favorites":
            token, session = self.session_context()
            owner = self.owner_key(token, session)
            with sqlite3.connect(DB) as con:
                ids = [row[0] for row in con.execute(
                    "SELECT location_id FROM local_favorite WHERE owner_key=? ORDER BY created_at DESC",
                    (owner,),
                )]
            return self.send_json(
                {"results": [EXPERIENCES[item] for item in ids if item in EXPERIENCES]},
                headers={"Set-Cookie": self.session_cookie(token)},
            )
        if path == "/api/booking-interest":
            with sqlite3.connect(DB) as con:
                saved = con.execute(
                    "SELECT location,room,party_size,visit_date FROM booking_interest ORDER BY id"
                ).fetchall()
            return self.send_json({
                "ok": True,
                "count": len(saved),
                "results": [
                    {"location": row[0], "room": row[1], "party_size": row[2], "visit_date": row[3]}
                    for row in saved
                ],
                "message": "Local game plans saved in this sandbox. No booking or payment was made.",
            })
        if path == "/api/account/bookings":
            token, session = self.session_context()
            account_id = self.account_id(session)
            headers = {"Set-Cookie": self.session_cookie(token)}
            if not account_id:
                return self.send_json({"ok": False, "error": "Sign in to view private booking history."}, 401, headers)
            with sqlite3.connect(DB) as con:
                con.row_factory = sqlite3.Row
                rows = con.execute(
                    "SELECT * FROM local_booking WHERE account_id=? ORDER BY created_at DESC, id DESC",
                    (account_id,),
                ).fetchall()
            return self.send_json(
                {"results": [self.history_response(row) for row in rows], "return_path": "/experiences"},
                headers=headers,
            )
        if path.startswith("/api/"):
            return self.send_json({"ok": False, "error": "Not found."}, 404)
        if path == "/assets/hero-video-v2.mp4":
            return self.serve_hero_video(head_only=False)
        if path in {"/app.css", "/app.js", "/index.html", "/catalog.json"} or path.startswith("/assets/"):
            return super().do_GET()
        expanded = {
            "/experiences", "/experiences/pittsburgh", "/account/sign-in",
            "/account/register", "/account/recovery", "/account/bookings",
        }
        known = path == "/" or path in {"/book", "/team-building", "/escape-rooms", "/company/gift-cards", "/company/jobs", "/waiver"} | expanded
        if not known:
            try:
                catalog = json.loads((ROOT / "static/catalog.json").read_text())
                first = path.strip("/").split("/", 1)[0]
                known = path in catalog.get("routes", []) or (path == f"/{first}" and first in catalog.get("locations", []))
            except (OSError, json.JSONDecodeError):
                known = False
        return self.serve_index(200 if known else 404)
    def serve_index(self, status):
        body = (ROOT / "static/index.html").read_bytes()
        self.send_response(status)
        self.send_header("Content-Type", "text/html; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_HEAD(self):
        path = urlparse(self.path).path
        if path == "/assets/hero-video-v2.mp4":
            return self.serve_hero_video(head_only=True)
        return super().do_HEAD()

    def serve_hero_video(self, head_only):
        asset = ROOT / "static/assets/hero-video-v2.mp4"
        size = asset.stat().st_size
        start, end, status = 0, size - 1, 200
        requested = self.headers.get("Range")
        if requested:
            match = re.fullmatch(r"bytes=(\d*)-(\d*)", requested.strip())
            if not match or (not match.group(1) and not match.group(2)):
                return self.send_range_error(size)
            if match.group(1):
                start = int(match.group(1))
                end = min(int(match.group(2)), size - 1) if match.group(2) else size - 1
            else:
                suffix = int(match.group(2))
                if suffix <= 0:
                    return self.send_range_error(size)
                start = max(0, size - suffix)
            if start >= size or start > end:
                return self.send_range_error(size)
            status = 206

        length = end - start + 1
        self.send_response(status)
        self.send_header("Content-Type", "video/mp4")
        self.send_header("Accept-Ranges", "bytes")
        self.send_header("Content-Length", str(length))
        self.send_header("Last-Modified", self.date_time_string(asset.stat().st_mtime))
        if status == 206:
            self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
        self.end_headers()
        if head_only:
            return
        try:
            with asset.open("rb") as source:
                source.seek(start)
                shutil.copyfileobj(source, self.wfile, length=64 * 1024) if length == size else self.copy_bounded(source, length)
        except (BrokenPipeError, ConnectionResetError):
            return

    def copy_bounded(self, source, remaining):
        while remaining:
            chunk = source.read(min(64 * 1024, remaining))
            if not chunk:
                break
            self.wfile.write(chunk)
            remaining -= len(chunk)

    def send_range_error(self, size):
        self.send_response(416)
        self.send_header("Content-Range", f"bytes */{size}")
        self.send_header("Accept-Ranges", "bytes")
        self.send_header("Content-Length", "0")
        self.end_headers()

    def local_action_allowed(self):
        if self.headers.get("X-WebsiteBench-Action") != "local-sandbox":
            self.send_json({"ok": False, "error": "Local sandbox action header required."}, 403)
            return False
        origin = self.headers.get("Origin")
        if origin:
            parsed = urlparse(origin)
            if parsed.scheme not in {"http", "https"} or parsed.hostname not in {"127.0.0.1", "localhost", "::1"}:
                self.send_json({"ok": False, "error": "Cross-origin actions are not allowed."}, 403)
                return False
        return True

    def do_POST(self):
        path = urlparse(self.path).path
        if not self.local_action_allowed():
            return
        try:
            size = int(self.headers.get("Content-Length", "0"))
        except ValueError:
            return self.send_json({"ok": False, "error": "Invalid content length."}, 400)
        if size > 32_768:
            return self.send_json({"ok": False, "error": "Draft is too large."}, 413)
        try:
            data = json.loads(self.rfile.read(size) or b"{}")
        except (json.JSONDecodeError, UnicodeDecodeError):
            return self.send_json({"ok": False, "error": "Invalid JSON."}, 400)
        if not isinstance(data, dict):
            return self.send_json({"ok": False, "error": "JSON body must be an object."}, 400)
        if path == "/api/reset":
            with sqlite3.connect(DB) as con:
                con.execute("DELETE FROM local_booking_action")
                con.execute("DELETE FROM booking_interest")
                con.execute("DELETE FROM local_draft")
                con.execute("DELETE FROM gift_card_plan")
                con.execute("DELETE FROM local_booking")
                con.execute("DELETE FROM local_favorite")
            return self.send_json({"ok": True, "message": "Local fixtures reset."})
        if path == "/api/favorites":
            return self.save_favorite(data)
        if path == "/api/auth/register":
            return self.register_account(data)
        if path == "/api/auth/sign-in":
            return self.sign_in_account(data)
        if path == "/api/auth/sign-out":
            return self.sign_out_account()
        if path == "/api/auth/recovery":
            return self.recover_account(data)
        if path == "/api/account/seed-history":
            return self.seed_history()
        if path == "/api/bookings/preview":
            try:
                return self.send_json(booking_preview(data))
            except ValueError as error:
                return self.send_json({"ok": False, "error": str(error)}, 422)
        if path == "/api/bookings":
            return self.create_booking(data)
        if path == "/api/bookings/manage":
            return self.manage_booking(data)
        if path == "/api/bookings/cancel":
            return self.change_booking_status(data, "canceled")
        if path == "/api/bookings/restore":
            return self.change_booking_status(data, "confirmed")
        if path == "/api/bookings/reschedule":
            return self.reschedule_booking(data)
        if path == "/api/bookings/post-action":
            return self.post_booking_action(data)
        if path.startswith("/api/drafts/"):
            return self.save_draft(path.rsplit("/", 1)[-1], data)
        if path == "/api/gift-card-plan":
            return self.save_gift_plan(data)
        if path != "/api/booking-interest":
            return self.send_json({"ok": False, "error": "Not found."}, 404)
        required = ("location", "room", "party_size", "visit_date")
        if any(not data.get(key) for key in required):
            return self.send_json({"ok": False, "error": "Complete every field."}, 422)
        try:
            party = int(data["party_size"])
        except (TypeError, ValueError):
            return self.send_json({"ok": False, "error": "Party size must be a whole number."}, 422)
        if not 2 <= party <= 12:
            return self.send_json({"ok": False, "error": "Party size must be between 2 and 12."}, 422)
        valid_locations = set(LOCATIONS) | {item["name"] for item in LOCATIONS.values()}
        valid_rooms = {item["name"] for item in BOOKING_ROOMS.values()}
        if data["location"] not in valid_locations or data["room"] not in valid_rooms:
            return self.send_json({"ok": False, "error": "Choose a listed location and room."}, 422)
        try:
            visit_date = datetime.strptime(str(data["visit_date"]), "%Y-%m-%d").date()
        except ValueError:
            return self.send_json({"ok": False, "error": "Enter a valid visit date."}, 422)
        if visit_date <= datetime.now(TORONTO).date():
            return self.send_json({"ok": False, "error": "Visit date must be in the future."}, 422)
        con = sqlite3.connect(DB, timeout=5)
        try:
            with con:
                con.execute(
                    "INSERT INTO booking_interest(location,room,party_size,visit_date) VALUES (?,?,?,?)",
                    (data["location"], data["room"], party, data["visit_date"]),
                )
            # The schema runs in WAL mode, so a committed plan lives in the
            # sidecar log until it is checkpointed.  Fold it into the database
            # file itself so the saved plan is durable on its own.
            con.execute("PRAGMA wal_checkpoint(TRUNCATE)")
        finally:
            con.close()
        return self.send_json({"ok": True, "message": "Your local game plan is saved. No booking or payment was made."}, 201)

    def create_booking(self, data):
        try:
            preview = booking_preview(data)
        except ValueError as error:
            return self.send_json({"ok": False, "error": str(error)}, 422)
        outcome = preview["payment"]["outcome"]
        if outcome == "declined":
            return self.send_json({
                "ok": False, "sandbox": True, "payment_status": "declined",
                "error": "Simulated payment decline. No booking or charge was created.",
            }, 402)
        if outcome == "retryable":
            return self.send_json({
                "ok": False, "sandbox": True, "payment_status": "retryable",
                "error": "Simulated temporary failure. Retry is safe and no charge was created.",
            }, 503)
        key = str(data.get("idempotency_key", ""))
        if not IDEMPOTENCY_KEY.fullmatch(key):
            return self.send_json({"ok": False, "error": "Provide a valid idempotency key."}, 422)
        token = secrets.token_urlsafe(32)
        confirmation = "BG-" + secrets.token_hex(6).upper()
        session = _auth.resolve_session(self.cookie_token())
        account_id = self.account_id(session or {})
        customer = preview["customer"]
        con = sqlite3.connect(DB, timeout=5, isolation_level=None)
        con.row_factory = sqlite3.Row
        try:
            con.execute("BEGIN IMMEDIATE")
            existing = con.execute("SELECT * FROM local_booking WHERE idempotency_key = ?", (key,)).fetchone()
            if existing:
                con.commit()
                return self.send_json(self.booking_response(existing), 200)
            con.execute(
                """INSERT INTO local_booking(
                    location_id,room_id,party_size,visit_date,time_slot,
                    unit_price_cents,total_cents,idempotency_key,confirmation_code,
                    manage_token_hash,account_id,package_id,customer_name,
                    customer_email,customer_phone,special_requests,payment_scenario
                ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
                (
                    preview["location"]["id"], preview["room"]["id"], preview["party_size"],
                    preview["visit_date"], preview["time_slot"]["id"], preview["unit_price_cents"],
                    preview["total_cents"], key, confirmation, hashlib.sha256(token.encode()).hexdigest(),
                    account_id, preview["package"]["id"], customer["name"], customer["email"],
                    customer["phone"], customer["special_requests"], preview["payment"]["scenario"],
                ),
            )
            row = con.execute("SELECT * FROM local_booking WHERE idempotency_key = ?", (key,)).fetchone()
            con.commit()
        except sqlite3.IntegrityError:
            con.rollback()
            return self.send_json({"ok": False, "error": "That room and time slot is no longer available."}, 409)
        finally:
            con.close()
        return self.send_json({**self.booking_response(row), "manage_token": token}, 201)

    def find_managed_booking(self, con, data):
        confirmation = str(data.get("confirmation_code", ""))
        token = str(data.get("manage_token", ""))
        if not confirmation or not token:
            return None
        row = con.execute("SELECT * FROM local_booking WHERE confirmation_code = ?", (confirmation,)).fetchone()
        if not row:
            return None
        supplied = hashlib.sha256(token.encode()).hexdigest()
        return row if hmac.compare_digest(row["manage_token_hash"], supplied) else None

    def manage_booking(self, data):
        with sqlite3.connect(DB) as con:
            con.row_factory = sqlite3.Row
            row = self.find_managed_booking(con, data)
        if not row:
            return self.send_json({"ok": False, "error": "Booking not found."}, 404)
        return self.send_json(self.booking_response(row))

    def change_booking_status(self, data, target):
        con = sqlite3.connect(DB, timeout=5, isolation_level=None)
        con.row_factory = sqlite3.Row
        try:
            con.execute("BEGIN IMMEDIATE")
            row = self.find_managed_booking(con, data)
            if not row:
                con.rollback()
                return self.send_json({"ok": False, "error": "Booking not found."}, 404)
            if row["status"] != target:
                con.execute("UPDATE local_booking SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?", (target, row["id"]))
            row = con.execute("SELECT * FROM local_booking WHERE id = ?", (row["id"],)).fetchone()
            con.commit()
        except sqlite3.IntegrityError:
            con.rollback()
            return self.send_json({"ok": False, "error": "The slot was taken while this booking was canceled."}, 409)
        finally:
            con.close()
        return self.send_json(self.booking_response(row))

    def booking_response(self, row):
        keys = set(row.keys())
        return {
            "ok": True,
            "sandbox": True,
            "status": row["status"],
            "confirmation_code": row["confirmation_code"],
            "location_id": row["location_id"],
            "room_id": row["room_id"],
            "party_size": row["party_size"],
            "visit_date": row["visit_date"],
            "time_slot": row["time_slot"],
            "unit_price_cents": row["unit_price_cents"],
            "total_cents": row["total_cents"],
            "currency": "USD",
            "package_id": row["package_id"] if "package_id" in keys else "standard",
            "customer_name": row["customer_name"] if "customer_name" in keys else "",
            "customer_email": row["customer_email"] if "customer_email" in keys else "",
            "customer_phone": row["customer_phone"] if "customer_phone" in keys else "",
            "special_requests": row["special_requests"] if "special_requests" in keys else "",
            "payment_scenario": row["payment_scenario"] if "payment_scenario" in keys else "sandbox-approved",
            "message": "Confirmed in the local sandbox only. No real booking or payment was made.",
        }

    def save_favorite(self, data):
        context = self.require_csrf()
        if not context:
            return
        token, session = context
        location_id = str(data.get("location_id", ""))
        if location_id not in EXPERIENCES:
            return self.send_json({"ok": False, "error": "Choose a listed location."}, 422)
        owner = self.owner_key(token, session)
        with sqlite3.connect(DB) as con:
            con.execute(
                "INSERT OR IGNORE INTO local_favorite(owner_key,location_id) VALUES (?,?)",
                (owner, location_id),
            )
        return self.send_json(
            {"ok": True, "location_id": location_id, "saved": True},
            201,
            {"Set-Cookie": self.session_cookie(token)},
        )

    def register_account(self, data):
        context = self.require_csrf()
        if not context:
            return
        token, session = context
        if self.account_id(session):
            return self.send_json({"ok": False, "error": "Sign out before creating another account."}, 409)
        display_name = str(data.get("display_name", "")).strip()
        email = str(data.get("email", "")).strip()
        password = str(data.get("password", ""))
        phone = str(data.get("phone", "")).strip()[:60]
        if data.get("accepted_terms") is not True:
            return self.send_json({"ok": False, "error": "Accept the local sandbox terms to continue.", "fields": ["accepted_terms"]}, 422)
        if not phone:
            return self.send_json({"ok": False, "error": "Enter a contact phone number.", "fields": ["phone"]}, 422)
        try:
            _auth.seed_account(
                subject_id="local-profile-" + secrets.token_hex(16),
                email=email,
                display_name=display_name,
                password=password,
                email_verified=True,
            )
            signed_in = _auth.sign_in(token, email=email, password=password)
        except AuthConflict:
            return self.send_json({"ok": False, "error": "That email already belongs to a local account."}, 409)
        except AuthValidationError as error:
            return self.send_json({"ok": False, "error": str(error)}, 422)
        except AuthError:
            return self.send_json({"ok": False, "error": "Local account creation failed."}, 400)
        account = signed_in["account"]
        with sqlite3.connect(DB) as con:
            con.execute(
                "INSERT OR REPLACE INTO local_profile(account_id,phone,updated_at) VALUES (?,?,CURRENT_TIMESTAMP)",
                (account["account_id"], phone),
            )
        new_token = signed_in["session_token"]
        return self.send_json(
            {"ok": True, "authenticated": True, "account": account, "profile": {"phone": phone},
             "message": "Local sandbox account created. No email or message was sent."},
            201,
            {"Set-Cookie": self.session_cookie(new_token)},
        )

    def sign_in_account(self, data):
        context = self.require_csrf()
        if not context:
            return
        token, _ = context
        try:
            signed_in = _auth.sign_in(
                token,
                email=str(data.get("email", "")),
                password=str(data.get("password", "")),
            )
        except (AuthRejected, AuthValidationError):
            return self.send_json({"ok": False, "error": "Credentials are invalid."}, 401)
        new_token = signed_in["session_token"]
        return self.send_json(
            {"ok": True, "authenticated": True, "account": signed_in["account"]},
            headers={"Set-Cookie": self.session_cookie(new_token)},
        )

    def sign_out_account(self):
        context = self.require_csrf()
        if not context:
            return
        token, _ = context
        _auth.sign_out(token)
        new_token, session = _auth.ensure_session(None)
        return self.send_json(
            {**session, "ok": True, "csrf_token": self.csrf_token(new_token)},
            headers={"Set-Cookie": self.session_cookie(new_token)},
        )

    def recover_account(self, data):
        context = self.require_csrf()
        if not context:
            return
        token, _ = context
        try:
            result = _auth.start_password_reset(token, email=str(data.get("email", "")))
        except AuthError:
            result = {"accepted": True, "message": "If a matching local account exists, recovery guidance is available locally."}
        return self.send_json({**result, "ok": True, "delivery": "disabled-local-only"}, 202)

    def seed_history(self):
        context = self.require_csrf()
        if not context:
            return
        _, session = context
        account_id = self.account_id(session)
        if not account_id:
            return self.send_json({"ok": False, "error": "Sign in before loading private demo history."}, 401)
        key = f"seed-history-{account_id}"
        with sqlite3.connect(DB) as con:
            con.execute(
                """INSERT OR IGNORE INTO local_booking(
                    location_id,room_id,party_size,visit_date,time_slot,unit_price_cents,
                    total_cents,idempotency_key,confirmation_code,manage_token_hash,status,
                    account_id,package_id,customer_name,payment_scenario
                ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
                (
                    "pittsburgh", "mystery-mansion", 4, "2026-01-10", "19:00-20:00",
                    UNIT_PRICE_CENTS, UNIT_PRICE_CENTS * 4, key,
                    "BG-HISTORY-" + hashlib.sha256(account_id.encode()).hexdigest()[:8].upper(),
                    hashlib.sha256(("history:" + account_id).encode()).hexdigest(), "completed",
                    account_id, "private-room", "Seeded Local Guest", "sandbox-approved",
                ),
            )
        return self.send_json({"ok": True, "seeded": True, "sandbox": True}, 201)

    def reschedule_booking(self, data):
        visit_date = str(data.get("visit_date", ""))
        time_slot = str(data.get("time_slot", ""))
        if visit_date != upcoming_saturday().isoformat() or time_slot not in {item["id"] for item in TIME_SLOTS}:
            return self.send_json({"ok": False, "error": "Choose an offered upcoming Saturday slot."}, 422)
        con = sqlite3.connect(DB, timeout=5, isolation_level=None)
        con.row_factory = sqlite3.Row
        try:
            con.execute("BEGIN IMMEDIATE")
            row = self.find_managed_booking(con, data)
            if not row:
                con.rollback()
                return self.send_json({"ok": False, "error": "Booking not found."}, 404)
            if row["status"] != "confirmed":
                con.rollback()
                return self.send_json({"ok": False, "error": "Only confirmed bookings can be rescheduled."}, 409)
            con.execute(
                "UPDATE local_booking SET visit_date=?,time_slot=?,updated_at=CURRENT_TIMESTAMP WHERE id=?",
                (visit_date, time_slot, row["id"]),
            )
            row = con.execute("SELECT * FROM local_booking WHERE id=?", (row["id"],)).fetchone()
            con.commit()
        except sqlite3.IntegrityError:
            con.rollback()
            return self.send_json({"ok": False, "error": "That replacement slot is no longer available."}, 409)
        finally:
            con.close()
        return self.send_json(self.booking_response(row))

    def post_booking_action(self, data):
        action = str(data.get("action", ""))
        if action not in {"contact", "review", "book-again"}:
            return self.send_json({"ok": False, "error": "Choose a supported post-booking action."}, 422)
        message = str(data.get("message", "")).strip()[:1000]
        rating = data.get("rating")
        if action in {"contact", "review"} and not message:
            return self.send_json({"ok": False, "error": "Enter a message for this local action."}, 422)
        if action == "review":
            try:
                rating = int(rating)
            except (TypeError, ValueError):
                rating = 0
            if not 1 <= rating <= 5:
                return self.send_json({"ok": False, "error": "Rating must be between 1 and 5."}, 422)
        else:
            rating = None
        with sqlite3.connect(DB) as con:
            con.row_factory = sqlite3.Row
            row = self.find_managed_booking(con, data)
            if not row:
                return self.send_json({"ok": False, "error": "Booking not found."}, 404)
            con.execute(
                "INSERT INTO local_booking_action(booking_id,action,message,rating) VALUES (?,?,?,?)",
                (row["id"], action, message, rating),
            )
        response = {"ok": True, "sandbox": True, "action": action,
                    "message": "Saved locally. Nothing was sent to the venue."}
        if action == "book-again":
            response["selection"] = self.booking_response(row)
            response["return_path"] = "/book"
        return self.send_json(response, 201)

    def history_response(self, row):
        response = self.booking_response(row)
        response.update({
            "detail_path": f"/account/bookings#{row['confirmation_code']}",
            "can_edit": row["status"] == "confirmed",
            "can_cancel": row["status"] == "confirmed",
        })
        return response

    def save_draft(self, kind, data):
        required = DRAFT_FIELDS.get(kind)
        if not required:
            return self.send_json({"ok": False, "error": "Unknown draft type."}, 404)
        clean = {key: str(data.get(key, "")).strip()[:2000] for key in required}
        missing = [key for key in required if not clean[key]]
        if missing:
            return self.send_json({"ok": False, "error": "Complete every required field.", "fields": missing}, 422)
        if "email" in clean and not EMAIL.match(clean["email"]):
            return self.send_json({"ok": False, "error": "Enter a valid email address.", "fields": ["email"]}, 422)
        if kind in {"team-building", "celebration"}:
            try:
                count = int(clean["max_players"] if kind == "team-building" else clean["party_size"])
            except ValueError:
                count = 0
            if not 2 <= count <= 200:
                return self.send_json({"ok": False, "error": "Group size must be between 2 and 200."}, 422)
        token = fingerprint(kind, clean)
        try:
            with sqlite3.connect(DB) as con:
                con.execute("INSERT INTO local_draft(kind,fingerprint,payload_json) VALUES (?,?,?)", (kind, token, canonical(clean)))
        except sqlite3.IntegrityError:
            return self.send_json({"ok": False, "error": "This identical local draft already exists."}, 409)
        return self.send_json({"ok": True, "status": "draft", "message": "Saved locally as a draft. Nothing was sent."}, 201)

    def save_gift_plan(self, data):
        location = str(data.get("location", "")).strip()
        recipient = str(data.get("recipient_name", "")).strip()[:200]
        try:
            amount = int(data.get("amount_cents", 0))
        except (TypeError, ValueError):
            amount = 0
        if not location or amount not in {2500, 5000, 7500, 10000, 15000, 20000}:
            return self.send_json({"ok": False, "error": "Choose a location and supported gift amount."}, 422)
        token = fingerprint("gift-card-plan", {"location": location, "amount_cents": amount, "recipient_name": recipient})
        try:
            with sqlite3.connect(DB) as con:
                con.execute("INSERT INTO gift_card_plan(fingerprint,location,amount_cents,recipient_name) VALUES (?,?,?,?)", (token, location, amount, recipient))
        except sqlite3.IntegrityError:
            return self.send_json({"ok": False, "error": "This identical gift-card plan already exists."}, 409)
        return self.send_json({"ok": True, "status": "review", "message": "Local review plan saved. No gift card was issued and no payment was taken."}, 201)

    def send_json(self, value, status=200, headers=None):
        body = json.dumps(value).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Cache-Control", "no-store")
        for name, header_value in (headers or {}).items():
            self.send_header(name, header_value)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)


if __name__ == "__main__":
    port = int(os.environ.get("PORT", "8762"))
    ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()