#!/usr/bin/env python3
"""
Test script to verify the stats command fix
"""

import sys
from pathlib import Path

# Add the project root and src directory to the path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
sys.path.insert(0, str(project_root / 'src'))

from trading_stats import TradingStats

def test_stats_fix():
    """Test that stats work with no trades and with trades."""
    print("๐Ÿงช Testing Stats Fix")
    print("=" * 40)
    
    try:
        # Test 1: New stats instance (no trades)
        print("๐Ÿ“Š Test 1: Empty stats (no trades)")
        stats = TradingStats(stats_file="test_stats.json")
        
        # Try to format stats message
        message = stats.format_stats_message(1000.0)
        print("โœ… Empty stats message generated successfully")
        print(f"๐Ÿ“ Message length: {len(message)} characters")
        
        # Test 2: Performance stats with no trades
        print("\n๐Ÿ“Š Test 2: Performance stats with no trades")
        perf_stats = stats.get_performance_stats()
        
        # Check that expectancy key exists
        if 'expectancy' in perf_stats:
            print(f"โœ… Expectancy key exists: {perf_stats['expectancy']}")
        else:
            print("โŒ Expectancy key missing!")
            return False
        
        # Check all required keys
        required_keys = [
            'win_rate', 'profit_factor', 'avg_win', 'avg_loss',
            'largest_win', 'largest_loss', 'consecutive_wins',
            'consecutive_losses', 'total_wins', 'total_losses', 'expectancy'
        ]
        
        missing_keys = [key for key in required_keys if key not in perf_stats]
        if missing_keys:
            print(f"โŒ Missing keys: {missing_keys}")
            return False
        else:
            print("โœ… All required performance keys present")
        
        # Test 3: Add some sample trades
        print("\n๐Ÿ“Š Test 3: Stats with sample trades")
        stats.record_trade("BTC/USDC:USDC", "buy", 0.001, 45000.0, "test1")
        stats.record_trade("BTC/USDC:USDC", "sell", 0.001, 46000.0, "test2")
        
        # Try to format stats message with trades
        message_with_trades = stats.format_stats_message(1010.0)
        print("โœ… Stats message with trades generated successfully")
        
        # Test performance stats with trades
        perf_stats_with_trades = stats.get_performance_stats()
        print(f"โœ… Win rate: {perf_stats_with_trades['win_rate']:.1f}%")
        print(f"โœ… Expectancy: ${perf_stats_with_trades['expectancy']:.2f}")
        
        # Test 4: Error handling
        print("\n๐Ÿ“Š Test 4: Error handling")
        try:
            # This should not fail due to the safe .get() access
            comprehensive_stats = stats.get_comprehensive_stats(1010.0)
            print("โœ… Comprehensive stats generated successfully")
        except Exception as e:
            print(f"โŒ Comprehensive stats failed: {e}")
            return False
        
        print("\n๐ŸŽ‰ All stats tests passed!")
        print("\n๐Ÿ“ Sample stats message:")
        print("-" * 40)
        print(message[:200] + "..." if len(message) > 200 else message)
        print("-" * 40)
        
        # Clean up test file
        import os
        try:
            os.remove("test_stats.json")
            print("\n๐Ÿงน Test file cleaned up")
        except:
            pass
        
        return True
        
    except Exception as e:
        print(f"๐Ÿ’ฅ Test failed with error: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = test_stats_fix()
    
    if success:
        print("\n๐ŸŽ‰ Stats fix test PASSED!")
        print("\nโœ… The /stats command should now work properly")
        sys.exit(0)
    else:
        print("\n๐Ÿ’ฅ Stats fix test FAILED!")
        sys.exit(1)