"""
Cryptocurrency API Routes
دریافت لیست ارزهای دیجیتال در حال صعود و نزول از CoinMarketCap
"""

from flask import Blueprint, request, jsonify
from flask_login import login_required
from app import limiter
from app.services.coinmarketcap_service import CoinMarketCapService

crypto_api = Blueprint('crypto_api', __name__)
cmc_service = CoinMarketCapService()


@crypto_api.route('/top-gainers', methods=['GET'])
@limiter.limit("30 per minute")
def get_top_gainers():
    """دریافت لیست ارزهای دیجیتال با بیشترین رشد قیمت در 24 ساعت"""
    limit = request.args.get('limit', 50, type=int)
    convert = request.args.get('convert', 'USD')
    
    # محدودیت حداکثر 100
    limit = min(limit, 100)
    
    result = cmc_service.get_top_gainers(limit=limit, convert=convert)
    return jsonify(result)


@crypto_api.route('/top-losers', methods=['GET'])
@limiter.limit("30 per minute")
def get_top_losers():
    """دریافت لیست ارزهای دیجیتال با بیشترین کاهش قیمت در 24 ساعت"""
    limit = request.args.get('limit', 50, type=int)
    convert = request.args.get('convert', 'USD')
    
    limit = min(limit, 100)
    
    result = cmc_service.get_top_losers(limit=limit, convert=convert)
    return jsonify(result)


@crypto_api.route('/search', methods=['GET'])
def search_crypto():
    """جستجوی ارز دیجیتال بر اساس نام یا نماد"""
    query = request.args.get('q', '').upper()
    limit = request.args.get('limit', 20, type=int)
    
    if not query:
        return jsonify({'error': 'Please provide a search query'}), 400
    
    # دریافت لیست کامل و فیلتر
    all_cryptos = cmc_service.get_top_gainers(limit=200)
    
    filtered = [
        crypto for crypto in all_cryptos.get('cryptocurrencies', [])
        if query in crypto['symbol'].upper() or query in crypto['name'].upper()
    ][:limit]
    
    return jsonify({
        'cryptocurrencies': filtered,
        'total_count': len(filtered),
        'query': query,
        'status': 'success'
    })


@crypto_api.route('/crypto/<symbol>', methods=['GET'])
def get_crypto_details(symbol):
    """دریافت اطلاعات دقیق یک ارز دیجیتال"""
    convert = request.args.get('convert', 'USD')
    result = cmc_service.get_crypto_info(symbol.upper(), convert=convert)
    
    if result.get('cryptocurrencies') and len(result['cryptocurrencies']) > 0:
        return jsonify(result['cryptocurrencies'][0])
    else:
        return jsonify({'error': 'Cryptocurrency not found'}), 404