File size: 28,199 Bytes
d3fa89e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import copy
import hashlib
import json
import secrets
import time
import uuid
from datetime import date, timedelta
from threading import RLock
from typing import Any
from pathlib import Path

from backend.catalog import MOVIES, SHOWTIMES, THEATERS
from backend.site_backend_integration import open_site_services


LOCK = RLock()
backend, auth = open_site_services()
NAV_CATALOG = json.loads((Path(__file__).parent / 'navigation-catalog.json').read_text(encoding='utf-8'))
NAV_PRODUCTS = {p['id']: p for p in NAV_CATALOG['products']}

SCHEMA = """
CREATE TABLE IF NOT EXISTS fandango_actor_state (
  actor_id TEXT PRIMARY KEY,
  state_json TEXT NOT NULL,
  updated_at INTEGER NOT NULL
);
"""


def initialize() -> None:
    with backend.lifecycle.connection(transaction=True) as connection:
        connection.executescript(SCHEMA)


initialize()


def navigation_state(actor_id: str) -> dict[str, Any]:
    value = state(actor_id)
    cart = []
    for line in value.get('fanstore_cart', []):
        product = NAV_PRODUCTS.get(line['product'])
        variant = next((v for v in product['variants'] if v['id'] == line['variant']), None) if product else None
        if variant:
            cart.append({**line, 'title': product['title'], 'image': product['image'],
                         'option': variant['title'], 'price': variant['price']})
    return {'cart': cart, 'subtotal': round(sum(v['price'] * v['quantity'] for v in cart), 2),
            'theaters': value.get('saved_theaters', []), 'library': value.get('streaming_library', [])}


def update_navigation(actor_id: str, action: dict[str, Any]) -> dict[str, Any]:
    with LOCK:
        value = state(actor_id)
        kind = action.get('kind')
        if kind == 'cart':
            product = NAV_PRODUCTS.get(action.get('product'))
            variant = next((v for v in product['variants'] if v['id'] == action.get('variant')), None) if product else None
            quantity = action.get('quantity')
            if not variant or type(quantity) is not int or not 0 <= quantity <= 99:
                raise ValueError('Choose a valid product, option and quantity from 0 to 99.')
            if quantity and not variant['available']:
                raise ValueError('This option is sold out in the captured catalog.')
            lines = [v for v in value.get('fanstore_cart', []) if v['variant'] != variant['id']]
            if quantity:
                lines.append({'product': product['id'], 'variant': variant['id'], 'quantity': quantity})
            value['fanstore_cart'] = lines
        elif kind in ('theaters', 'library'):
            key = 'saved_theaters' if kind == 'theaters' else 'streaming_library'
            allowed = NAV_CATALOG['theaters' if kind == 'theaters' else 'streaming']
            item = action.get('id')
            if item not in allowed:
                raise ValueError('This item is not available in the captured catalog.')
            saved = value.setdefault(key, [])
            if item in saved:
                saved.remove(item)
            else:
                saved.append(item)
        else:
            raise ValueError('Unknown navigation action.')
        _save_state(actor_id, value)
        return navigation_state(actor_id)


SHOWTIME_WINDOW_DAYS = 14


def upcoming_friday() -> str:
    today = date.today()
    delta = (4 - today.weekday()) % 7
    if delta == 0:
        delta = 7
    return (today + timedelta(days=delta)).isoformat()


def showtime_dates() -> list[dict[str, Any]]:
    """The selectable date strip on movie and theater pages."""
    today = date.today()
    rows = []
    for offset in range(SHOWTIME_WINDOW_DAYS):
        day = today + timedelta(days=offset)
        rows.append({
            "date": day.isoformat(),
            "weekday": "Today" if offset == 0 else ("Tomorrow" if offset == 1 else day.strftime("%a")),
            "month": day.strftime("%b").upper(),
            "day": day.day,
        })
    return rows


