#!/usr/bin/env python3
"""
Test script for Multi-Timeframe Signal Rules
Verifies that the new rules are correctly implemented
"""

def get_allowed_signals(w1_trend, d1_trend, h1_trend):
    """
    Определяет разрешенные сигналы (BUY/SELL/HOLD) на основе комбинации трендов.
    """
    # Нормализация трендов: sideways = тренд старшего ТФ
    d1_normalized = w1_trend if d1_trend == 'sideways' else d1_trend
    h1_normalized = d1_normalized if h1_trend == 'sideways' else h1_trend
    
    # Применяем правила
    if w1_trend == 'down' and d1_normalized == 'up' and h1_normalized == 'up':
        return ['BUY', 'SELL']
    elif w1_trend == 'up' and d1_normalized == 'down' and h1_normalized == 'down':
        return ['BUY', 'SELL']
    elif w1_trend == 'down' and d1_normalized == 'down' and h1_normalized == 'up':
        return ['SELL']
    elif w1_trend == 'up' and d1_normalized == 'up' and h1_normalized == 'down':
        return ['BUY']
    elif w1_trend == 'up' and d1_normalized == 'down' and h1_normalized == 'up':
        return ['BUY']
    elif w1_trend == 'down' and d1_normalized == 'up' and h1_normalized == 'down':
        return ['SELL']
    elif w1_trend == 'down' and d1_normalized == 'down' and h1_normalized == 'down':
        return ['SELL']
    elif w1_trend == 'up' and d1_normalized == 'up' and h1_normalized == 'up':
        return ['BUY']  # Сильный восходящий тренд - покупка
    else:
        return ['HOLD']

def test_multi_timeframe_rules():
    """Test all combinations according to the rules"""
    
    test_cases = [
        # Rule 1: W1(d), D1(u), H1(u) -> BUY, SELL
        ('down', 'up', 'up', ['BUY', 'SELL'], "Коррекция в восходящем тренде"),
        
        # Rule 2: W1(u), D1(d), H1(d) -> BUY, SELL  
        ('up', 'down', 'down', ['BUY', 'SELL'], "Откат в восходящем тренде"),
        
        # Rule 3: W1(d), D1(d), H1(u) -> SELL ONLY
        ('down', 'down', 'up', ['SELL'], "Локальный отскок в нисходящем тренде"),
        
        # Rule 4: W1(u), D1(u), H1(d) -> BUY ONLY
        ('up', 'up', 'down', ['BUY'], "Локальная коррекция в восходящем тренде"),
        
        # Rule 5: W1(u), D1(d), H1(u) -> BUY ONLY
        ('up', 'down', 'up', ['BUY'], "Возобновление роста после отката"),
        
        # Rule 6: W1(d), D1(u), H1(d) -> SELL ONLY
        ('down', 'up', 'down', ['SELL'], "Возобновление падения после отскока"),
        
        # Rule 7: W1(d), D1(d), H1(d) -> SELL ONLY
        ('down', 'down', 'down', ['SELL'], "Сильный нисходящий тренд"),
        
        # Rule 8: W1(u), D1(u), H1(u) -> BUY ONLY
        ('up', 'up', 'up', ['BUY'], "Сильный восходящий тренд"),
        
        # Test normalization: H1(sideways) + D1(up) -> H1(up)
        ('down', 'up', 'sideways', ['BUY', 'SELL'], "H1 sideways normalized to D1(up)"),
        ('up', 'up', 'sideways', ['BUY'], "H1 sideways normalized to D1(up) -> Rule 4: BUY ONLY"),
        
        # Test normalization: D1(sideways) + W1(down) -> D1(down)
        ('down', 'sideways', 'up', ['SELL'], "D1 sideways normalized to W1(down)"),
        ('down', 'sideways', 'sideways', ['SELL'], "Both D1 and H1 sideways normalized to W1(down)"),
    ]
    
    print("🧪 Testing Multi-Timeframe Signal Rules")
    print("=" * 60)
    
    all_passed = True
    
    for i, (w1, d1, h1, expected, description) in enumerate(test_cases, 1):
        result = get_allowed_signals(w1, d1, h1)
        
        # Sort for comparison
        result_sorted = sorted(result)
        expected_sorted = sorted(expected)
        
        if result_sorted == expected_sorted:
            status = "✅ PASS"
        else:
            status = "❌ FAIL"
            all_passed = False
        
        print(f"{i:2d}. {status} | {description}")
        print(f"     W1:{w1:6} D1:{d1:6} H1:{h1:6} -> {result} (expected {expected})")
        print()
    
    print("=" * 60)
    if all_passed:
        print("✅ All tests PASSED!")
    else:
        print("❌ Some tests FAILED!")
    
    return all_passed

