import pandas as pd
import numpy as np
import argparse
import os
from scipy.stats import pearsonr

def load_data(filepath):
    if not os.path.exists(filepath):
        print(f"Error: File not found: {filepath}")
        return None
    df = pd.read_csv(filepath)
    # Normalize column names: lowercase, strip whitespace
    df.columns = df.columns.str.lower().str.strip()
    
    # Try to find a time column
    time_col = None
    for col in ['time', 'date', 'timestamp']:
        if col in df.columns:
            time_col = col
            break
    
    if time_col:
        df[time_col] = pd.to_datetime(df[time_col])
        df = df.set_index(time_col)
    
    return df

def analyze(tv_path, py_path):
    print(f"--- Component Diagnosis ---")
    print(f"TV Data: {tv_path}")
    print(f"PY Data: {py_path}")
    
    tv_df = load_data(tv_path)
    py_df = load_data(py_path)
    
    if tv_df is None or py_df is None:
        return

    # Align dataframes by index (Time)
    # Inner join to only compare overlapping data
    common_index = tv_df.index.intersection(py_df.index)
    
    if len(common_index) == 0:
        print("\nCRITICAL ERROR: No overlapping timestamps found.")
        print(f"TV Range: {tv_df.index.min()} to {tv_df.index.max()}")
        print(f"PY Range: {py_df.index.min()} to {py_df.index.max()}")
        return

    tv_df = tv_df.loc[common_index]
    py_df = py_df.loc[common_index]
    
    print(f"\nAnalyzing {len(common_index)} overlapping bars...")
    
    # Find common columns (fuzzy match logic could go here, but strict for now)
    # We look for columns that start with 'db_' as per the strategy convention
    tv_cols = [c for c in tv_df.columns if c.startswith('db_')]
    py_cols = [c for c in py_df.columns if c.startswith('db_')]
    
    common_cols = list(set(tv_cols).intersection(py_cols))
    common_cols.sort()
    
    if not common_cols:
        print("\nNo common 'db_' columns found.")
        print(f"TV Debug Cols: {tv_cols}")
        print(f"PY Debug Cols: {py_cols}")
        print("Tip: Ensure both scripts export columns starting with 'DB_'")
        return

    print(f"\n{'COLUMN':<25} | {'CORRELATION':<12} | {'MAE':<10} | {'STATUS':<10}")
    print("-" * 65)
    
    for col in common_cols:
        s1 = tv_df[col].fillna(0)
        s2 = py_df[col].fillna(0)
        
        # Check for constant values (std dev is 0)
        if s1.std() == 0 or s2.std() == 0:
            corr = 0.0
            note = " (Constant)"
        else:
            corr, _ = pearsonr(s1, s2)
            note = ""
            
        mae = np.mean(np.abs(s1 - s2))
        
        # Grading Logic
        status = "FAIL"
        if corr > 0.99:
            status = "PASS"
        elif corr > 0.90:
            status = "WARN"
            
        # Special case for binary/sparse signals where correlation might be weird
        if mae < 0.001:
            status = "PASS"
            
        print(f"{col:<25} | {corr:>10.4f}{note} | {mae:>10.4f} | {status}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Diagnose Strategy Parity")
    parser.add_argument("--tv", required=True, help="Path to TradingView Export CSV")
    parser.add_argument("--py", required=True, help="Path to Python Strategy Output CSV")
    args = parser.parse_args()
    
    analyze(args.tv, args.py)