import pandas as pd
import pysrt
from datetime import timedelta

# --- Load data ---
telemetry = pd.read_csv('telemetry.csv')  # assumes 'time' in seconds
telemetry = telemetry.sort_values('Time')

# Convert time column to timedelta for matching
telemetry['Time'] = pd.to_timedelta(telemetry['Time'], unit='s')

# Load list of parameters to include
with open('params.txt') as f:
    params = [line.strip() for line in f if line.strip()]

# Load subtitle file
subs = pysrt.open('original.srt')

# --- Build new subtitle file ---
new_subs = pysrt.SubRipFile()

for sub in subs:
    # Get start time as timedelta
    t = timedelta(
        hours=sub.start.hours,
        minutes=sub.start.minutes,
        seconds=sub.start.seconds,
        milliseconds=sub.start.milliseconds
    )

    # Find closest telemetry row
    idx = telemetry['time'].sub(t).abs().idxmin()
    row = telemetry.loc[idx]

    # Build subtitle text
    time_str = f"Time: {str(t).split('.')[0]}"
    values = [f"{param.capitalize()}: {row[param]}" for param in params if param in telemetry.columns]
    new_text = "\n".join([time_str] + values)

    # Create new subtitle
    new_sub = pysrt.SubRipItem(index=sub.index, start=sub.start, end=sub.end, text=new_text)
    new_subs.append(new_sub)

# --- Save updated subtitle file ---
new_subs.save('enriched_subtitles.srt', encoding='utf-8')

print("✅ Enriched subtitle file saved as: enriched_subtitles.srt")