def test_real_world_scenarios():
    """Test with real ticker scenarios"""
    
    print("\n🌍 Real-World Scenarios Test")
    print("=" * 60)
    
    # Example scenarios based on actual market conditions
    scenarios = [
        {
            "name": "MOEX Index (bullish with pullback)",
            "w1": "up", "d1": "down", "h1": "down",
            "expected": ["BUY", "SELL"],
            "reason": "W1↑ but D1↓+H1↓ - pullback in uptrend"
        },
        {
            "name": "GAZP (bearish with correction)", 
            "w1": "down", "d1": "up", "h1": "up",
            "expected": ["BUY", "SELL"],
            "reason": "W1↓ but D1↑+H1↑ - correction in downtrend"
        },
        {
            "name": "SBER (bullish dip)",
            "w1": "up", "d1": "up", "h1": "down", 
            "expected": ["BUY"],
            "reason": "W1↑+D1↑ dominant, H1↓ - local dip"
        },
        {
            "name": "VTBR (bearish bounce)",
            "w1": "down", "d1": "down", "h1": "up",
            "expected": ["SELL"],
            "reason": "W1↓+D1↓ dominant, H1↑ - local bounce"
        },
        {
            "name": "PLZL (strong uptrend)",
            "w1": "up", "d1": "up", "h1": "up",
            "expected": ["BUY"],
            "reason": "Strong uptrend - look for continuation opportunities"
        }
    ]
    
    all_passed = True
    
    for i, scenario in enumerate(scenarios, 1):
        result = get_allowed_signals(scenario["w1"], scenario["d1"], scenario["h1"])
        
        result_sorted = sorted(result)
        expected_sorted = sorted(scenario["expected"])
        
        if result_sorted == expected_sorted:
            status = "✅ PASS"
        else:
            status = "❌ FAIL"
            all_passed = False
        
        print(f"{i}. {status} | {scenario['name']}")
        print(f"    Trends: W1={scenario['w1']}, D1={scenario['d1']}, H1={scenario['h1']}")
        print(f"    Expected: {scenario['expected']}, Got: {result}")
        print(f"    Reason: {scenario['reason']}")
        print()
    
    print("=" * 60)
    if all_passed:
        print("✅ All real-world scenarios PASSED!")
    else:
        print("❌ Some real-world scenarios FAILED!")
    
    return all_passed

if __name__ == "__main__":
    print("🚨 Multi-Timeframe Signal Rules Test")
    print("=" * 60)
    
    # Test the basic rules
    basic_passed = test_multi_timeframe_rules()
    
    # Test real-world scenarios
    real_passed = test_real_world_scenarios()
    
    print("\n" + "=" * 60)
    print("🎯 FINAL RESULT:")
    if basic_passed and real_passed:
        print("✅ ALL TESTS PASSED - Rules implemented correctly!")
    else:
        print("❌ SOME TESTS FAILED - Rules need review!")
    
    print("\n📝 Key insights:")
    print("  1. Rules clearly define when BUY/SELL/HOLD are allowed")
    print("  2. Normalization handles sideways trends correctly")
    print("  3. Real-world scenarios follow the expected logic")
    print("  4. Strong trends (all TFs aligned) limit signal types for reversals")