import sys
import csv

import numpy as np

def moving_average(input_file, window_size):

    values = []
    last_frame = -1
    count_in_frame = 0

    with open(input_file, 'r') as file:
        reader = csv.DictReader(file)
        for row in reader:
            frame_number = int(row['frame_number'])
            track_id = int(row['track_id'])
            count_in_frame +=1
            if last_frame != frame_number and last_frame!=-1:
                ts = float(frame_number) * 1/12.5
                values.append((ts,count_in_frame))
                count_in_frame = 0

            last_frame = frame_number




    timestamps, counts = zip(*values)
    moving_averages = []
    current_time = timestamps[0]
    current_window = []
    
    for timestamp, count in zip(timestamps, counts):
        if timestamp - current_time <= window_size:
            current_window.append((timestamp,count))
        else:
            while timestamp - current_time > window_size:
                if len(current_window)>0:
                    moving_averages.append((current_time, sum(count for ts,count in current_window) / len(current_window)))
                else:
                    moving_averages.append((current_time, 0))
                current_time += 1
                current_window = [(t,c) for t, c in current_window if current_time - t <= window_size]
            current_window.append((timestamp,count))
    
    while current_time <= timestamps[-1]:
        if len(current_window)>0:
            moving_averages.append((current_time, sum(count for ts,count in current_window) / len(current_window)))
        else:
            moving_averages.append((current_time, 0))
        current_time += 1
        current_window = [(t,c) for t, c in current_window if (current_time - t <= window_size) and current_window]
    
    return moving_averages



def seconds_to_mmss(the_seconds):
    minutes = int(the_seconds // 60.0)
    seconds = int(the_seconds % 60.0)
    return f"{minutes:02d}:{seconds:02d}"

def calculate_mean_people_count(input_file, seconds_window):
    window_counts = {}  # Dictionary to store the count of people detected in each frame
    mean_counts = {}
    frame_counts ={}
    current_frame_start = -1
    is_first_frame = True
    last_frame = -1

    count_by_frame = {}

    with open(input_file, 'r') as file:
        reader = csv.DictReader(file)
        for row in reader:
            frame_number = int(row['frame_number'])
            track_id = int(row['track_id'])

            ts = float(frame_number) * 1/12.5

            formatted_time = seconds_to_mmss(ts)

            if (frame_number!=last_frame):
                count_by_frame[frame_number] = 1
            else:
                count_by_frame[frame_number] +=1

            last_frame = frame_number

    last_frame = -1

    for frame_id in count_by_frame.keys():
         #print(f'frame_id= {frame_id} last_frame={last_frame}')

        if (frame_id>last_frame):
            current_frame_start = frame_id
            last_frame = current_frame_start + seconds_window*12.5

        # Update the count of people in the current frame
        if current_frame_start in frame_counts.keys():
            a,b,c = frame_counts[current_frame_start]
            frame_counts[current_frame_start] = (a + count_by_frame[frame_id],b +1,c)
        else:
            ts = float(current_frame_start) * 1/12.5
            formatted_time = seconds_to_mmss(ts)
            frame_counts[current_frame_start] = (count_by_frame[frame_id],1,formatted_time)

    for frame_key in frame_counts.keys():
        #print(f'frame_key= {frame_key}')
        count,num_frames,time = frame_counts[frame_key]
        mean_counts[frame_key]= ((count / num_frames), time)

    return mean_counts

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python script.py input_file seconds_window")
    else:
        input_file = sys.argv[1]
        seconds_window = int(sys.argv[2])

        moving_averages=moving_average(input_file, seconds_window)
        for time,count in moving_averages:
            print(f'{seconds_to_mmss(time)} {count}')


        # mean_counts = calculate_mean_people_count(input_file, seconds_window)
        # #print(f"Mean People Counts in Moving Windows of {frame_window} frames: {mean_counts}")

        # for frame_id in mean_counts.keys():
        #     count, time = mean_counts[frame_id]
        #     print(f'{time} {count}')