File size: 35,835 Bytes
fb678a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Fill fillable nulls in the packaged OpenF1 ML dataset from free sources.

Never overwrites a non-null OpenF1 (or previously filled) value.
Sources: TracingInsights session_laptimes.json, Jolpica driver nationalities,
and values copied from other sessions of the same driver.
"""
from __future__ import annotations

import json
import math
from collections import defaultdict
from pathlib import Path

import numpy as np
import pandas as pd

SRC_CACHE = Path("/workspace/openf1-dataset/tracinginsights_cache_store")
JCACHE = Path("/workspace/openf1-dataset/jolpica_cache_store")
HF = Path("/workspace/openf1-ml-hf")

NATIONALITY_TO_CODE = {
    "Argentine": "ARG",
    "Australian": "AUS",
    "Brazilian": "BRA",
    "British": "GBR",
    "Bulgarian": "BUL",
    "Canadian": "CAN",
    "Chinese": "CHN",
    "Danish": "DEN",
    "Dutch": "NED",
    "Estonian": "EST",
    "Finnish": "FIN",
    "French": "FRA",
    "German": "GER",
    "Italian": "ITA",
    "Japanese": "JPN",
    "Mexican": "MEX",
    "Monegasque": "MON",
    "New Zealander": "NZL",
    "Spanish": "ESP",
    "Swedish": "SWE",
    "Thai": "THA",
    "American": "USA",
}

TIMING_MAP = [
    ("lap_duration", "time"),
    ("duration_sector_1", "s1"),
    ("duration_sector_2", "s2"),
    ("duration_sector_3", "s3"),
    ("i1_speed", "vi1"),
    ("i2_speed", "vi2"),
    ("st_speed", "vst"),
]


def is_null(x) -> bool:
    if x is None or x == "" or x == "None":
        return True
    try:
        if isinstance(x, float) and math.isnan(x):
            return True
    except (TypeError, ValueError):
        pass
    return False


def to_float(x):
    if is_null(x):
        return np.nan
    try:
        return float(x)
    except (TypeError, ValueError):
        return np.nan


def to_int(x):
    if is_null(x):
        return pd.NA
    try:
        return int(float(x))
    except (TypeError, ValueError):
        return pd.NA


def parse_lsd(s):
    if is_null(s):
        return pd.NaT
    text = str(s).strip()
    if text.endswith("Z"):
        text = text[:-1] + "+00:00"
    if "+" not in text[10:] and not text.endswith("Z"):
        if "." in text:
            date, frac = text.split(".", 1)
            frac = "".join(ch for ch in frac if ch.isdigit())
            frac = (frac + "000000")[:6]
            text = f"{date}.{frac}+00:00"
        else:
            text = text + "+00:00"
    return pd.to_datetime(text, utc=True, errors="coerce")


def cache_path(year: int, event: str, session: str) -> Path:
    safe = event.replace("/", "_").replace(" ", "_")
    return SRC_CACHE / f"{year}_{safe}_{session}_session_laptimes.json"


def load_ti(year: int, event: str, session: str) -> pd.DataFrame:
    fn = cache_path(year, event, session)
    data = json.loads(fn.read_text())
    n = len(data["lap"])
    raw = pd.DataFrame({k: data[k] for k in data if isinstance(data[k], list) and len(data[k]) == n})
    out = pd.DataFrame({
        "driver_number": raw["dNum"].map(to_int).astype("Int64"),
        "lap_number": raw["lap"].map(to_int).astype("Int64"),
        "lap_duration": raw["time"].map(to_float) if "time" in raw else np.nan,
        "duration_sector_1": raw["s1"].map(to_float) if "s1" in raw else np.nan,
        "duration_sector_2": raw["s2"].map(to_float) if "s2" in raw else np.nan,
        "duration_sector_3": raw["s3"].map(to_float) if "s3" in raw else np.nan,
        "i1_speed": raw["vi1"].map(to_float) if "vi1" in raw else np.nan,
        "i2_speed": raw["vi2"].map(to_float) if "vi2" in raw else np.nan,
        "st_speed": raw["vst"].map(to_float) if "vst" in raw else np.nan,
        "date_start": raw["lSD"].map(parse_lsd) if "lSD" in raw else pd.NaT,
        "compound": raw["compound"].map(lambda x: None if is_null(x) else str(x)) if "compound" in raw else None,
        # FastF1/TI TyreLife is 1 higher than OpenF1 tyre_age = tyre_age_at_start + (lap - lap_start)
        "tyre_age": (
            raw["life"].map(to_int).astype("Int64") - 1
            if "life" in raw
            else pd.Series([pd.NA] * len(raw), dtype="Int64")
        ),
        "stint_number": raw["stint"].map(to_int).astype("Int64") if "stint" in raw else pd.Series([pd.NA] * len(raw), dtype="Int64"),
        "position": raw["pos"].map(to_int).astype("Int64") if "pos" in raw else pd.Series([pd.NA] * len(raw), dtype="Int64"),
        "is_deleted": raw["del"].map(lambda x: True if x is True or x == "True" or x == 1 else False) if "del" in raw else False,
        "is_pit_in_lap": raw["pin"].map(lambda x: not is_null(x)) if "pin" in raw else False,
        "is_pit_out_lap": raw["pout"].map(lambda x: not is_null(x)) if "pout" in raw else False,
        "air_temperature": raw["wAT"].map(to_float) if "wAT" in raw else np.nan,
        "track_temperature": raw["wTT"].map(to_float) if "wTT" in raw else np.nan,
        "humidity": raw["wH"].map(to_float) if "wH" in raw else np.nan,
        "rainfall": raw["wR"].map(lambda x: pd.NA if is_null(x) else int(bool(x))) if "wR" in raw else pd.Series([pd.NA] * len(raw), dtype="Int64"),
        "pressure": raw["wP"].map(to_float) if "wP" in raw else np.nan,
        "wind_speed": raw["wWS"].map(to_float) if "wWS" in raw else np.nan,
        "wind_direction": raw["wWD"].map(to_int).astype("Int64") if "wWD" in raw else pd.Series([pd.NA] * len(raw), dtype="Int64"),
        "weather_time": raw["wT"].map(to_float) if "wT" in raw else np.nan,
    })
    # drop rows without keys
    out = out.dropna(subset=["driver_number", "lap_number"])
    out["driver_number"] = out["driver_number"].astype(int)
    out["lap_number"] = out["lap_number"].astype(int)
    out = out.drop_duplicates(["driver_number", "lap_number"], keep="last")
    return out


def load_all_ti(sessions: pd.DataFrame) -> dict[int, pd.DataFrame]:
    out = {}
    for r in sessions.itertuples():
        ti = load_ti(int(r.year), r.meeting_name, r.session_name)
        ti["session_key"] = int(r.session_key)
        out[int(r.session_key)] = ti
    return out


def validate_overlap(laps: pd.DataFrame, ti_by_sk: dict) -> dict:
    stats = {}
    fields = [a for a, _ in TIMING_MAP] + ["date_start"]
    for field in fields:
        both_abs = []
        fillable = 0
        both_n = 0
        for sk, ti in ti_by_sk.items():
            of = laps[laps.session_key == sk][["driver_number", "lap_number", field]]
            m = of.merge(ti[["driver_number", "lap_number", field]], on=["driver_number", "lap_number"], how="inner", suffixes=("_of", "_ti"))
            both = m[m[f"{field}_of"].notna() & m[f"{field}_ti"].notna()]
            fillable += int((m[f"{field}_of"].isna() & m[f"{field}_ti"].notna()).sum())
            both_n += len(both)
            if field == "date_start" and len(both):
                both_abs.extend((both[f"{field}_of"] - both[f"{field}_ti"]).abs().dt.total_seconds().tolist())
            elif field != "date_start" and len(both):
                both_abs.extend((both[f"{field}_of"] - both[f"{field}_ti"]).abs().tolist())
        rec = {"overlap_n": both_n, "fillable_openf1_null_ti_present": fillable}
        if both_abs:
            s = pd.Series(both_abs)
            rec.update({
                "median_abs_error": float(s.median()),
                "p90_abs_error": float(s.quantile(0.9)),
                "max_abs_error": float(s.max()),
                "pct_within_0.2": float((s <= 0.2).mean() * 100),
                "pct_exact_0.001": float((s <= 0.001).mean() * 100),
            })
        stats[field] = rec
    # compound / tyre / pos
    for field, tif in [("compound", "compound"), ("tyre_age", "tyre_age"), ("position_at_lap", "position")]:
        pass
    return stats


def fill_series(target: pd.Series, donor: pd.Series) -> tuple[pd.Series, int]:
    """Fill nulls in target from donor; return (new_series, n_filled)."""
    mask = target.isna() & donor.notna()
    n = int(mask.sum())
    if n:
        target = target.copy()
        target[mask] = donor[mask]
    return target, n


def jolpica_codes() -> pd.DataFrame:
    rows = []
    for year in (2023, 2024, 2025, 2026):
        data = json.loads((JCACHE / f"drivers_{year}.json").read_text())
        for d in data["MRData"]["DriverTable"]["Drivers"]:
            nat = d.get("nationality")
            code = NATIONALITY_TO_CODE.get(nat)
            if not code:
                continue
            rows.append({
                "year": year,
                "name_acronym": d.get("code"),
                "permanent_number": int(d["permanentNumber"]) if d.get("permanentNumber") else pd.NA,
                "family_name": (d.get("familyName") or "").upper(),
                "given_name": d.get("givenName") or "",
                "country_code": code,
                "nationality": nat,
            })
    return pd.DataFrame(rows)


def fill_drivers(drv: pd.DataFrame, sessions: pd.DataFrame) -> tuple[pd.DataFrame, dict]:
    d = drv.copy()
    d = d.merge(sessions[["session_key", "year"]], on="session_key", how="left")
    report = {"country_code": {}, "headshot_url": {}}

    # Track original
    orig_cc = d["country_code"].copy()
    src = pd.Series(np.where(orig_cc.notna(), "openf1", None), index=d.index, dtype="object")

    # 1) same number + acronym
    have = d[d.country_code.notna()][["driver_number", "name_acronym", "country_code"]].drop_duplicates()
    # if multiple, they already agreed
    m = d[["driver_number", "name_acronym"]].merge(
        have.rename(columns={"country_code": "cc_fill"}),
        on=["driver_number", "name_acronym"],
        how="left",
    )
    mask = d.country_code.isna() & m.cc_fill.notna()
    d.loc[mask, "country_code"] = m.loc[mask, "cc_fill"].values
    src.loc[mask] = "openf1_other_session"
    report["country_code"]["openf1_other_session_same_number"] = int(mask.sum())

    # 2) same acronym (number changes: VER 1→3, NOR 4→1)
    have2 = d[d.country_code.notna()][["name_acronym", "country_code"]].drop_duplicates()
    # unique acronym -> code
    uniq = have2.groupby("name_acronym").country_code.nunique()
    ok = set(uniq[uniq == 1].index)
    have2 = have2[have2.name_acronym.isin(ok)].drop_duplicates("name_acronym")
    m2 = d[["name_acronym"]].merge(have2.rename(columns={"country_code": "cc_fill"}), on="name_acronym", how="left")
    mask = d.country_code.isna() & m2.cc_fill.notna()
    d.loc[mask, "country_code"] = m2.loc[mask, "cc_fill"].values
    src.loc[mask] = "openf1_other_session"
    report["country_code"]["openf1_other_session_same_acronym"] = int(mask.sum())

    # 3) Jolpica nationality
    jc = jolpica_codes()
    # prefer (year, acronym), then (year, number)
    by_ac = jc.dropna(subset=["name_acronym"]).drop_duplicates(["year", "name_acronym"])
    m3 = d.merge(
        by_ac[["year", "name_acronym", "country_code"]].rename(columns={"country_code": "cc_fill"}),
        on=["year", "name_acronym"],
        how="left",
    )
    mask = d.country_code.isna() & m3.cc_fill.notna()
    d.loc[mask, "country_code"] = m3.loc[mask, "cc_fill"].values
    src.loc[mask] = "jolpica"
    report["country_code"]["jolpica_year_acronym"] = int(mask.sum())

    by_num = jc.dropna(subset=["permanent_number"]).drop_duplicates(["year", "permanent_number"])
    by_num["permanent_number"] = by_num["permanent_number"].astype(int)
    m4 = d.merge(
        by_num[["year", "permanent_number", "country_code"]].rename(columns={"permanent_number": "driver_number", "country_code": "cc_fill"}),
        on=["year", "driver_number"],
        how="left",
    )
    mask = d.country_code.isna() & m4.cc_fill.notna()
    d.loc[mask, "country_code"] = m4.loc[mask, "cc_fill"].values
    src.loc[mask] = "jolpica"
    report["country_code"]["jolpica_year_number"] = int(mask.sum())

    report["country_code"]["still_null"] = int(d.country_code.isna().sum())
    report["country_code"]["still_null_identities"] = (
        d.loc[d.country_code.isna(), ["driver_number", "name_acronym", "full_name", "year"]]
        .drop_duplicates()
        .to_dict("records")
    )
    d["country_code_source"] = src

    # Headshots: other sessions only
    orig_h = d["headshot_url"].copy()
    hsrc = pd.Series(np.where(orig_h.notna(), "openf1", None), index=d.index, dtype="object")
    haveh = d[d.headshot_url.notna()][["driver_number", "name_acronym", "headshot_url"]].drop_duplicates(["driver_number", "name_acronym"])
    mh = d.merge(haveh.rename(columns={"headshot_url": "h_fill"}), on=["driver_number", "name_acronym"], how="left")
    mask = d.headshot_url.isna() & mh.h_fill.notna()
    d.loc[mask, "headshot_url"] = mh.loc[mask, "h_fill"].values
    hsrc.loc[mask] = "openf1_other_session"
    report["headshot_url"]["openf1_other_session_same_number"] = int(mask.sum())

    haveh2 = d[d.headshot_url.notna()][["name_acronym", "headshot_url"]].drop_duplicates("name_acronym")
    # if acronym maps to one url (or any), take first
    mh2 = d.merge(haveh2.rename(columns={"headshot_url": "h_fill"}), on="name_acronym", how="left")
    mask = d.headshot_url.isna() & mh2.h_fill.notna()
    d.loc[mask, "headshot_url"] = mh2.loc[mask, "h_fill"].values
    hsrc.loc[mask] = "openf1_other_session"
    report["headshot_url"]["openf1_other_session_same_acronym"] = int(mask.sum())
    report["headshot_url"]["still_null"] = int(d.headshot_url.isna().sum())
    d["headshot_url_source"] = hsrc

    # drop helper year if it wasn't in original drivers
    d = d.drop(columns=["year"])
    return d, report


def fill_from_ti(df: pd.DataFrame, ti_all: pd.DataFrame, fields: list[str], report: dict, prefix: str) -> pd.DataFrame:
    """Fill nulls in df[fields] from ti_all, same session/driver/lap. Add <field>_source."""
    keys = ["session_key", "driver_number", "lap_number"]
    donor = ti_all[keys + [c for c in fields if c in ti_all.columns]].copy()
    # disambiguate
    rename = {c: f"_ti_{c}" for c in fields if c in donor.columns}
    donor = donor.rename(columns=rename)
    merged = df.merge(donor, on=keys, how="left")
    for c in fields:
        tc = f"_ti_{c}"
        if tc not in merged.columns:
            continue
        if c not in merged.columns:
            continue
        src_col = f"{c}_source"
        if src_col not in merged.columns:
            merged[src_col] = np.where(merged[c].notna(), "openf1", None)
        else:
            merged.loc[merged[c].notna() & merged[src_col].isna(), src_col] = "openf1"
        mask = merged[c].isna() & merged[tc].notna()
        n = int(mask.sum())
        report[f"{prefix}_{c}"] = report.get(f"{prefix}_{c}", 0) + n
        if n:
            if c == "date_start" or "datetime" in str(merged[c].dtype):
                merged[c] = pd.to_datetime(merged[c], utc=True, errors="coerce")
                merged[tc] = pd.to_datetime(merged[tc], utc=True, errors="coerce")
                merged.loc[mask, c] = merged.loc[mask, tc]
            else:
                merged.loc[mask, c] = merged.loc[mask, tc].values
            merged.loc[mask, src_col] = "tracinginsights"
        if c == "date_start":
            merged[c] = pd.to_datetime(merged[c], utc=True, errors="coerce")
        merged = merged.drop(columns=[tc])
    return merged


def asof_fill_weather(ml: pd.DataFrame, weather: pd.DataFrame) -> tuple[pd.DataFrame, int]:
    wcols = [
        "air_temperature", "track_temperature", "humidity", "rainfall",
        "pressure", "wind_speed", "wind_direction",
    ]
    need = ml["date_start"].notna() & ml["air_temperature"].isna()
    if not need.any():
        return ml, 0
    w = weather.copy()
    w["_w_date"] = pd.to_datetime(w["date"], utc=True, errors="coerce")
    w = w.dropna(subset=["_w_date"]).sort_values("_w_date")
    right = w[["session_key", "_w_date"] + [c for c in wcols if c in w.columns]].rename(
        columns={c: f"_w_{c}" for c in wcols if c in w.columns}
    )
    take = ml.loc[need, ["session_key", "date_start"]].copy()
    take["date_start"] = pd.to_datetime(take["date_start"], utc=True, errors="coerce")
    take = take.dropna(subset=["date_start"]).sort_values("date_start")
    joined = pd.merge_asof(
        take,
        right,
        left_on="date_start",
        right_on="_w_date",
        by="session_key",
        direction="nearest",
    )
    idx = take.index
    filled_any = pd.Series(False, index=idx)
    for c in wcols:
        wc = f"_w_{c}"
        if wc not in joined.columns or c not in ml.columns:
            continue
        vals = pd.Series(joined[wc].to_numpy(), index=idx)
        mask = ml.loc[idx, c].isna() & vals.notna()
        if mask.any():
            ml.loc[idx[mask.to_numpy()], c] = vals.loc[mask].to_numpy()
            filled_any.loc[mask] = True
    n = int(filled_any.sum())
    if n:
        dates = pd.Series(joined["_w_date"].to_numpy(), index=idx)
        ml.loc[idx[filled_any.to_numpy()], "weather_date"] = dates.loc[filled_any].to_numpy()
        if "weather_source" not in ml.columns:
            ml["weather_source"] = np.where(ml["air_temperature"].notna(), "openf1", None)
        ml.loc[idx[filled_any.to_numpy()], "weather_source"] = "openf1_asof_after_date_fill"
    return ml, n


def asof_fill_position(ml: pd.DataFrame, position: pd.DataFrame) -> tuple[pd.DataFrame, int]:
    need = ml["date_start"].notna() & ml["position_at_lap"].isna()
    if not need.any():
        return ml, 0
    p = position.copy()
    p["_p_date"] = pd.to_datetime(p["date"], utc=True, errors="coerce")
    p = p.dropna(subset=["_p_date"]).sort_values("_p_date")
    right = p[["session_key", "driver_number", "_p_date", "position"]].rename(columns={"position": "_p_pos"})
    take = ml.loc[need, ["session_key", "driver_number", "date_start"]].copy()
    take["date_start"] = pd.to_datetime(take["date_start"], utc=True, errors="coerce")
    take = take.dropna(subset=["date_start"]).sort_values("date_start")
    joined = pd.merge_asof(
        take,
        right,
        left_on="date_start",
        right_on="_p_date",
        by=["session_key", "driver_number"],
        direction="backward",
    )
    idx = take.index
    vals = pd.Series(joined["_p_pos"].to_numpy(), index=idx)
    dates = pd.Series(joined["_p_date"].to_numpy(), index=idx)
    mask = ml.loc[idx, "position_at_lap"].isna() & vals.notna()
    n = int(mask.sum())
    if n:
        ml.loc[idx[mask.to_numpy()], "position_at_lap"] = vals.loc[mask].to_numpy()
        ml.loc[idx[mask.to_numpy()], "position_date"] = dates.loc[mask].to_numpy()
        if "position_at_lap_source" not in ml.columns:
            ml["position_at_lap_source"] = np.where(ml["position_at_lap"].notna(), "openf1", None)
        ml.loc[idx[mask.to_numpy()], "position_at_lap_source"] = "openf1_asof_after_date_fill"
    return ml, n


def write_parquet(name: str, df: pd.DataFrame) -> dict:
    path = HF / "data" / name / "train.parquet"
    path.parent.mkdir(parents=True, exist_ok=True)
    df.to_parquet(path, index=False)
    return {"table": name, "rows": int(len(df)), "columns": list(df.columns), "bytes": path.stat().st_size}


def null_profile(df: pd.DataFrame, cols=None) -> dict:
    cols = cols or list(df.columns)
    n = len(df)
    out = {}
    for c in cols:
        if c not in df.columns:
            continue
        nn = int(df[c].isna().sum())
        out[c] = {"nulls": nn, "pct": round(100 * nn / n, 2) if n else None}
    return out


def main() -> None:
    sessions = pd.read_parquet(HF / "data/sessions/train.parquet")
    meetings = pd.read_parquet(HF / "data/meetings/train.parquet")
    sessions = sessions.merge(meetings[["meeting_key", "meeting_name"]], on="meeting_key", how="left")
    drivers = pd.read_parquet(HF / "data/drivers/train.parquet")
    laps = pd.read_parquet(HF / "data/laps/train.parquet")
    laps_ml = pd.read_parquet(HF / "data/laps_ml/train.parquet")
    stints = pd.read_parquet(HF / "data/stints/train.parquet")
    pit = pd.read_parquet(HF / "data/pit/train.parquet")
    weather = pd.read_parquet(HF / "data/weather/train.parquet")
    position = pd.read_parquet(HF / "data/position/train.parquet")

    before = {
        "laps": null_profile(laps),
        "laps_ml": null_profile(laps_ml),
        "drivers": null_profile(drivers, ["country_code", "headshot_url"]),
        "stints": null_profile(stints, ["compound"]),
        "pit": null_profile(pit, ["pit_duration", "lane_duration", "stop_duration", "date"]),
    }

    print("loading TracingInsights files")
    ti_by_sk = load_all_ti(sessions)
    ti_all = pd.concat(ti_by_sk.values(), ignore_index=True)
    print("TI rows", len(ti_all), "sessions", ti_all.session_key.nunique())

    print("validating overlap")
    overlap = validate_overlap(laps, ti_by_sk)
    # tyre/compound/pos overlap vs laps_ml
    for field, tif in [("compound", "compound"), ("tyre_age", "tyre_age")]:
        both_n = agree = fillable = 0
        for sk, ti in ti_by_sk.items():
            of = laps_ml[laps_ml.session_key == sk][["driver_number", "lap_number", field]]
            m = of.merge(
                ti[["driver_number", "lap_number", tif]].rename(columns={tif: "_ti"}),
                on=["driver_number", "lap_number"],
                how="inner",
            )
            both = m[m[field].notna() & m["_ti"].notna()]
            both_n += len(both)
            fillable += int((m[field].isna() & m["_ti"].notna()).sum())
            if field == "compound":
                agree += int((both[field] == both["_ti"]).sum())
            else:
                agree += int((both[field].astype("Float64") == both["_ti"].astype("Float64")).sum()) if len(both) else 0
        overlap[field] = {"overlap_n": both_n, "n_agree": agree, "pct_agree": (100 * agree / both_n) if both_n else None, "fillable_openf1_null_ti_present": fillable}
    print(json.dumps(overlap, indent=2, default=str)[:3000])

    fill_report: dict = {"overlap_validation": overlap, "filled": {}}

    print("filling drivers")
    drivers, drep = fill_drivers(drivers, sessions)
    fill_report["filled"]["drivers"] = drep
    print("  country still null", drep["country_code"]["still_null"], "headshot", drep["headshot_url"]["still_null"])

    print("filling laps timing")
    timing_fields = [a for a, _ in TIMING_MAP] + ["date_start"]
    laps_rep = {}
    # init sources
    for c in timing_fields:
        laps[f"{c}_source"] = np.where(laps[c].notna(), "openf1", None)
    laps = fill_from_ti(laps, ti_all, timing_fields, laps_rep, "laps")
    # is_pit_out_lap already bool; fill False/True only when? don't overwrite
    # add is_pit_in_lap, is_deleted from TI
    flags = ti_all[["session_key", "driver_number", "lap_number", "is_pit_in_lap", "is_deleted"]]
    laps = laps.merge(flags, on=["session_key", "driver_number", "lap_number"], how="left")
    laps["is_pit_in_lap"] = laps["is_pit_in_lap"].astype("boolean")
    laps["is_deleted"] = laps["is_deleted"].astype("boolean")
    fill_report["filled"]["laps"] = laps_rep
    print("  laps fills", laps_rep)

    print("filling stints compound from TI majority in window")
    stint_fills = 0
    # join TI laps into stint windows
    st = stints.copy()
    ti_c = ti_all.dropna(subset=["compound"])[["session_key", "driver_number", "lap_number", "compound"]]
    if st["compound"].isna().any() and len(ti_c):
        j = st.merge(ti_c, on=["session_key", "driver_number"], how="left", suffixes=("", "_ti"))
        in_win = (j["lap_number"] >= j["lap_start"]) & (j["lap_number"] <= j["lap_end"])
        j = j[in_win & j["compound"].isna() & j["compound_ti"].notna()]
        if len(j):
            maj = (
                j.groupby(["session_key", "driver_number", "stint_number"])["compound_ti"]
                .agg(lambda s: s.mode().iloc[0] if len(s.mode()) else s.iloc[0])
                .reset_index()
                .rename(columns={"compound_ti": "cc"})
            )
            st = st.merge(maj, on=["session_key", "driver_number", "stint_number"], how="left")
            mask = st["compound"].isna() & st["cc"].notna()
            stint_fills = int(mask.sum())
            st.loc[mask, "compound"] = st.loc[mask, "cc"]
            st["compound_source"] = np.where(st["compound"].notna() & ~mask, "openf1", None)
            st.loc[mask, "compound_source"] = "tracinginsights"
            st = st.drop(columns=["cc"])
        else:
            st["compound_source"] = np.where(st["compound"].notna(), "openf1", None)
    else:
        st["compound_source"] = np.where(st["compound"].notna(), "openf1", None)
    stints = st
    fill_report["filled"]["stints_compound"] = stint_fills
    print("  stints compound filled", stint_fills)

    print("filling laps_ml")
    ml = laps_ml.copy()
    # country_code from updated drivers
    dmap = drivers[["session_key", "driver_number", "country_code", "country_code_source", "broadcast_name"]].drop_duplicates(["session_key", "driver_number"])
    ml = ml.drop(columns=["country_code"], errors="ignore")
    ml = ml.merge(dmap[["session_key", "driver_number", "country_code", "country_code_source"]], on=["session_key", "driver_number"], how="left")

    # timing from updated laps
    lsrc = [c for c in timing_fields if c in laps.columns] + [f"{c}_source" for c in timing_fields] + ["is_pit_in_lap", "is_deleted"]
    lpart = laps[["session_key", "driver_number", "lap_number"] + [c for c in lsrc if c in laps.columns]].copy()
    # drop old timing, take filled
    drop_cols = [c for c in timing_fields if c in ml.columns]
    ml = ml.drop(columns=drop_cols)
    ml = ml.merge(lpart, on=["session_key", "driver_number", "lap_number"], how="left")

    # compound / tyre / stint from updated stints first, then TI leftovers
    # Re-join stints for rows that were null
    need = ml["compound"].isna() | ml["stint_number"].isna()
    if need.any():
        s = stints.copy()
        keys = ["session_key", "driver_number"]
        merged = ml.loc[need, keys + ["lap_number"]].merge(
            s[keys + ["stint_number", "compound", "lap_start", "lap_end", "tyre_age_at_start"]],
            on=keys,
            how="left",
        )
        lap = merged["lap_number"]
        in_range = (merged["lap_start"].isna() | (lap >= merged["lap_start"])) & (
            merged["lap_end"].isna() | (lap <= merged["lap_end"])
        )
        hit = merged[in_range & merged["compound"].notna()].drop_duplicates(["session_key", "driver_number", "lap_number"], keep="last")
        if len(hit):
            ml = ml.merge(
                hit[["session_key", "driver_number", "lap_number", "stint_number", "compound", "lap_start", "lap_end", "tyre_age_at_start"]].rename(
                    columns={c: f"_s_{c}" for c in ["stint_number", "compound", "lap_start", "lap_end", "tyre_age_at_start"]}
                ),
                on=["session_key", "driver_number", "lap_number"],
                how="left",
            )
            n_s = 0
            for c in ["stint_number", "compound", "lap_start", "lap_end", "tyre_age_at_start"]:
                mask = ml[c].isna() & ml[f"_s_{c}"].notna()
                n_s += int(mask.sum())
                ml.loc[mask, c] = ml.loc[mask, f"_s_{c}"]
                if c == "compound":
                    if "compound_source" not in ml.columns:
                        ml["compound_source"] = np.where(ml["compound"].notna() & ~mask, "openf1", None)
                    ml.loc[mask, "compound_source"] = ml.loc[mask, "compound_source"].fillna("openf1")
                    # these came from stints (possibly TI-filled stints)
            ml = ml.drop(columns=[c for c in ml.columns if c.startswith("_s_")])
            # recompute tyre_age where still null but we now have age_at_start
            can = ml["tyre_age"].isna() & ml["tyre_age_at_start"].notna() & ml["lap_start"].notna()
            ml.loc[can, "tyre_age"] = (
                ml.loc[can, "tyre_age_at_start"].astype("Int64") + (ml.loc[can, "lap_number"] - ml.loc[can, "lap_start"]).astype("Int64")
            )
            fill_report["filled"]["laps_ml_stint_rejoin"] = n_s

    if "compound_source" not in ml.columns:
        ml["compound_source"] = np.where(ml["compound"].notna(), "openf1", None)
    if "tyre_age_source" not in ml.columns:
        ml["tyre_age_source"] = np.where(ml["tyre_age"].notna(), "openf1", None)
    if "stint_number_source" not in ml.columns:
        ml["stint_number_source"] = np.where(ml["stint_number"].notna(), "openf1", None)

    # leftover compound/tyre/stint from TI per-lap
    ti_st = ti_all[["session_key", "driver_number", "lap_number", "compound", "tyre_age", "stint_number"]].rename(
        columns={"compound": "_ti_compound", "tyre_age": "_ti_tyre_age", "stint_number": "_ti_stint_number"}
    )
    ml = ml.merge(ti_st, on=["session_key", "driver_number", "lap_number"], how="left")
    for c, srcname in [("compound", "compound_source"), ("tyre_age", "tyre_age_source"), ("stint_number", "stint_number_source")]:
        mask = ml[c].isna() & ml[f"_ti_{c}"].notna()
        fill_report["filled"][f"laps_ml_{c}_from_ti"] = int(mask.sum())
        ml.loc[mask, c] = ml.loc[mask, f"_ti_{c}"]
        ml.loc[mask, srcname] = "tracinginsights"
    ml = ml.drop(columns=["_ti_compound", "_ti_tyre_age", "_ti_stint_number"])

    # weather + position asof for newly dated laps
    if "weather_source" not in ml.columns:
        ml["weather_source"] = np.where(ml["air_temperature"].notna(), "openf1", None)
    ml, n_w = asof_fill_weather(ml, weather)
    fill_report["filled"]["laps_ml_weather_asof"] = n_w
    # leftover weather from TI per-lap weather
    wfields = ["air_temperature", "track_temperature", "humidity", "rainfall", "pressure", "wind_speed", "wind_direction"]
    ti_w = ti_all[["session_key", "driver_number", "lap_number"] + wfields].rename(columns={c: f"_tiw_{c}" for c in wfields})
    ml = ml.merge(ti_w, on=["session_key", "driver_number", "lap_number"], how="left")
    n_wt = 0
    for c in wfields:
        mask = ml[c].isna() & ml[f"_tiw_{c}"].notna()
        n_wt += int(mask.sum())
        ml.loc[mask, c] = ml.loc[mask, f"_tiw_{c}"]
        if c == "air_temperature":
            ml.loc[mask, "weather_source"] = "tracinginsights"
        else:
            # mark weather_source if still empty
            ml.loc[mask & ml["weather_source"].isna(), "weather_source"] = "tracinginsights"
    ml = ml.drop(columns=[f"_tiw_{c}" for c in wfields])
    fill_report["filled"]["laps_ml_weather_from_ti"] = n_wt

    if "position_at_lap_source" not in ml.columns:
        ml["position_at_lap_source"] = np.where(ml["position_at_lap"].notna(), "openf1", None)
    ml, n_p = asof_fill_position(ml, position)
    fill_report["filled"]["laps_ml_position_asof"] = n_p
    # leftover positions from TI
    ti_p = ti_all[["session_key", "driver_number", "lap_number", "position"]].rename(columns={"position": "_ti_pos"})
    ml = ml.merge(ti_p, on=["session_key", "driver_number", "lap_number"], how="left")
    mask = ml["position_at_lap"].isna() & ml["_ti_pos"].notna()
    fill_report["filled"]["laps_ml_position_from_ti"] = int(mask.sum())
    ml.loc[mask, "position_at_lap"] = ml.loc[mask, "_ti_pos"]
    ml.loc[mask, "position_at_lap_source"] = "tracinginsights"
    ml = ml.drop(columns=["_ti_pos"])

    # flags already merged from laps
    if "is_pit_in_lap" in ml.columns:
        ml["is_pit_in_lap"] = ml["is_pit_in_lap"].astype("boolean")
    if "is_deleted" in ml.columns:
        ml["is_deleted"] = ml["is_deleted"].astype("boolean")

    # dtypes tidy
    for c in ["stint_number", "tyre_age_at_start", "tyre_age", "lap_start", "lap_end", "position_at_lap", "wind_direction", "rainfall"]:
        if c in ml.columns:
            ml[c] = pd.to_numeric(ml[c], errors="coerce").astype("Int64")
    for c in ["date_start", "weather_date", "position_date", "session_date_start", "date_end"]:
        if c in ml.columns:
            ml[c] = pd.to_datetime(ml[c], utc=True, errors="coerce").astype("datetime64[ns, UTC]")

    # column order: original preferred + new flags/sources at the end of their groups
    preferred = [
        "year", "meeting_key", "meeting_name", "meeting_official_name",
        "session_key", "session_name", "session_type", "session_date_start",
        "date_end", "gmt_offset", "circuit_short_name", "country_name", "location",
        "driver_number", "full_name", "name_acronym", "team_name", "broadcast_name",
        "country_code", "country_code_source",
        "lap_number", "date_start", "date_start_source", "lap_duration", "lap_duration_source",
        "duration_sector_1", "duration_sector_1_source", "duration_sector_2", "duration_sector_2_source",
        "duration_sector_3", "duration_sector_3_source",
        "i1_speed", "i1_speed_source", "i2_speed", "i2_speed_source", "st_speed", "st_speed_source",
        "is_pit_out_lap", "is_pit_in_lap", "is_deleted",
        "stint_number", "stint_number_source", "compound", "compound_source",
        "tyre_age_at_start", "tyre_age", "tyre_age_source", "lap_start", "lap_end",
        "air_temperature", "track_temperature", "humidity", "rainfall", "pressure",
        "wind_speed", "wind_direction", "weather_date", "weather_source",
        "position_at_lap", "position_date", "position_at_lap_source", "final_position",
        "pit_this_lap", "pit_duration", "stop_duration", "lane_duration", "pit_source",
        "lap_source",
        "segments_sector_1", "segments_sector_2", "segments_sector_3",
    ]
    rest = [c for c in ml.columns if c not in preferred]
    ml = ml[[c for c in preferred if c in ml.columns] + rest]
    ml = ml.sort_values(["year", "session_key", "driver_number", "lap_number"], kind="mergesort").reset_index(drop=True)
    laps = laps.sort_values(["session_key", "driver_number", "lap_number"], kind="mergesort").reset_index(drop=True)
    drivers = drivers.sort_values(["session_key", "driver_number"], kind="mergesort").reset_index(drop=True)
    stints = stints.sort_values(["session_key", "driver_number", "stint_number"], kind="mergesort").reset_index(drop=True)

    after = {
        "laps": null_profile(laps),
        "laps_ml": null_profile(ml),
        "drivers": null_profile(drivers, ["country_code", "headshot_url"]),
        "stints": null_profile(stints, ["compound"]),
    }
    fill_report["nulls_before"] = before
    fill_report["nulls_after"] = after

    # key before/after for README
    key_cols = [
        "country_code", "i1_speed", "st_speed", "i2_speed",
        "duration_sector_1", "duration_sector_2", "duration_sector_3", "lap_duration",
        "date_start", "compound", "tyre_age", "stint_number",
        "air_temperature", "position_at_lap",
        "pit_duration", "stop_duration", "lane_duration", "pit_source",
        "segments_sector_1",
    ]
    cmp = {}
    for c in key_cols:
        b = before["laps_ml"].get(c, {})
        a = after["laps_ml"].get(c, {})
        cmp[c] = {"before_pct": b.get("pct"), "before_nulls": b.get("nulls"), "after_pct": a.get("pct"), "after_nulls": a.get("nulls")}
    fill_report["laps_ml_key_before_after"] = cmp
    print(json.dumps(cmp, indent=2))

    stats = {
        "laps": write_parquet("laps", laps),
        "laps_ml": write_parquet("laps_ml", ml),
        "drivers": write_parquet("drivers", drivers),
        "stints": write_parquet("stints", stints),
    }
    print("wrote", {k: v["rows"] for k, v in stats.items()})

    # persist report
    outp = HF / "nullfill_report.json"
    outp.write_text(json.dumps(fill_report, indent=2, default=str))
    # also merge into gapfill_report
    gpath = HF / "gapfill_report.json"
    grep = json.loads(gpath.read_text()) if gpath.exists() else {}
    grep["null_fill"] = {
        "overlap_validation": overlap,
        "filled": fill_report["filled"],
        "laps_ml_key_before_after": cmp,
        "drivers": drep,
    }
    gpath.write_text(json.dumps(grep, indent=2, default=str))
    print("wrote reports")


if __name__ == "__main__":
    main()