#!/usr/bin/env python3
"""
Comprehensive test for improved OpenRouter prompts
Tests both AI analysis and trading plan generation with gold-specific prompts
"""

import asyncio
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))

from app.services.openrouter import openrouter_service
from app.schemas.schemas import AIAnalysisRequest, PriceData


async def test_ai_analysis():
    """Test improved AI analysis with gold-specific prompts"""
    print("\n" + "="*70)
    print("TEST 1: AI SCENARIO ANALYSIS (Improved Prompt)")
    print("="*70)
    
    # Create sample price data (time is Unix timestamp)
    import time as time_module
    base_time = int(time_module.time()) - (5 * 86400)  # 5 days ago
    
    price_data = [
        PriceData(time=base_time, open=2040.0, high=2055.0, low=2038.0, close=2052.0, volume=10000),
        PriceData(time=base_time + 86400, open=2052.0, high=2060.0, low=2048.0, close=2058.0, volume=12000),
        PriceData(time=base_time + 2*86400, open=2058.0, high=2065.0, low=2055.0, close=2062.0, volume=11000),
        PriceData(time=base_time + 3*86400, open=2062.0, high=2068.0, low=2059.0, close=2064.0, volume=13000),
        PriceData(time=base_time + 4*86400, open=2064.0, high=2070.0, low=2061.0, close=2067.0, volume=14000),
    ]
    
    # Create analysis request
    request = AIAnalysisRequest(
        current_price=2067.50,
        price_data=price_data,
        indicators=[
            {"name": "RSI_14", "value": 62.5},
            {"name": "MACD", "value": 2.3, "signal": 1.8, "histogram": 0.5},
            {"name": "EMA_20", "value": 2058.0},
            {"name": "EMA_50", "value": 2048.0},
            {"name": "ATR_14", "value": 12.5},
            {"name": "Volume_Trend", "value": "Increasing"}
        ]
    )
    
    try:
        print("\n📊 Analyzing gold market with enhanced prompts...")
        print(f"Current Price: ${request.current_price:.2f}")
        print(f"Technical Setup: Bullish trend, RSI at 62.5, MACD positive")
        print("\nSending request to OpenRouter API...")
        
        response = await openrouter_service.analyze_scenario(request)
        
        print("\n✅ Analysis Complete!")
        print("\n" + "-"*70)
        print(f"Recommendation: {response.recommendation.value}")
        print(f"Confidence: {response.confidence:.1f}%")
        print(f"Risk Level: {response.risk_level.value}")
        print(f"\nReasoning:\n{response.reasoning}")
        print(f"\nSupport Levels: {', '.join([f'${x:.2f}' for x in response.support_resistance.support])}")
        print(f"Resistance Levels: {', '.join([f'${x:.2f}' for x in response.support_resistance.resistance])}")
        print("-"*70)
        return True
        
    except Exception as e:
        print(f"\n❌ ERROR: {str(e)}")
        import traceback
        traceback.print_exc()
        return False


