#!/usr/bin/env python3
"""
Test script to verify the integrated TradingStats position tracking system.
This test ensures that the enhanced position tracking in TradingStats
works correctly for multi-entry/exit scenarios.
"""

import sys
import os
import tempfile
from datetime import datetime

# Add src directory to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))

from trading_stats import TradingStats

def test_integrated_position_tracking():
    """Test the integrated position tracking system."""
    
    # Create temporary stats file
    with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
        temp_file = f.name
    
    try:
        # Initialize TradingStats
        stats = TradingStats(temp_file)
        stats.set_initial_balance(10000.0)
        
        print("Testing Integrated Position Tracking System")
        print("=" * 50)
        
        # Test Case 1: Simple long position
        print("\n1. Testing simple long position:")
        action_type = stats.record_trade_with_enhanced_tracking("ETH/USDC", "buy", 1.0, 3000.0, "test1")
        print(f"   Action: {action_type}")
        position = stats.get_enhanced_position_state("ETH/USDC")
        print(f"   Position: {position['contracts']} ETH @ ${position['avg_entry_price']:.2f}")
        
        # Test Case 2: Add to long position
        print("\n2. Adding to long position:")
        action_type = stats.record_trade_with_enhanced_tracking("ETH/USDC", "buy", 0.5, 3100.0, "test2")
        print(f"   Action: {action_type}")
        position = stats.get_enhanced_position_state("ETH/USDC")
        print(f"   Position: {position['contracts']} ETH @ ${position['avg_entry_price']:.2f}")
        
        # Test Case 3: Partial close
        print("\n3. Partial close of long position:")
        action_type = stats.record_trade_with_enhanced_tracking("ETH/USDC", "sell", 0.5, 3200.0, "test3")
        print(f"   Action: {action_type}")
        position = stats.get_enhanced_position_state("ETH/USDC")
        print(f"   Remaining position: {position['contracts']} ETH @ ${position['avg_entry_price']:.2f}")
        
        # Calculate P&L for the partial close
        pnl_data = stats.calculate_enhanced_position_pnl("ETH/USDC", 0.5, 3200.0)
        print(f"   P&L for partial close: ${pnl_data['pnl']:.2f} ({pnl_data['pnl_percent']:.2f}%)")
        
        # Test Case 4: Full close
        print("\n4. Full close of remaining position:")
        action_type = stats.record_trade_with_enhanced_tracking("ETH/USDC", "sell", 1.0, 3150.0, "test4")
        print(f"   Action: {action_type}")
        position = stats.get_enhanced_position_state("ETH/USDC")
        print(f"   Final position: {position['contracts']} ETH @ ${position['avg_entry_price']:.2f}")
        
        # Test Case 5: Short position
        print("\n5. Testing short position:")
        action_type = stats.record_trade_with_enhanced_tracking("BTC/USDC", "sell", 0.1, 65000.0, "test5")
        print(f"   Action: {action_type}")
        position = stats.get_enhanced_position_state("BTC/USDC")
        print(f"   Position: {position['contracts']} BTC @ entry price tracking")
        
        # Test Case 6: Close short position
        print("\n6. Closing short position:")
        action_type = stats.record_trade_with_enhanced_tracking("BTC/USDC", "buy", 0.1, 64500.0, "test6")
        print(f"   Action: {action_type}")
        pnl_data = stats.calculate_enhanced_position_pnl("BTC/USDC", 0.1, 64500.0)
        print(f"   P&L for short close: ${pnl_data['pnl']:.2f} ({pnl_data['pnl_percent']:.2f}%)")
        
        # Test Case 7: Verify stats consistency
        print("\n7. Verifying stats consistency:")
        basic_stats = stats.get_basic_stats()
        trades_with_pnl = stats.calculate_trade_pnl()
        
        print(f"   Total trades recorded: {basic_stats['total_trades']}")
        print(f"   Completed trade cycles: {basic_stats['completed_trades']}")
        print(f"   Total P&L: ${basic_stats['total_pnl']:.2f}")
        
        # Show all recorded trades
        print("\n8. All trades recorded:")
        for i, trade in enumerate(stats.data['trades'], 1):
            print(f"   {i}. {trade['side'].upper()} {trade['amount']} {trade['symbol']} @ ${trade['price']:.2f}")
        
        print("\nāœ… Integration test completed successfully!")
        print("šŸ”„ Single source of truth for position tracking established!")
        return True
        
    except Exception as e:
        print(f"āŒ Test failed: {e}")
        import traceback
        traceback.print_exc()
        return False
    
    finally:
        # Clean up temp file
        if os.path.exists(temp_file):
            os.unlink(temp_file)

if __name__ == "__main__":
    success = test_integrated_position_tracking()
    exit(0 if success else 1)