#!/usr/bin/env python3
"""
Test script to demonstrate detailed backtesting with trade logs and statistics
"""

import json
import sys
import os

# Add the project root to Python path
sys.path.insert(0, os.path.dirname(__file__))

from universal_backtesting import UniversalBacktestingEngine

def test_detailed_backtesting():
    """Test detailed backtesting functionality"""

    print("🧪 Testing Detailed Backtesting with XAUUSD Data")
    print("=" * 60)

    engine = UniversalBacktestingEngine()

    # Test XAUUSD trend following
    result = engine.run_backtest(
        market="forex",
        strategy_name="trend_following",
        parameters={"pair": "XAUUSD", "stake": 100},
        timeframe="1hour",
        min_trades=5
    )

    if not result.get('success'):
        print(f"❌ Backtest failed: {result.get('error')}")
        return

    print("✅ Backtest completed successfully!")
    print(f"📊 Market: {result['market'].upper()}")
    print(f"📈 Strategy: {result['strategy_name'].replace('_', ' ').title()}")
    print(f"⏰ Timeframe: {result.get('timeframe', '1hour')}")
    print(f"💰 Stake per trade: ${result['parameters']['stake']}")
    print()

    # Show detailed statistics
    if 'detailed_statistics' in result:
        stats = result['detailed_statistics']

        print("📊 DETAILED TRADE ANALYSIS:")
        print("-" * 40)
        trade_stats = stats['trade_analysis']
        print(f"Total Trades: {trade_stats['total_trades']}")
        print(f"Winning Trades: {trade_stats['winning_trades']}")
        print(f"Losing Trades: {trade_stats['losing_trades']}")
        print(".1f")
        print()

        print("💰 PROFIT/LOSS BREAKDOWN:")
        print("-" * 40)
        pnl_stats = stats['profit_loss_analysis']
        print(f"Total Profit: ${pnl_stats['total_profit']}")
        print(f"Biggest Win: ${pnl_stats['biggest_win']}")
        print(f"Biggest Loss: ${pnl_stats['biggest_loss']}")
        print(f"Average Win: ${pnl_stats['average_win']}")
        print(f"Average Loss: ${pnl_stats['average_loss']}")
        print()

        print("📈 RISK & PERFORMANCE RATIOS:")
        print("-" * 40)
        ratios = stats['ratios_and_factors']
        print(f"Profit Factor: {ratios['profit_factor']}")
        print(f"Win/Loss Ratio: {ratios['win_loss_ratio']}")
        print(f"Recovery Factor: {ratios['recovery_factor']}")
        print(".2f")
        print(f"Kelly Fraction: {ratios['kelly_fraction_percent']}%")
        print()

        print("🎯 RISK METRICS:")
        print("-" * 40)
        risk_stats = stats['risk_metrics']
        print(f"Sharpe Ratio: {risk_stats['sharpe_ratio']}")
        print(f"Sortino Ratio: {risk_stats['sortino_ratio']}")
        print(f"Max Drawdown: ${risk_stats['max_drawdown']}")
        print()

    # Show verification data
    if 'verification_data' in result:
        print("🔍 VERIFICATION:")
        print("-" * 40)
        verify = result['verification_data']
        print(f"Data Source: {verify['data_source']}")
        print(f"Calculation Method: {verify['calculation_method']}")
        print(f"Status: {verify['verification_status']}")
        print()

    # Show sample trades
    if 'all_trades' in result and len(result['all_trades']) > 0:
        trades = result['all_trades']
        print("📋 SAMPLE TRADES (First 3 & Last 3):")
        print("-" * 40)

        # First 3 trades
        print("First 3 trades:")
        for i, trade in enumerate(trades[:3]):
            date = trade.get('date', 'N/A')
            action = trade.get('action', 'UNKNOWN')
            outcome = trade.get('outcome', 'unknown')
            profit = trade.get('profit', 0)
            print(f"  {i+1}. {date} | {action} | {outcome.upper()} | ${profit:.2f}")

        print()
        # Last 3 trades
        print("Last 3 trades:")
        for i, trade in enumerate(trades[-3:]):
            date = trade.get('date', 'N/A')
            action = trade.get('action', 'UNKNOWN')
            outcome = trade.get('outcome', 'unknown')
            profit = trade.get('profit', 0)
            print(f"  {len(trades)-2+i}. {date} | {action} | {outcome.upper()} | ${profit:.2f}")

        print()
        print(f"💡 All {len(trades)} trades logged with detailed P&L calculations")
        print("💡 Statistics calculated from real trade data - no fake results!")

if __name__ == "__main__":
    test_detailed_backtesting()
