import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from dnt.track import Tracker
from dnt.label.labeler2 import Labeler
from dnt.filter import Filter
from tssa.core.nearmiss import NearmissAnalyzer
import pandas as pd
from shapely import Polygon

input_video = '/mnt/e/25-120037/25-120037-001-NB/02.04/20250204_013725B.mp4'
base_path = '/mnt/e/25-120037/25-120037-001-NB'
basename = os.path.splitext(os.path.basename(input_video))[0]
ped_track_file = os.path.join(base_path, 'peds', basename+'_cross_ped_track.txt')
veh_track_file = os.path.join(base_path, 'vehs', basename+'_veh_track_inzone.txt')

# Generate paths
basename = os.path.splitext(os.path.basename(input_video))[0]
interaction_path = os.path.join(base_path, 'int')
os.makedirs(interaction_path, exist_ok=True)

nearmiss_file = os.path.join(basename, 'int', basename+"_yield.csv")
label_path = os.path.join(base_path, 'labels_nearmiss')
os.makedirs(label_path, exist_ok=True)

ped_track_infill_file = os.path.join(base_path, 'peds', basename+'_ped_track_infill.txt')
veh_track_infill_file = os.path.join(base_path, 'vehs', basename+'_veh_track_infill.txt')
ped_tracks = pd.read_csv(ped_track_file, header=None)
veh_tracks = pd.read_csv(veh_track_file)

ped_tracks = Tracker.infill_frames(ped_tracks, info='ped')
veh_tracks = Tracker.infill_frames(veh_tracks, info='veh')
#ped_tracks.to_csv(ped_track_infill_file, index=False)
#rt_tracks.to_csv(veh_track_infill_file, index=False)

yield_file = os.path.join(interaction_path, basename+'_yield.csv')

analyzer = NearmissAnalyzer()
pairs = analyzer.scan(tracks_p=ped_tracks, tracks_y=veh_tracks, name_p='ped', name_y='veh')
pairs.to_csv(yield_file, index=False)

NearmissAnalyzer.draw_clips(pairs=pairs,
                            tracks_p=ped_tracks,
                            tracks_y=veh_tracks,
                            input_video=input_video,
                            out_path=label_path,
                            padding=0,
                            prefix=True,
                            size=1,
                            thick=2,
                            show_track=True,
                            show_desc=True,
                            verbose=True)