"""
Export Parameters to TradingView

Reads the 'optimization_winner_*.csv' file and generates a block of Pine Script
input code with the optimized values as defaults.

Usage:
    python3 tools/export_params_to_tv.py --strategy activation_scores
"""
import pandas as pd
import argparse
import os
import sys

# Metrics to exclude from the export
METRICS = ['Total P&L %', 'Max Drawdown %', 'Sharpe Ratio', 'Sortino Ratio', 'Total Trades']

def infer_pine_type(name, value):
    """Infers the Pine Script input type and format based on name and value."""
    # Boolean check
    if name.startswith("i_use_") or name.startswith("use_") or "_use_" in name:
        val_bool = "true" if float(value) > 0.5 else "false"
        return "input.bool", val_bool
    
    # Integer check (lengths, periods)
    if "length" in name.lower() or "period" in name.lower() or "len" in name.lower():
        return "input.int", str(int(value))
        
    # Default to float
    return "input.float", f"{float(value):.4f}".rstrip('0').rstrip('.')

def main():
    parser = argparse.ArgumentParser(description="Export Optimized Params to Pine Script")
    parser.add_argument("--strategy", type=str, default="activation_scores", help="Strategy name (e.g. activation_scores)")
    parser.add_argument("--results_dir", type=str, default="results", help="Directory containing results")
    args = parser.parse_args()

    filename = f"optimization_winner_{args.strategy}.csv"
    filepath = os.path.join(args.results_dir, filename)
    
    if not os.path.exists(filepath):
        print(f"Error: File not found: {filepath}")
        return

    try:
        df = pd.read_csv(filepath)
        if df.empty:
            print("Error: CSV is empty.")
            return
            
        row = df.iloc[0]
        
        print(f"// --- Optimized Defaults for {args.strategy} ---")
        print(f"// Sharpe: {row.get('Sharpe Ratio', 'N/A')} | Trades: {row.get('Total Trades', 'N/A')}")
        print("// Copy and paste the lines below into your Pine Script:\n")
        
        for col in df.columns:
            if col in METRICS:
                continue
                
            val = row[col]
            pine_type, pine_val = infer_pine_type(col, val)
            
            # Construct the line
            # Example: i_w_stoch = input.float(0.85, "i_w_stoch")
            print(f'{col} = {pine_type}({pine_val}, "{col}")')
            
        print("\n// ----------------------------------------------")

    except Exception as e:
        print(f"Error processing file: {e}")

if __name__ == "__main__":
    # Add project root to path if needed
    sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
    main()
