"""
AI Analysis API Routes
تحلیل هوشمند بازار با DeepSeek AI
"""

from flask import Blueprint, request, jsonify
from flask_login import login_required
from app import limiter
from app.services.deepseek_service import DeepSeekService
import yfinance as yf

ai_api = Blueprint('ai_api', __name__)
deepseek = DeepSeekService()


def get_market_data(symbol: str, interval: str = '1h'):
    """دریافت داده‌های بازار برای تحلیل AI"""
    try:
        ticker = yf.Ticker(symbol)
        hist = ticker.history(period='2d', interval=interval)
        
        if hist.empty:
            return None
        
        current_price = float(hist['Close'].iloc[-1])
        previous_close = float(hist['Close'].iloc[-2]) if len(hist) > 1 else current_price
        change_24h = ((current_price - previous_close) / previous_close) * 100
        
        # دریافت داده‌های بیشتر برای تحلیل
        hist_30d = ticker.history(period='30d', interval=interval)
        
        # محاسبه نوسان‌پذیری
        if len(hist_30d) > 1:
            returns = hist_30d['Close'].pct_change().dropna()
            volatility = returns.std() * (252 ** 0.5) * 100
        else:
            volatility = 0
        
        return {
            'symbol': symbol,
            'price': current_price,
            'change_24h': round(change_24h, 2),
            'volume': int(hist['Volume'].iloc[-1]) if not hist['Volume'].empty else 0,
            'current_volatility': round(volatility, 1),
            'historical_volatility': round(volatility, 1),
            'volatility_outlook': 'Elevated risk' if volatility > 50 else 'Low risk' if volatility < 30 else 'Normal',
            'liquidity_zones': [
                {'level': current_price * 0.98, 'strength': 0.7},
                {'level': current_price * 1.02, 'strength': 0.6}
            ],
            'order_flow_anomaly': 'MODERATE',
            'scenarios': {
                'bullish': 35,
                'bearish': 30,
                'neutral': 35
            },
            'price_targets': {
                'bullish': current_price * 1.05,
                'bearish': current_price * 0.95,
                'most_likely': current_price
            }
        }
    except Exception as e:
        print(f"Error getting market data: {e}")
        return None


@ai_api.route('/analyze', methods=['GET'])
@limiter.limit("30 per minute")
def analyze_market():
    """تحلیل هوشمند بازار با DeepSeek AI"""
    symbol = request.args.get('symbol', 'BTC-USD')
    interval = request.args.get('interval', '1h')
    
    # دریافت داده‌های بازار
    market_data = get_market_data(symbol, interval)
    
    if not market_data:
        return jsonify({'error': 'Unable to fetch market data'}), 404
    
    # تحلیل با DeepSeek
    analysis = deepseek.analyze_market(market_data)
    
    return jsonify({
        'symbol': symbol,
        'ai_analysis': analysis,
        'market_data': market_data,
        'timestamp': datetime.now().isoformat(),
        'status': 'success'
    })


@ai_api.route('/test', methods=['GET'])
def test_deepseek():
    """تست اتصال به DeepSeek API"""
    result = deepseek.test_connection()
    return jsonify(result)