from database.models import VPNSubscription, Payment
from utils.db import get_active_subscriptions_count, get_payments_amount, get_users_count, get_plan, get_referral_earnings
from sqlalchemy import select, func
from aiogram.types import User as TelegramUser
from database.models import User
from database.base import async_session
from aiogram.utils.deep_linking import create_start_link
from vpns.marz import marzban_service
from aiogram import Bot
import os


async def get_subscription_info(subscription: VPNSubscription) -> str:
    plan = await get_plan(subscription.plan_id)
    text = (f"<b>🔑 Подписка №{subscription.id}</b>\n\n"
            f"✨ Статус: {'✅ Активна' if subscription.is_active else '❌ Истекла'}\n"
            f"📅 Дата покупки: {subscription.start_date.strftime('%d.%m.%Y')}\n"
            f"💰 Цена: {plan.price} руб.\n"
            f"📦 Тариф: {plan.name}\n"
            f"⏰ Дата следуещего платежа: {subscription.end_date.strftime('%d.%m.%Y')}\n\n")
    
    if subscription.config_data:
        links = subscription.config_data.split("\n")
        if len(links) > 1:
            text += f"🌐 Адреса VPN:\n" + "\n".join(f"<code>{link}</code>" for link in links)
        else:
            text += f"🌐 Адрес VPN: <code>{subscription.config_data}</code>"
    else:
        text += "⚠️ Адрес VPN: не настроен"
    
    return text


async def profile_info(tg_user: TelegramUser) -> str:
    async with async_session() as session:
        # Get user with relationships
        query = select(User).where(User.telegram_id == tg_user.id)
        result = await session.execute(query)
        user = result.scalar_one()
        
        # Count active subscriptions
        active_subs_query = select(func.count(VPNSubscription.id)).where(
            (VPNSubscription.user_id == user.telegram_id) & 
            (VPNSubscription.status == 'active')
        )
        active_subs_count = await session.scalar(active_subs_query)
        
        # Sum completed payments
        payments_sum_query = select(func.coalesce(func.sum(Payment.amount), 0)).where(
            (Payment.user_id == user.telegram_id) & 
            (Payment.status == 'completed')
        )
        total_payments = await session.scalar(payments_sum_query)

        balance = user.balance
        
        text = (f"<b>👤 Профиль</b>\n\n"
                f"📊 Активных подписок: {active_subs_count}\n"
                f"👑 Пополнений на сумму: {total_payments} руб.\n"
                f"💰 Баланс: {balance} руб.\n"
                f"📅 Дата регистрации: {user.created_at.strftime('%d.%m.%Y')}")
        return text

async def referal_info(tg_user: TelegramUser, bot: Bot) -> str:
    async with async_session() as session:
        query = select(func.count(User.telegram_id)).where(User.ref_id == tg_user.id)
        referral_count = await session.scalar(query)
        referal_link = await create_start_link(bot, tg_user.id, encode=True)
        referral_earnings = await get_referral_earnings(tg_user.id)
        return (f"<b>🔗 Реферальная система</b>\n\n" \
                f"👤 Количество ваших рефералов: {referral_count}\n" \
                f"🔗 Ваша реферальная ссылка: {referal_link}\n" \
                f"💰 Заработано с нами: {referral_earnings} руб.\n\n" \
                f"<i>Приглашайте друзей и знакомых и получайте {os.getenv('referal_percent')}% от их покупок</i>")

async def get_admin_stats() -> str:
    users_count = await get_users_count()
    active_subs_count = await get_active_subscriptions_count()
    payments_amount = await get_payments_amount()
    system_stats = await marzban_service.get_system_stats()
    nodes = await marzban_service.get_nodes()

    return (f"<b>📈 Статистика:</b>\n\n" \
            f"👤 Пользователей: {users_count}\n" \
            f"📊 Активных подписок: {active_subs_count}\n" \
            f"💰 Платежей на сумму: {payments_amount} руб.\n" \
            f"💻 Использование процессора: {system_stats.cpu_usage}%\n" \
            f"📥 Текущая скорость входящего траффика: {int(system_stats.incoming_bandwidth_speed)/1024} KB/s\n" \
            f"📤 Текущая скорость исходящего траффика: {int(system_stats.outgoing_bandwidth_speed)/1024} KB/s\n" \
            f"🌐 Узлов: {len(nodes)}\n" \
    )

async def get_user_info(user: User) -> str:
    async with async_session() as session:
        # Get user with relationships
        query = select(User).where(User.telegram_id == user.telegram_id)
        result = await session.execute(query)
        user = result.scalar_one()
        
        # Count active subscriptions
        active_subs_query = select(func.count(VPNSubscription.id)).where(
            (VPNSubscription.user_id == user.telegram_id) & 
            (VPNSubscription.status == 'active')
        )
        active_subs_count = await session.scalar(active_subs_query)
        
        # Sum completed payments
        payments_sum_query = select(func.coalesce(func.sum(Payment.amount), 0)).where(
            (Payment.user_id == user.telegram_id) & 
            (Payment.status == 'completed')
        )
        total_payments = await session.scalar(payments_sum_query)
        return (f"<b>👤 Информация о пользователе</b>\n\n" \
                f"🆔 ID: {user.telegram_id}\n" \
                f"👤 Username: {user.username}\n" \
                f"📅 Дата регистрации: {user.created_at.strftime('%d.%m.%Y')}\n" \
                f"📊 Активных подписок: {active_subs_count}\n" \
                f"💰 Пополнений на сумму: {total_payments} руб.\n" \
                f"💰 Баланс: {user.balance} руб."
                )
