"""Read a collision sample from Real Driving Events and Scenarios: the impact time, speed before it, and the crash pulse.
Tested 2026-11-26 with Python 3.12.14, numpy 2.5.4 and opencv-python 5.1.0 on the published files.

route.json is a list of records; "t_s" is seconds from the start of road.mp4 (negative = before the video starts).
Record types: gnss_imu (10 Hz position, speed, heading, IMU), gps, accel, gyro, crash_pulse (the ~100 Hz pulse), sample_info.
velocity.csv gives speed per video frame with seconds_from_impact. Positions are metres from the car at t_s = 0.
Usage: python 03_collision_timeline.py ./real-driving-events-and-scenarios/events/collisions/brooklyn
"""
import csv, json, sys
import cv2

d = sys.argv[1] if len(sys.argv) > 1 else "./real-driving-events-and-scenarios/events/collisions/brooklyn"
rec = json.load(open(f"{d}/route.json"))
info = next(r for r in rec if r["type"] == "sample_info")
print(info["neighbourhood"], info["date"])
types = {}
for r in rec: types[r["type"]] = types.get(r["type"], 0) + 1
print("records:", types)

v = list(csv.DictReader(open(f"{d}/velocity.csv", newline="")))
imp = min(v, key=lambda r: abs(float(r["seconds_from_impact"])))
t_imp = float(imp["video_time_s"])
before = min(v, key=lambda r: abs(float(r["seconds_from_impact"]) + 3.0))
print(f"impact at video time {t_imp:.2f} s; speed 3 s before: {float(before['fused_speed_mph']):.1f} mph, at impact: {float(imp['fused_speed_mph']):.1f} mph")

p = next((r for r in rec if r["type"] == "crash_pulse"), None)
if p:
    ig = p["integration"]
    print(f"crash pulse: trigger {p['trigger_t_s']} s, {p['n_accel']} accel samples ({p['units']})")
    print(f"  peak horizontal {ig['peak_horizontal_g']} g, pulse {ig['pulse_duration_s']} s, delta-v {ig['delta_v_low_mph']}-{ig['delta_v_high_mph']} mph")

cap = cv2.VideoCapture(f"{d}/road.mp4"); fps = cap.get(cv2.CAP_PROP_FPS)
cap.set(cv2.CAP_PROP_POS_MSEC, max(0.0, t_imp - 1.0) * 1000); ok, img = cap.read()
if ok: cv2.imwrite("one_second_before_impact.jpg", img); print(f"saved one_second_before_impact.jpg ({fps:.1f} fps video)")
