"""
بروزرسانی خودکار قیمت از نرخ TON
منطق: قیمت تلگرام پرمیوم = X دلار × نرخ دلار به تومان
نرخ دلار از TON محاسبه میشه (TON/USDT × ضریب)
"""
import urllib.request
import json
import database as db

# ===== تنظیمات قیمت خودکار =====
# قیمت رسمی تلگرام پرمیوم به دلار
TELEGRAM_PREMIUM_PRICES_USD = {
    '1 ماهه':  4.99,
    '3 ماهه':  14.99,
    '6 ماهه':  27.99,
    '12 ماهه': 47.99,
}

# ضریب سود (مثلاً 1.25 = 25% سود)
PROFIT_MARGIN = 1.25

# سرویس‌هایی که قیمت خودکار دارن
AUTO_PRICE_SERVICES = ['تلگرام پرمیوم']

def get_ton_price_usd():
    """دریافت قیمت TON به دلار از CoinGecko (بدون API key)"""
    try:
        url = "https://api.coingecko.com/api/v3/simple/price?ids=the-open-network&vs_currencies=usd,irr"
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        with urllib.request.urlopen(req, timeout=10) as r:
            data = json.loads(r.read())
        ton_usd = data['the-open-network']['usd']
        ton_irr = data['the-open-network'].get('irr', 0)
        return ton_usd, ton_irr
    except Exception as e:
        print(f"خطا در دریافت قیمت TON: {e}")
        return None, None

def get_usd_to_toman():
    """دریافت نرخ دلار به تومان از سایت نرخ (بدون API key)"""
    try:
        # از navasan.tech استفاده میکنیم که رایگانه
        url = "https://api.navasan.tech/latest/?api_key=free&item=usd_sell"
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        with urllib.request.urlopen(req, timeout=10) as r:
            data = json.loads(r.read())
        rate = int(data.get('usd_sell', {}).get('value', 0))
        if rate > 10000:  # ریال
            return rate // 10  # تبدیل به تومان
        return rate
    except:
        pass

    # backup: از exchangerate-api
    try:
        url = "https://open.er-api.com/v6/latest/USD"
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        with urllib.request.urlopen(req, timeout=10) as r:
            data = json.loads(r.read())
        irr_rate = data.get('rates', {}).get('IRR', 0)
        if irr_rate > 0:
            return int(irr_rate / 10)  # تبدیل ریال به تومان
    except:
        pass

    return None

def calculate_auto_prices():
    """محاسبه قیمت‌های جدید بر اساس نرخ لحظه‌ای"""
    usd_toman = get_usd_to_toman()
    if not usd_toman or usd_toman < 10000:
        print("❌ نرخ دلار دریافت نشد")
        return None

    results = {}
    for duration, usd_price in TELEGRAM_PREMIUM_PRICES_USD.items():
        raw = usd_price * usd_toman * PROFIT_MARGIN
        # گرد کردن به نزدیک‌ترین ۵۰۰۰
        rounded = round(raw / 5000) * 5000
        results[duration] = {
            'usd': usd_price,
            'usd_rate': usd_toman,
            'raw': int(raw),
            'price': int(rounded),
        }

    return results, usd_toman

def update_telegram_premium_prices(dry_run=False):
    """بروزرسانی قیمت تلگرام پرمیوم در دیتابیس"""
    result = calculate_auto_prices()
    if not result:
        return False, "نرخ دلار دریافت نشد"

    prices, usd_rate = result
    products = db.get_all_products_admin()
    updated = []

    for p in products:
        if p['service'] in AUTO_PRICE_SERVICES:
            duration = p['duration']
            if duration in prices:
                new_price = prices[duration]['price']
                if not dry_run:
                    db.update_product_price(p['id'], new_price)
                updated.append({
                    'id': p['id'],
                    'service': p['service'],
                    'duration': duration,
                    'old_price': p['price'],
                    'new_price': new_price,
                })

    return True, {
        'usd_rate': usd_rate,
        'updated': updated,
        'prices': prices,
    }

async def auto_update_prices(context):
    """تسک خودکار scheduler - هر ۶ ساعت یه بار"""
    from config import ADMIN_IDS
    setting = db.get_setting('auto_price_enabled', '0')
    if setting != '1':
        return

    success, result = update_telegram_premium_prices()
    if not success:
        return

    # اطلاع‌رسانی به ادمین
    usd = result['usd_rate']
    text = f"🔄 *قیمت‌ها بروز شد*\n\n💵 نرخ دلار: {usd:,} تومان\n\n"
    for u in result['updated']:
        diff = u['new_price'] - u['old_price']
        arrow = "📈" if diff > 0 else "📉" if diff < 0 else "➡️"
        text += f"{arrow} {u['service']} {u['duration']}\n"
        text += f"   {u['old_price']:,} ← {u['new_price']:,} ت\n\n"

    for admin_id in ADMIN_IDS:
        try:
            await context.bot.send_message(admin_id, text, parse_mode='Markdown')
        except:
            pass
