File size: 23,968 Bytes
267266e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Fast F1 replay streamer for frontend/backend integration testing.



Goals:

- Do NOT hit unavailable 2026 FastF1 archives by default.

- Use a stable historical source session (2024 by default).

- Build a compact local JSON replay cache once, then reuse it on later runs.

- Auto-start the FastAPI backend when needed.

- Stream lap-by-lap data quickly to the frontend/backend.

- Exit cleanly after the replay instead of hanging forever.



Typical usage:

    python fast_replay.py --gp Monza --laps 3

    python fast_replay.py --gp Bahrain --laps 10

    python fast_replay.py --gp Monza --laps 5 --interval 0

    python fast_replay.py --gp Monza --refresh-cache

"""

from __future__ import annotations

import argparse
import inspect
import json
import os
import re
import subprocess
import sys
import time
import urllib.request
from pathlib import Path
from typing import Any


PROJECT_ROOT = Path(__file__).resolve().parent
TESTING_DIR = PROJECT_ROOT / "testing_pipeline"
TEST_ENV_PYTHON = TESTING_DIR / ".venv" / "Scripts" / "python.exe"
BACKEND_ENV_PYTHON = PROJECT_ROOT / ".venv" / "Scripts" / "python.exe"
REPLAY_CACHE_DIR = TESTING_DIR / ".cache" / "replays"
FASTF1_CACHE_DIR = TESTING_DIR / ".cache" / "fastf1"
REENTRY_FLAG = "F1_REPLAY_TEST_ENV"


# This is only a frontend/demo roster.
# It is intentionally independent from the historical source session.
TEST_GRID = [
    {"DriverNumber": 1, "Driver": "VER", "FullName": "Max Verstappen", "TeamName": "Red Bull Racing"},
    {"DriverNumber": 4, "Driver": "NOR", "FullName": "Lando Norris", "TeamName": "McLaren"},
    {"DriverNumber": 81, "Driver": "PIA", "FullName": "Oscar Piastri", "TeamName": "McLaren"},
    {"DriverNumber": 16, "Driver": "LEC", "FullName": "Charles Leclerc", "TeamName": "Ferrari"},
    {"DriverNumber": 44, "Driver": "HAM", "FullName": "Lewis Hamilton", "TeamName": "Ferrari"},
    {"DriverNumber": 63, "Driver": "RUS", "FullName": "George Russell", "TeamName": "Mercedes"},
    {"DriverNumber": 12, "Driver": "ANT", "FullName": "Andrea Kimi Antonelli", "TeamName": "Mercedes"},
    {"DriverNumber": 55, "Driver": "SAI", "FullName": "Carlos Sainz", "TeamName": "Williams"},
    {"DriverNumber": 23, "Driver": "ALB", "FullName": "Alexander Albon", "TeamName": "Williams"},
    {"DriverNumber": 14, "Driver": "ALO", "FullName": "Fernando Alonso", "TeamName": "Aston Martin"},
    {"DriverNumber": 18, "Driver": "STR", "FullName": "Lance Stroll", "TeamName": "Aston Martin"},
    {"DriverNumber": 10, "Driver": "GAS", "FullName": "Pierre Gasly", "TeamName": "Alpine"},
    {"DriverNumber": 7, "Driver": "DOO", "FullName": "Jack Doohan", "TeamName": "Alpine"},
    {"DriverNumber": 22, "Driver": "TSU", "FullName": "Yuki Tsunoda", "TeamName": "RB"},
    {"DriverNumber": 30, "Driver": "LAW", "FullName": "Liam Lawson", "TeamName": "RB"},
    {"DriverNumber": 27, "Driver": "HUL", "FullName": "Nico Hulkenberg", "TeamName": "Kick Sauber"},
    {"DriverNumber": 5, "Driver": "BOR", "FullName": "Gabriel Bortoleto", "TeamName": "Kick Sauber"},
    {"DriverNumber": 31, "Driver": "OCO", "FullName": "Esteban Ocon", "TeamName": "Haas"},
    {"DriverNumber": 87, "Driver": "BEA", "FullName": "Oliver Bearman", "TeamName": "Haas"},
    {"DriverNumber": 11, "Driver": "PER", "FullName": "Sergio Perez", "TeamName": "Red Bull Racing"},
]


DEFAULT_WEATHER = {
    "AirTemp": 27.5,
    "TrackTemp": 39.2,
    "Rainfall": 0,
    "Humidity": 48.0,
    "Pressure": 1012.0,
    "WindSpeed": 7.5,
    "WindDirection": 110.0,
}


def _safe_float(value: Any, default: float) -> float:
    try:
        if value is None:
            return default
        value = float(value)
        if value != value:  # NaN
            return default
        return value
    except (TypeError, ValueError):
        return default


def _safe_int(value: Any, default: int = 1) -> int:
    try:
        if value is None:
            return default
        value = float(value)
        if value != value:
            return default
        return int(value)
    except (TypeError, ValueError):
        return default


def _slug(text: str) -> str:
    return re.sub(r"[^a-zA-Z0-9_-]+", "_", text.strip()).strip("_") or "race"


def _cache_path(source_year: int, source_gp: str) -> Path:
    return REPLAY_CACHE_DIR / f"{source_year}_{_slug(source_gp)}.json"


def _request_json(

    method: str,

    url: str,

    data: dict[str, Any] | list[Any] | None = None,

    timeout: float = 3.0,

) -> dict[str, Any] | None:
    body = None
    headers = {"Accept": "application/json"}

    if data is not None:
        body = json.dumps(data).encode("utf-8")
        headers["Content-Type"] = "application/json"

    request = urllib.request.Request(
        url,
        data=body,
        headers=headers,
        method=method,
    )

    try:
        with urllib.request.urlopen(request, timeout=timeout) as response:
            raw = response.read()
            if not raw:
                return {}
            return json.loads(raw.decode("utf-8"))
    except Exception:
        return None


def _get_json(url: str, timeout: float = 2.0) -> dict[str, Any] | None:
    return _request_json("GET", url, timeout=timeout)


def _post_json(

    url: str,

    data: dict[str, Any] | list[Any],

    timeout: float = 3.0,

) -> dict[str, Any] | None:
    return _request_json("POST", url, data=data, timeout=timeout)


def _backend_python() -> str:
    if BACKEND_ENV_PYTHON.is_file():
        return str(BACKEND_ENV_PYTHON)
    return sys.executable


def _ensure_backend_running(

    backend_url: str,

    auto_start: bool = True,

) -> subprocess.Popen[Any] | None:
    health = _get_json(f"{backend_url}/health", timeout=1.0)
    if health and health.get("status") in {"ok", "degraded"}:
        print(f"[Backend] Connected: {backend_url}")
        return None

    if not auto_start:
        raise RuntimeError(
            f"Backend is not running at {backend_url}. "
            "Start it manually or remove --no-auto-backend."
        )

    print(f"[Backend] Not running. Starting FastAPI at {backend_url}...")

    creationflags = 0
    if os.name == "nt" and hasattr(subprocess, "CREATE_NEW_PROCESS_GROUP"):
        creationflags = subprocess.CREATE_NEW_PROCESS_GROUP

    process = subprocess.Popen(
        [
            _backend_python(),
            "-m",
            "uvicorn",
            "app.main:app",
            "--host",
            "127.0.0.1",
            "--port",
            "8000",
        ],
        cwd=PROJECT_ROOT,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
        creationflags=creationflags,
    )

    # Fast polling; no long 15-second retry loop.
    deadline = time.monotonic() + 12.0
    while time.monotonic() < deadline:
        health = _get_json(f"{backend_url}/health", timeout=0.8)
        if health and health.get("status") in {"ok", "degraded"}:
            print(f"[Backend] Started (PID {process.pid})")
            return process
        if process.poll() is not None:
            raise RuntimeError(
                "Backend process exited during startup. "
                "Run uvicorn manually once to inspect the backend error."
            )
        time.sleep(0.25)

    raise RuntimeError(
        f"Backend did not become healthy at {backend_url} within 12 seconds."
    )


def _fastf1_importable() -> bool:
    try:
        import fastf1  # noqa: F401
        return True
    except Exception:
        return False


def _reenter_test_env_if_needed() -> None:
    if _fastf1_importable():
        return

    if os.environ.get(REENTRY_FLAG):
        raise RuntimeError("FastF1 is not importable inside the testing environment.")

    if not TEST_ENV_PYTHON.is_file():
        raise RuntimeError(
            "FastF1 environment is missing.\n"
            "Create it with:\n"
            "  python -m venv testing_pipeline\\.venv\n"
            "  testing_pipeline\\.venv\\Scripts\\python -m pip install -r testing_pipeline\\requirements.txt"
        )

    env = os.environ.copy()
    env[REENTRY_FLAG] = "1"

    completed = subprocess.run(
        [str(TEST_ENV_PYTHON), str(Path(__file__).resolve()), *sys.argv[1:]],
        cwd=PROJECT_ROOT,
        env=env,
        check=False,
    )
    raise SystemExit(completed.returncode)


def _load_source_session(source_year: int, source_gp: str):
    import fastf1

    FASTF1_CACHE_DIR.mkdir(parents=True, exist_ok=True)
    fastf1.Cache.enable_cache(str(FASTF1_CACHE_DIR))

    print(f"[FastF1] Loading stable source: {source_year} {source_gp} Race")
    session = fastf1.get_session(source_year, source_gp, "R")

    # Keep the call compatible across FastF1 versions.
    # We intentionally do NOT load telemetry/weather/messages for this frontend test.
    supported = inspect.signature(session.load).parameters
    kwargs: dict[str, Any] = {}

    if "laps" in supported:
        kwargs["laps"] = True
    if "telemetry" in supported:
        kwargs["telemetry"] = False
    if "weather" in supported:
        kwargs["weather"] = False
    if "messages" in supported:
        kwargs["messages"] = False

    started = time.perf_counter()
    session.load(**kwargs)
    elapsed = time.perf_counter() - started

    if not hasattr(session, "laps") or session.laps.empty:
        raise RuntimeError(
            f"No lap data available for {source_year} {source_gp}."
        )

    print(f"[FastF1] Source loaded in {elapsed:.2f}s")
    return session


def _build_replay_cache(

    source_year: int,

    source_gp: str,

    cache_file: Path,

) -> dict[str, Any]:
    session = _load_source_session(source_year, source_gp)

    laps = session.laps
    source_drivers = [
        str(driver).strip().upper()
        for driver in laps["Driver"].dropna().unique().tolist()
        if str(driver).strip()
    ]

    if not source_drivers:
        raise RuntimeError("Source session contains no drivers.")

    # Stable source-driver -> demo-driver mapping.
    driver_map: dict[str, dict[str, Any]] = {}
    for index, source_driver in enumerate(source_drivers):
        driver_map[source_driver] = TEST_GRID[index % len(TEST_GRID)]

    max_lap = _safe_int(laps["LapNumber"].max(), 1)
    replay_laps: list[dict[str, Any]] = []

    # Group once. This avoids repeatedly filtering the full DataFrame for every lap.
    grouped = laps.groupby("LapNumber", sort=True)

    for lap_number_raw, frame in grouped:
        lap_number = _safe_int(lap_number_raw, 0)
        if lap_number <= 0:
            continue

        car_batch: list[dict[str, Any]] = []
        timing_batch: list[dict[str, Any]] = []

        for _, row in frame.iterrows():
            source_driver = str(row.get("Driver", "")).strip().upper()
            target = driver_map.get(source_driver)
            if target is None:
                continue

            position = max(1, _safe_int(row.get("Position"), 1))
            compound = str(row.get("Compound", "MEDIUM") or "MEDIUM").upper()
            tyre_life = _safe_float(row.get("TyreLife"), float(lap_number))
            speed_st = _safe_float(row.get("SpeedST"), 315.0)

            is_braking = (position % 3 == 0) and (lap_number % 2 == 0)
            rpm = 8400 if is_braking else max(9000, 11500 - position * 12)
            gear = 4 if is_braking else 8
            throttle = 0 if is_braking else 100
            brake = 85 if is_braking else 0
            drs = 1 if position > 1 and not is_braking else 0

            car_batch.append(
                {
                    "Driver": target["Driver"],
                    "DriverNumber": target["DriverNumber"],
                    "LapNumber": lap_number,
                    "Speed": speed_st,
                    "RPM": rpm,
                    "nGear": gear,
                    "Throttle": throttle,
                    "Brake": brake,
                    "DRS": drs,
                    "Compound": compound,
                    "TyreLife": tyre_life,
                    "Position": position,
                    **DEFAULT_WEATHER,
                }
            )

            timing_batch.append(
                {
                    "Driver": target["Driver"],
                    "DriverNumber": target["DriverNumber"],
                    "LapNumber": lap_number,
                    "Position": position,
                }
            )

        if car_batch and timing_batch:
            replay_laps.append(
                {
                    "lap": lap_number,
                    "car": car_batch,
                    "timing": timing_batch,
                }
            )

    replay = {
        "schema_version": 1,
        "source_year": source_year,
        "source_gp": source_gp,
        "source_max_lap": max_lap,
        "grid": TEST_GRID,
        "weather": DEFAULT_WEATHER,
        "laps": replay_laps,
    }

    cache_file.parent.mkdir(parents=True, exist_ok=True)
    temp_file = cache_file.with_suffix(".tmp")
    temp_file.write_text(
        json.dumps(replay, separators=(",", ":"), ensure_ascii=False),
        encoding="utf-8",
    )
    temp_file.replace(cache_file)

    print(
        f"[Cache] Built {cache_file.name}: "
        f"{len(replay_laps)} replay laps, {len(source_drivers)} source drivers"
    )

    return replay


def _load_or_build_replay(

    source_year: int,

    source_gp: str,

    refresh_cache: bool,

) -> dict[str, Any]:
    cache_file = _cache_path(source_year, source_gp)

    if cache_file.is_file() and not refresh_cache:
        started = time.perf_counter()
        replay = json.loads(cache_file.read_text(encoding="utf-8"))
        elapsed = time.perf_counter() - started
        print(f"[Cache] Loaded {cache_file.name} in {elapsed:.3f}s")
        return replay

    _reenter_test_env_if_needed()
    return _build_replay_cache(source_year, source_gp, cache_file)


def _leader_text(snapshot: dict[str, Any] | None) -> tuple[str, str]:
    if not snapshot:
        return "Calculating...", ""

    prediction = snapshot.get("prediction") or {}
    leaderboard = prediction.get("leaderboard") or []

    if not leaderboard:
        return "Calculating...", ""

    leader = leaderboard[0]
    probability = _safe_float(leader.get("normalized_probability"), 0.0) * 100
    leader_text = f"{leader.get('driver', '?')} ({probability:.1f}%)"
    top3 = ", ".join(
        f"P{i + 1}:{item.get('driver', '?')}"
        for i, item in enumerate(leaderboard[:3])
    )
    return leader_text, top3


def run_replay(

    *,

    display_year: int,

    display_gp: str,

    source_year: int,

    source_gp: str,

    max_laps: int | None,

    interval: float,

    backend_url: str,

    refresh_cache: bool,

    auto_backend: bool,

    snapshot_every: int,

    hold: bool,

    stop_backend_after: bool,

) -> int:
    replay = _load_or_build_replay(
        source_year=source_year,
        source_gp=source_gp,
        refresh_cache=refresh_cache,
    )

    backend_proc: subprocess.Popen[Any] | None = None

    try:
        backend_proc = _ensure_backend_running(
            backend_url=backend_url,
            auto_start=auto_backend,
        )

        available_laps = replay.get("laps") or []
        if not available_laps:
            raise RuntimeError("Replay cache contains no laps.")

        target_laps = len(available_laps)
        if max_laps is not None:
            target_laps = min(max(1, max_laps), target_laps)

        selected = available_laps[:target_laps]

        print()
        print("=" * 72)
        print(" FAST F1 FRONTEND/BACKEND REPLAY")
        print(f" Display race : {display_year} {display_gp}")
        print(f" Data source  : {source_year} {source_gp} historical race")
        print(f" Laps         : {target_laps}")
        print(f" Interval     : {interval:.2f}s")
        print(f" Backend      : {backend_url}")
        print("=" * 72)
        print()

        # Reset once.
        if _post_json(f"{backend_url}/live/reset", {}) is None:
            raise RuntimeError("Backend /live/reset request failed.")

        driver_records = [
            {
                "DriverNumber": d["DriverNumber"],
                "Driver": d["Driver"],
                "BroadcastName": d["FullName"],
                "TeamName": d["TeamName"],
            }
            for d in replay.get("grid", TEST_GRID)
        ]

        if _post_json(
            f"{backend_url}/live/feed",
            {"DriverList": driver_records},
        ) is None:
            raise RuntimeError("Failed to register driver list.")

        weather = replay.get("weather") or DEFAULT_WEATHER
        _post_json(
            f"{backend_url}/live/feed",
            {
                "WeatherData": [weather],
                "TrackStatus": [{"TrackStatus": "1"}],
                "LapCount": [{"CurrentLap": 0, "TotalLaps": target_laps}],
                "SessionStatus": [{"Status": "Started"}],
            },
        )

        _post_json(
            f"{backend_url}/live/feed",
            {
                "TimingData": [
                    {
                        "DriverNumber": d["DriverNumber"],
                        "Driver": d["Driver"],
                        "LapNumber": 0,
                    }
                    for d in driver_records
                ]
            },
        )

        replay_started = time.perf_counter()

        for index, lap_data in enumerate(selected, start=1):
            lap_number = index

            # Copy only because we need the displayed lap numbering to be contiguous
            # even if the source had any missing lap groups.
            car_batch = [dict(row, LapNumber=lap_number) for row in lap_data["car"]]
            timing_batch = [dict(row, LapNumber=lap_number) for row in lap_data["timing"]]

            payload = {
                "LapCount": [{"CurrentLap": lap_number, "TotalLaps": target_laps}],
                "CarData.z": car_batch,
                "TimingData": timing_batch,
            }

            if _post_json(f"{backend_url}/live/feed", payload) is None:
                print(f"[Warning] Lap {lap_number} feed failed")
                continue

            should_snapshot = (
                snapshot_every > 0
                and (
                    lap_number == 1
                    or lap_number == target_laps
                    or lap_number % snapshot_every == 0
                )
            )

            if should_snapshot:
                snapshot = _get_json(
                    f"{backend_url}/live/frontend",
                    timeout=1.5,
                )
                leader, top3 = _leader_text(snapshot)
                print(
                    f"[Lap {lap_number:>2}/{target_laps}] "
                    f"Leader: {leader:<18} Top 3: [{top3}]"
                )
            else:
                print(f"[Lap {lap_number:>2}/{target_laps}] streamed")

            if interval > 0:
                time.sleep(interval)

        _post_json(
            f"{backend_url}/live/feed",
            {"SessionStatus": [{"Status": "Finished"}]},
        )

        elapsed = time.perf_counter() - replay_started
        final_snapshot = _get_json(f"{backend_url}/live/frontend", timeout=2.0) or {}
        prediction = final_snapshot.get("prediction") or {}
        leaderboard = prediction.get("leaderboard") or []
        winner = prediction.get("final_predicted_winner")
        if not winner and leaderboard:
            winner = leaderboard[0].get("driver")

        print()
        print("=" * 72)
        print(" REPLAY FINISHED")
        print(f" Predicted winner : {winner or 'N/A'}")
        print(f" Stream time      : {elapsed:.2f}s")
        print(" Frontend         : http://localhost:5173")
        print("=" * 72)

        if hold:
            print("\n[Hold] Keeping this process alive. Press Ctrl+C to stop.")
            while True:
                time.sleep(1)

        return 0

    except KeyboardInterrupt:
        print("\n[Replay] Stopped by user.")
        return 130

    except Exception as exc:
        print(f"\n[Error] {exc}", file=sys.stderr)
        return 1

    finally:
        if stop_backend_after and backend_proc is not None:
            try:
                backend_proc.terminate()
            except Exception:
                pass


def _parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Fast local F1 replay streamer for frontend/backend integration testing."
        )
    )

    parser.add_argument(
        "--gp",
        default="Monza",
        help="Displayed/test Grand Prix name. Also used as source GP unless --source-gp is set.",
    )
    parser.add_argument(
        "--year",
        type=int,
        default=2026,
        help="Displayed/test season year (default: 2026).",
    )
    parser.add_argument(
        "--source-year",
        type=int,
        default=2024,
        help="Historical FastF1 source year (default: 2024).",
    )
    parser.add_argument(
        "--source-gp",
        default=None,
        help="Historical FastF1 source GP. Defaults to the value of --gp.",
    )
    parser.add_argument(
        "--laps",
        type=int,
        default=None,
        help="Number of laps to replay. Default: all cached source laps.",
    )
    parser.add_argument(
        "--interval",
        type=float,
        default=0.25,
        help="Seconds between streamed laps. Use 0 for maximum speed. Default: 0.25.",
    )
    parser.add_argument(
        "--backend-url",
        default="http://127.0.0.1:8000",
        help="Backend base URL.",
    )
    parser.add_argument(
        "--refresh-cache",
        action="store_true",
        help="Ignore local replay JSON and rebuild it from FastF1.",
    )
    parser.add_argument(
        "--no-auto-backend",
        action="store_true",
        help="Do not auto-start the FastAPI backend.",
    )
    parser.add_argument(
        "--snapshot-every",
        type=int,
        default=1,
        help="Read /live/frontend every N laps. Use 0 to disable snapshot polling.",
    )
    parser.add_argument(
        "--hold",
        action="store_true",
        help="Keep this replay process alive after the race finishes.",
    )
    parser.add_argument(
        "--stop-backend-after",
        action="store_true",
        help="Stop the backend only if this script started it.",
    )

    return parser.parse_args()


def main() -> int:
    args = _parse_args()

    if args.interval < 0:
        print("[Error] --interval cannot be negative.", file=sys.stderr)
        return 2

    if args.snapshot_every < 0:
        print("[Error] --snapshot-every cannot be negative.", file=sys.stderr)
        return 2

    source_gp = args.source_gp or args.gp

    return run_replay(
        display_year=args.year,
        display_gp=args.gp,
        source_year=args.source_year,
        source_gp=source_gp,
        max_laps=args.laps,
        interval=args.interval,
        backend_url=args.backend_url.rstrip("/"),
        refresh_cache=args.refresh_cache,
        auto_backend=not args.no_auto_backend,
        snapshot_every=args.snapshot_every,
        hold=args.hold,
        stop_backend_after=args.stop_backend_after,
    )


if __name__ == "__main__":
    raise SystemExit(main())