#!/usr/bin/env python3
"""
Debug script to examine current trading stats and understand calculation issues.
"""

import sys
import os
import json
from pathlib import Path

# Add src directory to Python path
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

from src.stats import TradingStats

def debug_stats():
    """Debug current trading statistics."""
    print("šŸ” Trading Stats Debug\n")
    
    # Check if stats file exists
    stats_file = "trading_stats.json"
    if not os.path.exists(stats_file):
        print(f"āŒ Stats file {stats_file} does not exist")
        return
    
    # Load raw stats data
    print("šŸ“ Raw Stats File:")
    with open(stats_file, 'r') as f:
        raw_data = json.load(f)
    
    print(f"   Trades count: {len(raw_data.get('trades', []))}")
    print(f"   Initial balance: ${raw_data.get('initial_balance', 0):,.2f}")
    print(f"   Start time: {raw_data.get('start_time', 'Not set')}")
    
    if raw_data.get('trades'):
        print(f"\nšŸ“‹ Raw Trades:")
        for i, trade in enumerate(raw_data['trades'], 1):
            print(f"   {i}. {trade['side'].upper()} {trade['amount']} {trade['symbol']} @ ${trade['price']:,.2f}")
            print(f"      Value: ${trade['value']:,.2f} | ID: {trade.get('order_id', 'N/A')}")
    
    # Initialize TradingStats and test calculations
    stats = TradingStats()
    
    print(f"\n🧮 Calculated P&L Trades:")
    trades_with_pnl = stats.calculate_trade_pnl()
    
    for i, trade in enumerate(trades_with_pnl, 1):
        pnl = trade.get('pnl', 0)
        print(f"   {i}. {trade['side'].upper()} {trade['amount']} {trade['symbol']} @ ${trade['price']:,.2f}")
        print(f"      P&L: ${pnl:,.2f} | Value: ${trade['value']:,.2f}")
    
    completed_trades = [t for t in trades_with_pnl if t.get('pnl', 0) != 0]
    print(f"\nāœ… Completed Trades (with P&L): {len(completed_trades)}")
    
    if completed_trades:
        total_pnl = sum(t['pnl'] for t in completed_trades)
        print(f"   Total P&L: ${total_pnl:,.2f}")
    
    # Test basic stats
    print(f"\nšŸ“Š Basic Stats:")
    basic_stats = stats.get_basic_stats()
    for key, value in basic_stats.items():
        if isinstance(value, float):
            print(f"   {key}: ${value:,.2f}")
        else:
            print(f"   {key}: {value}")
    
    # Test performance stats
    print(f"\nšŸ† Performance Stats:")
    perf_stats = stats.get_performance_stats()
    for key, value in perf_stats.items():
        if isinstance(value, float):
            print(f"   {key}: {value:.2f}")
        else:
            print(f"   {key}: {value}")
    
    # Test token performance
    print(f"\nšŸŽÆ Token Performance:")
    token_perf = stats.get_token_performance()
    for token, data in token_perf.items():
        print(f"   {token}:")
        print(f"      Total Orders: {data['total_trades']}")
        print(f"      Completed Trades: {data['completed_trades']}")
        print(f"      Total P&L: ${data['total_pnl']:,.2f}")
        print(f"      Win Rate: {data['win_rate']:.1f}%")

if __name__ == "__main__":
    debug_stats()