async def test_trading_plan_generation():
    """Test improved trading plan generation with comprehensive gold prompts"""
    print("\n" + "="*70)
    print("TEST 2: DAILY TRADING PLAN GENERATION (Enhanced Prompt)")
    print("="*70)
    
    # Create a comprehensive trading plan prompt
    test_prompt = """You are a senior gold (XAU/USD) trading strategist with expertise in precious metals markets, technical analysis, and professional risk management. Generate a comprehensive daily trading plan for a gold trader based on current market conditions.

═══════════════════════════════════════════════════════════
TRADER'S PROFILE & ACCOUNT:
═══════════════════════════════════════════════════════════
- Current Gold Price: $2,067.50
- Risk Tolerance: MODERATE
- Available Trading Capital: $10,000

═══════════════════════════════════════════════════════════
PREFERRED TECHNICAL ANALYSIS FRAMEWORK:
═══════════════════════════════════════════════════════════
Primary Indicators: RSI, MACD, Moving Averages (EMA 20/50), ATR

DETAILED INDICATOR CONFIGURATION:
- RSI (14): Currently at 62.5 (trending higher)
- MACD: Bullish crossover (2.3 / 1.8 / +0.5)
- EMA 20: $2,058.00 (price above)
- EMA 50: $2,048.00 (price above)
- ATR (14): $12.50 (average volatility)

RECENT PRICE ACTION (last 5 periods):
  1. Open: $2,040.00, High: $2,055.00, Low: $2,038.00, Close: $2,052.00
  2. Open: $2,052.00, High: $2,060.00, Low: $2,048.00, Close: $2,058.00
  3. Open: $2,058.00, High: $2,065.00, Low: $2,055.00, Close: $2,062.00
  4. Open: $2,062.00, High: $2,068.00, Low: $2,059.00, Close: $2,064.00
  5. Open: $2,064.00, High: $2,070.00, Low: $2,061.00, Close: $2,067.00

Generate a professional trading plan following the comprehensive format requested.
"""
    
    try:
        print("\n📈 Generating daily trading plan with enhanced prompts...")
        print("Trader Profile: $10K capital, MODERATE risk tolerance")
        print("Market Conditions: Bullish trend, strong momentum")
        print("\nSending request to OpenRouter API...")
        
        plan = await openrouter_service.generate_trading_plan(test_prompt)
        
        print("\n✅ Trading Plan Generated!")
        print(f"\nRaw response type: {type(plan)}")
        print(f"Raw response: {plan}")
        print("\n" + "-"*70)
        print(f"Market Bias: {plan.get('market_bias', 'N/A')}")
        print(f"Confidence: {plan.get('confidence', 0):.1f}%")
        print(f"Daily Target: ${plan.get('daily_target', 0):.2f}")
        print(f"Max Loss: ${plan.get('max_loss', 0):.2f}")
        print(f"\nEntry Zone: ${plan.get('entry_zone_min', 0):.2f} - ${plan.get('entry_zone_max', 0):.2f}")
        print(f"Target Price: ${plan.get('target_price', 0):.2f}")
        print(f"Stop Loss: ${plan.get('stop_loss', 0):.2f}")
        
        print(f"\nSupport Levels:")
        for i, level in enumerate(plan.get('support_levels', []), 1):
            print(f"  {i}. ${level:.2f}")
            
        print(f"\nResistance Levels:")
        for i, level in enumerate(plan.get('resistance_levels', []), 1):
            print(f"  {i}. ${level:.2f}")
            
        print(f"\nMax Trades: {plan.get('max_trades', 0)}")
        print(f"\nTrading Notes:\n{plan.get('trading_notes', 'N/A')}")
        print(f"\nDetailed Reasoning:\n{plan.get('reasoning', 'N/A')}")
        print("-"*70)
        return True
        
    except Exception as e:
        print(f"\n❌ ERROR: {str(e)}")
        import traceback
        traceback.print_exc()
        return False


async def main():
    """Run all tests"""
    print("\n" + "="*70)
    print("OPENROUTER API - GOLD TRADING PROMPTS TEST SUITE")
    print("="*70)
    print(f"API Key: {'✓ Set' if openrouter_service.api_key else '✗ Not Set'}")
    print(f"Model: {openrouter_service.model}")
    print(f"Base URL: {openrouter_service.base_url}")
    
    if not openrouter_service.api_key:
        print("\n❌ ERROR: OPENROUTER_API_KEY not set")
        return False
    
    # Run tests
    test1_passed = await test_ai_analysis()
    test2_passed = await test_trading_plan_generation()
    
    # Summary
    print("\n" + "="*70)
    print("TEST SUMMARY")
    print("="*70)
    print(f"AI Scenario Analysis: {'✅ PASSED' if test1_passed else '❌ FAILED'}")
    print(f"Trading Plan Generation: {'✅ PASSED' if test2_passed else '❌ FAILED'}")
    print("="*70)
    
    return test1_passed and test2_passed


if __name__ == "__main__":
    success = asyncio.run(main())
    sys.exit(0 if success else 1)
