import pandas as pd
import matplotlib.pyplot as plt
import argparse
from RemoveDuplicates import remove_duplicate_rows

def process_file(filename):
    remove_duplicate_rows(filename)
    df = pd.read_csv(filename, names=['IOC', 'Key', 'Value'])
    df = df.sort_values('Key')
    df['Category'] = df['Key'].apply(lambda x: ':'.join(x.split(':')[:-1]))
    df['Value'] = pd.to_numeric(df['Value'].str.replace('+', ''), errors='coerce')
    return df

def main():
    parser = argparse.ArgumentParser(description='Compare collimator values from CSV files.')
    parser.add_argument('files', nargs=2, help='Paths to the two CSV files')
    args = parser.parse_args()

    if len(args.files) != 2:
        print("Please provide exactly two CSV files.")
        return

    fig, ax1 = plt.subplots(figsize=(20, 12))

    dfs = []
    for i, file in enumerate(args.files):
        df = process_file(file)
        df = df.sort_values('Category')
        dfs.append(df)
        
        ax1.plot(df['Category'], df['Value'], marker='.', 
                 linestyle='-.', linewidth=2, markersize=10, label=f'Snapshot File {i+1}')

    merged_df = pd.merge(dfs[0], dfs[1], on='Category', suffixes=('_1', '_2'))
    merged_df['Error'] = merged_df['Value_1'] - merged_df['Value_2']

    ax2 = ax1.twinx()
    ax2.plot(merged_df['Category'], merged_df['Error'], color='green', marker='o', linestyle=':', linewidth=2, markersize=5, label='Error')

    ax1.set_xlabel('PV Name')
    ax1.set_ylabel('Value')
    ax2.set_ylabel('Error')
    plt.title('Comparison of Snapshot Values and Error')
    
    lines1, labels1 = ax1.get_legend_handles_labels()
    lines2, labels2 = ax2.get_legend_handles_labels()
    ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper left')

    plt.setp(ax1.get_xticklabels(), rotation='vertical', ha='center')
    
    plt.tight_layout()
    plt.subplots_adjust(bottom=0.2)
    
    ax1.grid(True, which='both', linestyle='--', linewidth=0.5)

    plt.show()

if __name__ == "__main__":
    main()