def valid_date(value: str) -> bool:
    return any(row["date"] == value for row in showtime_dates())


def _availability(base: int, theater_id: str, showtime_id: str, on_date: str) -> int:
    """Seats left varies by date so the strip is not a static repeat."""
    digest = hashlib.sha256(f"{theater_id}|{showtime_id}|{on_date}".encode()).digest()
    return max(4, base - digest[0] % max(1, base // 2))


THEATER_BY_ID = {row["id"]: row for row in THEATERS}

_SLOTS = {
    "matinee": ("1:15 PM", 795),
    "afternoon": ("4:05 PM", 965),
    "early": ("6:40 PM", 1120),
    "prime": ("7:30 PM", 1170),
    "late": ("9:15 PM", 1275),
    "night": ("10:20 PM", 1340),
}

_FORMAT_PRICE = {
    "Standard": 18.49,
    "RPX": 22.49,
    "IMAX": 25.99,
    "ScreenX": 22.99,
    "4DX": 26.49,
}


def _showtimes_for(theater_id: str, slots: list[tuple[str, str, int]], on_date: str) -> list[dict[str, Any]]:
    rows = []
    for slot, fmt, base in slots:
        time_label, minutes = _SLOTS[slot]
        showtime_id = f"{slot}-{fmt.lower().replace(' ', '-')}"
        rows.append({
            "id": showtime_id,
            "time": time_label,
            "minutes": minutes,
            "format": fmt,
            "price": _FORMAT_PRICE[fmt],
            "available": _availability(base, theater_id, showtime_id, on_date),
        })
    rows.sort(key=lambda row: row["minutes"])
    return rows


def _movie_theaters(movie_id: str, on_date: str) -> list[dict[str, Any]]:
    plan = SHOWTIMES.get(movie_id, {})
    rows = [
        {**THEATER_BY_ID[theater_id], "date": on_date, "showtimes": _showtimes_for(theater_id, slots, on_date)}
        for theater_id, slots in plan.items()
    ]
    rows.sort(key=lambda row: row["distance"])
    return rows


def catalog(on_date: str = "") -> list[dict[str, Any]]:
    on_date = on_date if on_date and valid_date(on_date) else upcoming_friday()
    return [
        {**movie, "theaters": _movie_theaters(movie["id"], on_date)}
        for movie in copy.deepcopy(MOVIES)
    ]


def theater_directory(on_date: str = "") -> list[dict[str, Any]]:
    """Every theater with the movies and showtimes playing there on a given date."""
    on_date = on_date if on_date and valid_date(on_date) else upcoming_friday()
    rows = []
    for theater in copy.deepcopy(THEATERS):
        playing = []
        for movie in MOVIES:
            slots = SHOWTIMES.get(movie["id"], {}).get(theater["id"])
            if not slots:
                continue
            playing.append({
                "id": movie["id"], "title": movie["title"], "rating": movie["rating"],
                "runtime": movie["runtime"], "genre": movie["genre"],
                "poster": movie["poster"], "year": movie["year"], "score": movie["score"],
                "showtimes": _showtimes_for(theater["id"], slots, on_date),
            })
        rows.append({**theater, "date": on_date, "movies": playing})
    rows.sort(key=lambda row: row["distance"])
    return rows


SEAT_ROWS = ["A", "B", "C", "D", "E", "F", "G", "H"]
SEATS_PER_ROW = 12


def sold_seats(theater_id: str, showtime_id: str) -> list[str]:
    """Deterministic per-showtime sold seats so the map is stable across reloads."""
    digest = hashlib.sha256(f"{theater_id}|{showtime_id}".encode()).digest()
    taken = {
        f"{SEAT_ROWS[digest[index] % len(SEAT_ROWS)]}{digest[index + 1] % SEATS_PER_ROW + 1}"
        for index in range(0, 24, 2)
    }
    return sorted(taken)


def new_actor() -> str:
    return "moviegoer_" + secrets.token_urlsafe(18)


def account_actor(account: dict[str, Any]) -> str:
    # This server-only namespace is never accepted from an actor cookie.
    return "account:" + str(account["subject_id"])


def claim_registration_state(guest: str, account: dict[str, Any]) -> None:
    """Move this guest's state to their newly created account exactly once."""
    if not guest.startswith("moviegoer_"):
        return
    owner = account_actor(account)
    with LOCK, backend.lifecycle.connection(transaction=True) as connection:
        if connection.execute("SELECT 1 FROM fandango_actor_state WHERE actor_id=?", (owner,)).fetchone():
            return
        connection.execute("UPDATE fandango_actor_state SET actor_id=? WHERE actor_id=?", (owner, guest))


def offers() -> list[dict[str, Any]]:
    """The rotating promo band above the fold, built from the captured lineup."""
    now_playing = [row for row in MOVIES if row["status"] == "now-playing"]
    coming_soon = [row for row in MOVIES if row["status"] == "coming-soon"]
    templates = [
        ("Buy a ticket to {title}", "Join FanClub with your ticket order to get 2 free tickets to use later."),
        ("Pre-order {title} now", "Save $5 when you buy your ticket before opening weekend."),
        ("See {title} in a premium format", "ScreenX, 4DX and IMAX auditoriums are bookable at checkout."),
        ("{title} is now playing", "Reserve seats at a theater near New York, NY."),
    ]
    picks = (now_playing[:2] + coming_soon[:1] + now_playing[2:3])
    rows = []
    for index, movie in enumerate(picks):
        headline, detail = templates[index % len(templates)]
        rows.append({
            "id": f"offer-{movie['id']}",
            "movie_id": movie["id"],
            "headline": headline.format(title=movie["title"]),
            "detail": detail + " Captured source promotion; discounts and rewards are not applied to local simulated bookings.",
        })
    return rows


def featured_thriller() -> dict[str, Any]:
    """The ClawBench task targets a currently showing thriller at Regal Union Square."""
    return next(
        row for row in MOVIES
        if row["status"] == "now-playing"
        and "Suspense/Thriller" in (row.get("genres") or [])
        and "regal-union-square" in SHOWTIMES.get(row["id"], {})
    )


def _seed_booking() -> dict[str, Any]:
    movie = featured_thriller()
    theater = THEATER_BY_ID["regal-union-square"]
    slot, fmt, _ = SHOWTIMES[movie["id"]]["regal-union-square"][2]
    time_label, _ = _SLOTS[slot]
    unit = _FORMAT_PRICE[fmt]
    subtotal = round(unit * 3, 2)
    fees = round(2.29 * 3, 2)
    return {
        "id": "FDG-SEED-2048",
        "status": "Upcoming",
        "movie": movie["title"],
        "genre": movie["genre"],
        "theater": theater["name"],
        "location": theater["location"],
        "date": upcoming_friday(),
        "time": time_label,
        "format": fmt,
        "tickets": 3,
        "seats": ["E5", "E6", "E7"],
        "total": round(subtotal + fees + (subtotal + fees) * 0.08875, 2),
        "contact_status": None,
        "review": None,
    }


def _new_state() -> dict[str, Any]:
    return {
        "favorites": [],
        "selection": {},
        "bookings": [_seed_booking()],
        "profile": None,
    }


def state(actor: str) -> dict[str, Any]:
    with LOCK:
        with backend.lifecycle.connection(transaction=True) as connection:
            row = connection.execute("SELECT state_json FROM fandango_actor_state WHERE actor_id=?", (actor,)).fetchone()
            if row:
                return json.loads(str(row["state_json"]))
            value = _new_state()
            connection.execute(
                "INSERT INTO fandango_actor_state(actor_id,state_json,updated_at) VALUES(?,?,?)",
                (actor, json.dumps(value, separators=(",", ":")), int(time.time())),
            )
            return value


def _save_state(actor: str, value: dict[str, Any], connection=None) -> None:
    if connection is None:
        with backend.lifecycle.connection(transaction=True) as transaction:
            _save_state(actor, value, transaction)
        return
    connection.execute(
        "INSERT INTO fandango_actor_state(actor_id,state_json,updated_at) VALUES(?,?,?) ON CONFLICT(actor_id) DO UPDATE SET state_json=excluded.state_json,updated_at=excluded.updated_at",
        (actor, json.dumps(value, separators=(",", ":")), int(time.time())),
    )


def _booked_seats(selection: dict[str, Any], connection=None, *, exclude_id: str | None = None) -> set[str]:
    """Read durable bookings, including pre-upgrade orders, for this screening.

    Display names/time/format are the immutable screening fields that older
    orders already store. The per-actor demo order is not a real reservation.
    A caller making a reservation must hold the same BEGIN IMMEDIATE transaction
    across this read and its order write, not just the process-local LOCK.
    """
    if connection is None:
        with backend.lifecycle.connection() as reader:
            return _booked_seats(selection, reader, exclude_id=exclude_id)
    fields = ("movie", "theater", "date", "time", "format")
    seats: set[str] = set()
    for row in connection.execute("SELECT state_json FROM fandango_actor_state"):
        for booking in json.loads(row["state_json"]).get("bookings", []):
            if booking["id"] in ("FDG-SEED-2048", exclude_id) or booking["status"] == "Cancelled":
                continue
            if all(booking.get(field) == selection.get(field) for field in fields):
                seats.update(booking["seats"])
    return seats


def ensure_auth_session(token: str | None) -> tuple[str, dict[str, Any]]:
    return auth.ensure_session(token)


def resolve_account(token: str | None) -> dict[str, Any] | None:
    return auth.resolve_session(token)


def bootstrap(actor: str, account: dict[str, Any] | None = None) -> dict[str, Any]:
    with LOCK:
        current = state(actor)
        selection = current["selection"]
        if selection:
            selection["sold_seats"] = sorted(set(sold_seats(selection["theater_id"], selection["showtime_id"])) | _booked_seats(selection))
        return {
            "movies": catalog(),
            "theaters": copy.deepcopy(THEATERS),
            "genres": genres(),
            "dates": showtime_dates(),
            "featured": {k: featured_thriller()[k] for k in ("id", "title", "poster")},
            "offers": offers(),
            "friday": upcoming_friday(),
            **copy.deepcopy(current),
            "profile": account,
        }


def genres() -> list[str]:
    """Every genre a source movie is tagged with, not just its primary one."""
    return sorted({name for movie in MOVIES for name in movie.get("genres") or [movie["genre"]]})


def search(query: str = "", genre: str = "", sort: str = "rating", max_price: float | None = None,
           service: str = "", status: str = "", theater: str = "") -> list[dict[str, Any]]:
    rows = copy.deepcopy(catalog())
    q = query.strip().lower()
    if q:
        rows = [
            row for row in rows
            if q in row["title"].lower() or q in row["synopsis"].lower()
            or any(q in name.lower() for name in row.get("genres") or [row["genre"]])
            or any(q in item["name"].lower() for item in row["theaters"])
        ]
    if status:
        rows = [row for row in rows if row["status"] == status]
    if theater:
        rows = [row for row in rows if any(item["id"] == theater for item in row["theaters"])]
    if genre:
        wanted = genre.lower()
        rows = [row for row in rows
                if wanted in {name.lower() for name in row.get("genres") or [row["genre"]]}]
    if max_price is not None:
        rows = [row for row in rows if any(show["price"] <= max_price for theater in row["theaters"] for show in theater["showtimes"])]
    if service:
        rows = [row for row in rows if any(service in theater["services"] for theater in row["theaters"])]
    if sort == "title":
        rows.sort(key=lambda row: row["title"])
    elif sort == "price":
        rows.sort(key=lambda row: min([show["price"] for theater in row["theaters"] for show in theater["showtimes"]] or [999]))
    else:
        rows.sort(key=lambda row: row["score"], reverse=True)
    return rows


def movie(movie_id: str, on_date: str = "") -> dict[str, Any] | None:
    return next((row for row in catalog(on_date) if row["id"] == movie_id), None)


def toggle_favorite(actor: str, movie_id: str) -> dict[str, Any]:
    if not movie(movie_id):
        raise KeyError(movie_id)
    with LOCK:
        current = state(actor)
        favorites = current["favorites"]
        if movie_id in favorites:
            favorites.remove(movie_id)
            saved = False
        else:
            favorites.append(movie_id)
            saved = True
        _save_state(actor, current)
        return {"saved": saved, "favorites": copy.deepcopy(favorites)}


def select_showtime(actor: str, movie_id: str, theater_id: str, showtime_id: str, selected_date: str) -> dict[str, Any]:
    if not valid_date(selected_date):
        raise ValueError("Choose a date within the next two weeks")
    row = movie(movie_id, selected_date)
    if not row:
        raise ValueError("Movie not found")
    theater = next((item for item in row["theaters"] if item["id"] == theater_id), None)
    showtime = next((item for item in theater["showtimes"] if item["id"] == showtime_id), None) if theater else None
    if not theater or not showtime:
        raise ValueError("Showtime not found")
    with LOCK:
        current = state(actor)
        selection = {
            "movie_id": movie_id,
            "movie": row["title"],
            "genre": row["genre"],
            "theater_id": theater_id,
            "theater": theater["name"],
            "location": theater["location"],
            "date": selected_date,
            "showtime_id": showtime_id,
            "time": showtime["time"],
            "format": showtime["format"],
            "unit_price": showtime["price"],
            "ticket_count": 0,
            "ticket_types": {},
            "seats": [],
            "sold_seats": sold_seats(theater_id, showtime_id),
            "seat_rows": SEAT_ROWS,
            "seats_per_row": SEATS_PER_ROW,
        }
        selection["sold_seats"] = sorted(set(selection["sold_seats"]) | _booked_seats(selection))
        current["selection"] = selection
        _save_state(actor, current)
        return copy.deepcopy(selection)


def _review_inputs(selection: dict[str, Any]) -> dict[str, Any]:
    return {key: copy.deepcopy(selection.get(key)) for key in (
        "movie_id", "theater_id", "showtime_id", "date", "unit_price",
        "ticket_count", "ticket_types", "seats",
    )}


def _invalidate_review(selection: dict[str, Any]) -> None:
    for key in ("subtotal", "fees", "tax", "total", "payment_adapter", "is_simulation", "reviewed_selection"):
        selection.pop(key, None)


def set_tickets(actor: str, adults: int, children: int = 0, seniors: int = 0) -> dict[str, Any]:
    if any(type(value) is not int or value < 0 or value > 8 for value in (adults, children, seniors)):
        raise ValueError("Ticket quantities must be whole numbers from 0 to 8")
    count = adults + children + seniors
    if count < 1 or count > 8:
        raise ValueError("Choose between 1 and 8 tickets")
    with LOCK:
        current = state(actor)
        selection = current["selection"]
        if not selection:
            raise ValueError("Select a showtime first")
        selection["ticket_count"] = count
        selection["ticket_types"] = {"Adult": adults, "Child": children, "Senior": seniors}
        selection["seats"] = []
        _invalidate_review(selection)
        _save_state(actor, current)
        return copy.deepcopy(selection)


def set_seats(actor: str, seats: list[str]) -> dict[str, Any]:
    with LOCK:
        current = state(actor)
        selection = current["selection"]
        if not selection or not selection.get("ticket_count"):
            raise ValueError("Select a showtime and tickets first")
        if not isinstance(seats, list) or not seats or any(not isinstance(seat, str) for seat in seats):
            raise ValueError("Select one seat for each ticket")
        if len(seats) != selection.get("ticket_count", 0):
            raise ValueError("Select one seat for each ticket")
        valid_seats = {f"{row}{number}" for row in SEAT_ROWS for number in range(1, SEATS_PER_ROW + 1)}
        if any(seat not in valid_seats for seat in seats):
            raise ValueError("Choose seats from the displayed seat map")
        parsed = [(seat[0], int(seat[1:])) for seat in seats if len(seat) >= 2]
        if len(parsed) != len(seats) or len({seat for seat in seats}) != len(seats):
            raise ValueError("Seats must be unique")
        taken = set(sold_seats(selection["theater_id"], selection["showtime_id"])) | _booked_seats(selection)
        conflict = [seat for seat in seats if seat in taken]
        if conflict:
            raise ValueError(f"Seat {', '.join(conflict)} is already sold for this showtime")
        if len({row for row, _ in parsed}) != 1:
            raise ValueError("Choose adjacent seats in one row")
        numbers = sorted(number for _, number in parsed)
        if numbers != list(range(numbers[0], numbers[0] + len(numbers))):
            raise ValueError("Choose adjacent seats")
        row_letter = parsed[0][0]
        selection["seats"] = [f"{row_letter}{number}" for number in numbers]
        _invalidate_review(selection)
        _save_state(actor, current)
        return copy.deepcopy(selection)


def review(actor: str, email: str, postal_code: str) -> dict[str, Any]:
    with LOCK:
        current = state(actor)
        selection = current["selection"]
        if not email or "@" not in email:
            raise ValueError("Enter a valid email")
        if len(postal_code.strip()) < 5:
            raise ValueError("Enter a billing ZIP or postal code")
        if not selection.get("seats"):
            raise ValueError("Select seats before review")
        subtotal = round(selection["unit_price"] * selection["ticket_count"], 2)
        fees = round(2.29 * selection["ticket_count"], 2)
        tax = round((subtotal + fees) * 0.08875, 2)
        total = round(subtotal + fees + tax, 2)
        selection["contact_email"] = email.strip().lower()
        selection["billing_postal_code"] = postal_code.strip()
        selection["subtotal"] = subtotal
        selection["fees"] = fees
        selection["tax"] = tax
        selection["total"] = total
        selection["payment_adapter"] = "local-sandbox"
        selection["is_simulation"] = True
        selection["reviewed_selection"] = _review_inputs(selection)
        _save_state(actor, current)
        return copy.deepcopy(selection)


def confirm(actor: str) -> dict[str, Any]:
    # BEGIN IMMEDIATE serializes conflict check + order write across processes.
    with LOCK, backend.lifecycle.connection(transaction=True) as connection:
        row = connection.execute("SELECT state_json FROM fandango_actor_state WHERE actor_id=?", (actor,)).fetchone()
        current = json.loads(row["state_json"]) if row else _new_state()
        selection = current["selection"]
        if not selection.get("total") or selection.get("reviewed_selection") != _review_inputs(selection):
            raise ValueError("Review the booking first")
        if not selection.get("seats") or len(selection["seats"]) != selection.get("ticket_count"):
            raise ValueError("Select one seat for each ticket and review the booking again")
        conflict = sorted(set(selection["seats"]) & _booked_seats(selection, connection))
        if conflict:
            raise ValueError(f"Seat {', '.join(conflict)} is already sold for this showtime")
        booking = {
            "id": f"FDG-{uuid.uuid4().hex[:8].upper()}",
            "status": "Confirmed (Local Simulation)",
            "movie": selection["movie"],
            "genre": selection["genre"],
            "theater": selection["theater"],
            "location": selection["location"],
            "date": selection["date"],
            "time": selection["time"],
            "format": selection["format"],
            "tickets": selection["ticket_count"],
            "seats": copy.deepcopy(selection["seats"]),
            "total": selection["total"],
            "contact_status": None,
            "review": None,
        }
        current["bookings"].insert(0, booking)
        current["selection"] = {}
        _save_state(actor, current, connection)
        return copy.deepcopy(booking)


def update_booking(actor: str, booking_id: str, action: str, value: Any = None) -> dict[str, Any]:
    with LOCK, backend.lifecycle.connection(transaction=True) as connection:
        row = connection.execute("SELECT state_json FROM fandango_actor_state WHERE actor_id=?", (actor,)).fetchone()
        current = json.loads(row["state_json"]) if row else _new_state()
        booking = next((row for row in current["bookings"] if row["id"] == booking_id), None)
        if not booking:
            raise KeyError(booking_id)
        if action == "cancel":
            booking["status"] = "Cancelled"
        elif action == "reschedule":
            if booking["status"] == "Cancelled":
                raise ValueError("Cancelled bookings cannot be rescheduled; book again instead")
            if not isinstance(value, str) or not valid_date(value):
                raise ValueError("Choose an available showtime date")
            target = {**booking, "date": value}
            conflict = sorted(set(booking["seats"]) & _booked_seats(target, connection, exclude_id=booking_id))
            if conflict:
                raise ValueError(f"Seat {', '.join(conflict)} is already sold for this showtime")
            booking["date"] = target["date"]
            booking["status"] = "Rescheduled"
        elif action == "contact":
            booking["contact_status"] = "Local message saved — nothing was sent"
        elif action == "review":
            booking["review"] = str(value or "5-star local review")
        elif action == "book-again":
            target = next((row for row in MOVIES if row["title"] == booking["movie"]), featured_thriller())
            theater_id = next(iter(SHOWTIMES.get(target["id"], {})), "regal-union-square")
            slot, fmt, _ = SHOWTIMES[target["id"]][theater_id][0]
            time_label, _ = _SLOTS[slot]
            theater = THEATER_BY_ID[theater_id]
            current["selection"] = {
                "movie_id": target["id"], "movie": target["title"], "genre": target["genre"],
                "theater_id": theater_id, "theater": theater["name"], "location": theater["location"],
                "date": upcoming_friday(),
                "showtime_id": f"{slot}-{fmt.lower().replace(' ', '-')}",
                "time": time_label, "format": fmt, "unit_price": _FORMAT_PRICE[fmt],
                "ticket_count": booking["tickets"], "ticket_types": {"Adult": booking["tickets"]}, "seats": [],
                "sold_seats": sold_seats(theater_id, f"{slot}-{fmt.lower().replace(' ', '-')}"),
                "seat_rows": SEAT_ROWS, "seats_per_row": SEATS_PER_ROW,
            }
        else:
            raise ValueError("Unknown booking action")
        _save_state(actor, current, connection)
        return {"booking": copy.deepcopy(booking), "selection": copy.deepcopy(current["selection"])}


def register(display_name: str, email: str, password: str) -> dict[str, Any]:
    details = auth.validate_registration_details(email=email, display_name=display_name, password=password)
    if auth.account_exists(details["email"]):
        raise ValueError("An account already exists for this email")
    subject = "moviegoer_" + hashlib.sha256(details["email"].encode()).hexdigest()[:20]
    auth.seed_account(subject_id=subject, email=details["email"], display_name=details["display_name"], password=details["password"], email_verified=True)
    return {"subject_id": subject, "display_name": details["display_name"], "email_normalized": details["email"]}


def login(session_token: str, email: str, password: str) -> dict[str, Any]:
    return auth.sign_in(session_token, email=email, password=password)


def logout(session_token: str | None) -> None:
    auth.sign_out(session_token)


def reset() -> None:
    def site_reset(connection):
        connection.execute("DELETE FROM fandango_actor_state")
    auth.reset_site_state(site_reset=site_reset, seed_accounts=[])