import pandas as pd
import argparse
import sys
from pathlib import Path

def load_data(filepath):
    """Loads CSV data, parsing dates and setting index."""
    try:
        df = pd.read_csv(filepath)
        # Attempt to parse time column. Adjust 'time' or 'date' as needed.
        time_col = None
        for col in df.columns:
            if 'time' in col.lower() or 'date' in col.lower():
                time_col = col
                break
        
        if time_col:
            df[time_col] = pd.to_datetime(df[time_col])
            df.set_index(time_col, inplace=True)
        else:
            print(f"Warning: No time/date column found in {filepath}")
            
        return df
    except Exception as e:
        print(f"Error loading {filepath}: {e}")
        sys.exit(1)

def compare_datasets(python_df, tv_df):
    """Compares Python calculated indicators vs TradingView exported indicators."""
    
    print(f"\n--- Comparing Data ---")
    print(f"Python Data Range: {python_df.index.min()} to {python_df.index.max()}")
    print(f"TV Data Range:     {tv_df.index.min()} to {tv_df.index.max()}")

    # Find common columns (fuzzy match)
    common_cols = []
    for py_col in python_df.columns:
        # Normalize column names for comparison (lowercase, remove DB_, etc)
        py_slug = py_col.lower().replace("db_", "").replace("_", "")
        
        for tv_col in tv_df.columns:
            tv_slug = tv_col.lower().replace("plot", "").replace("_", "")
            
            if py_slug == tv_slug:
                common_cols.append((py_col, tv_col))
    
    if not common_cols:
        print("\nNo matching columns found! Please ensure TradingView plots are named similarly to Python columns.")
        print(f"Python Columns: {list(python_df.columns)}")
        print(f"TV Columns:     {list(tv_df.columns)}")
        return

    # Align dataframes on index
    common_index = python_df.index.intersection(tv_df.index)
    py_subset = python_df.loc[common_index]
    tv_subset = tv_df.loc[common_index]

    print(f"\nAnalyzing {len(common_index)} overlapping bars...")

    for py_col, tv_col in common_cols:
        py_vals = py_subset[py_col]
        tv_vals = tv_subset[tv_col]
        
        diff = py_vals - tv_vals
        mean_diff = diff.mean()
        max_diff = diff.abs().max()
        
        # Check for correlation
        corr = py_vals.corr(tv_vals)
        
        print(f"\nIndicator: {py_col} vs {tv_col}")
        print(f"  Correlation: {corr:.4f} (Should be close to 1.0)")
        print(f"  Mean Diff:   {mean_diff:.4f}")
        print(f"  Max Diff:    {max_diff:.4f}")
        
        if max_diff > 0.01: # Threshold for significant difference
            print("  >> SIGNIFICANT DISCREPANCY DETECTED <<")
            # Show first 5 mismatches
            mismatches = diff[diff.abs() > 0.01].head(5)
            for date, val in mismatches.items():
                print(f"     {date}: Py={py_vals[date]:.4f}, TV={tv_vals[date]:.4f}, Diff={val:.4f}")

def main():
    parser = argparse.ArgumentParser(description="Compare Python Strategy CSV vs TradingView Export CSV")
    parser.add_argument("--python", required=True, help="Path to Python generated CSV (e.g. StrategyActivationBTC1D-weightsApplied.csv)")
    parser.add_argument("--tv", required=True, help="Path to TradingView exported CSV")
    
    args = parser.parse_args()
    
    py_df = load_data(args.python)
    tv_df = load_data(args.tv)
    
    compare_datasets(py_df, tv_df)

if __name__ == "__main__":
    main()
