import sys
import csv


import numpy as np

def moving_average(input_file, window_size,aoi):

    values = []
    with open(input_file, 'r') as file:
        reader = csv.DictReader(file)
        for row in reader:
            ts = float(row['seconds'])
            area = row['area']
            count = int(row['count'])

            if (area==aoi):
                values.append((ts,count))

    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, aoi):
    window_counts = {}  # Dictionary to store the count of people detected in each frame
    mean_counts = {}
    time_windows_counts ={}
    current_frame_start = -1
    is_first_frame = True
    last_ts = -1

    count_by_second = {}

    first_interval_index = seconds_window



    with open(input_file, 'r') as file:
        reader = csv.DictReader(file)
        for row in reader:
            ts = float(row['seconds'])
            area = row['area']
            count = int(row['count'])

            if (area==aoi):
                count_by_second[ts] =count

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

        if (ts>last_ts):
            current_ts_start = ts
            last_ts = current_ts_start + seconds_window

        # Update the count of people in the current frame
        if current_ts_start in time_windows_counts.keys():
            a,b,c = time_windows_counts[current_ts_start]
            time_windows_counts[current_ts_start] = (a + count_by_second[ts],b +1,c)
        else:
            formatted_time = seconds_to_mmss(ts)
            time_windows_counts[current_ts_start] = (count_by_second[ts],1,formatted_time)

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

    return mean_counts

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

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

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

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