#!/usr/bin/env python3
"""
Test script to demonstrate the stop loss configuration and functionality.
This script shows how the automatic stop loss system would work.
"""

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))

from config import Config

def test_stop_loss_config():
    """Test and display stop loss configuration."""
    print("🛡️ Stop Loss Configuration Test")
    print("=" * 50)
    
    # Display current configuration
    print(f"📊 Risk Management Enabled: {Config.RISK_MANAGEMENT_ENABLED}")
    print(f"🛑 Stop Loss Percentage: {Config.STOP_LOSS_PERCENTAGE}%")
    print(f"⏰ Monitoring Interval: {Config.BOT_HEARTBEAT_SECONDS} seconds")
    print()
    
    # Simulate position scenarios
    scenarios = [
        {
            'name': 'Long BTC Position',
            'position_type': 'long',
            'entry_price': 45000,
            'current_prices': [44000, 42000, 40500, 39000],
            'position_size': 0.1
        },
        {
            'name': 'Short ETH Position', 
            'position_type': 'short',
            'entry_price': 3000,
            'current_prices': [3100, 3200, 3300, 3400],
            'position_size': 2.0
        }
    ]
    
    for scenario in scenarios:
        print(f"📋 Scenario: {scenario['name']}")
        print(f"   Direction: {scenario['position_type'].upper()}")
        print(f"   Entry Price: ${scenario['entry_price']:,.2f}")
        print(f"   Position Size: {scenario['position_size']}")
        print()
        
        for current_price in scenario['current_prices']:
            # Calculate P&L percentage
            if scenario['position_type'] == 'long':
                pnl_percent = ((current_price - scenario['entry_price']) / scenario['entry_price']) * 100
            else:  # short
                pnl_percent = ((scenario['entry_price'] - current_price) / scenario['entry_price']) * 100
            
            # Check if stop loss would trigger
            would_trigger = pnl_percent <= -Config.STOP_LOSS_PERCENTAGE
            
            # Calculate loss value
            loss_value = scenario['position_size'] * abs(current_price - scenario['entry_price'])
            
            status = "🛑 STOP LOSS TRIGGERED!" if would_trigger else "✅ Safe"
            
            print(f"   Current Price: ${current_price:,.2f} | P&L: {pnl_percent:+.2f}% | Loss: ${loss_value:,.2f} | {status}")
        
        print()

def test_stop_loss_thresholds():
    """Test different stop loss threshold scenarios."""
    print("🔧 Stop Loss Threshold Testing")
    print("=" * 50)
    
    thresholds = [5.0, 10.0, 15.0, 20.0]
    entry_price = 50000  # BTC example
    
    print(f"Entry Price: ${entry_price:,.2f}")
    print()
    
    for threshold in thresholds:
        # Calculate trigger prices
        long_trigger_price = entry_price * (1 - threshold/100)
        short_trigger_price = entry_price * (1 + threshold/100)
        
        print(f"Stop Loss Threshold: {threshold}%")
        print(f"   Long Position Trigger: ${long_trigger_price:,.2f} (loss of ${entry_price - long_trigger_price:,.2f})")
        print(f"   Short Position Trigger: ${short_trigger_price:,.2f} (loss of ${short_trigger_price - entry_price:,.2f})")
        print()

def test_monitoring_frequency():
    """Test monitoring frequency scenarios."""
    print("⏰ Monitoring Frequency Analysis")
    print("=" * 50)
    
    frequencies = [10, 30, 60, 120, 300]  # seconds
    
    print("Different monitoring intervals and their implications:")
    print()
    
    for freq in frequencies:
        checks_per_minute = 60 / freq
        checks_per_hour = 3600 / freq
        
        print(f"Interval: {freq} seconds")
        print(f"   Checks per minute: {checks_per_minute:.1f}")
        print(f"   Checks per hour: {checks_per_hour:.0f}")
        print(f"   Responsiveness: {'High' if freq <= 30 else 'Medium' if freq <= 120 else 'Low'}")
        print(f"   API Usage: {'High' if freq <= 10 else 'Medium' if freq <= 60 else 'Low'}")
        print()

if __name__ == "__main__":
    print("🚀 Stop Loss System Configuration Test")
    print("=" * 60)
    print()
    
    # Test current configuration
    test_stop_loss_config()
    
    print("\n" + "=" * 60)
    test_stop_loss_thresholds()
    
    print("\n" + "=" * 60)
    test_monitoring_frequency()
    
    print("\n" + "=" * 60)
    print("✅ Stop Loss System Ready!")
    print(f"📊 Current Settings: {Config.STOP_LOSS_PERCENTAGE}% stop loss, {Config.BOT_HEARTBEAT_SECONDS}s monitoring")
    print("🛡️ Automatic position protection is enabled")
    print("📱 You'll receive Telegram notifications for all stop loss events")