from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from aiogram import Bot
from utils.db import get_active_subscriptions
from utils.backup import create_backup


async def check_expiring_subscriptions(bot: Bot):
    """Check for subscriptions that are about to expire and send notifications"""
    now = datetime.now(ZoneInfo("Europe/Moscow"))
    
    try:
        # Query for subscriptions expiring soon
        expiring_subs = await get_active_subscriptions()
        
        # Send notifications for each expiring subscription
        for sub in expiring_subs:
            try:
                # Convert end_date to Moscow timezone if it's naive
                end_date = sub.end_date
                if end_date.tzinfo is None:
                    end_date = end_date.replace(tzinfo=ZoneInfo("Europe/Moscow"))
                
                days_left = (end_date - now).days
                
                if days_left == 0:
                    message = (
                        f"⚠️ <b>Внимание!</b>\n\n"
                        f"Ваша подписка №{sub.id} истекает сегодня!\n"
                        f"Не забудьте продлить подписку, чтобы продолжить пользоваться VPN."
                    )
                elif days_left == 1:
                    message = (
                        f"⚠️ <b>Внимание!</b>\n\n"
                        f"Ваша подписка №{sub.id} истекает завтра!\n"
                        f"Не забудьте продлить подписку, чтобы продолжить пользоваться VPN."
                    )
                elif days_left == 2:
                    message = (
                        f"⚠️ <b>Внимание!</b>\n\n"
                        f"Ваша подписка №{sub.id} истекает через 2 дня!\n"
                        f"Не забудьте продлить подписку, чтобы продолжить пользоваться VPN."
                    )
                else:
                    continue

                if sub.user and sub.user.telegram_id:
                    await bot.send_message(
                        chat_id=sub.user.telegram_id,
                        text=message,
                        parse_mode="HTML"
                    )
                else:
                    print(f"Warning: Subscription {sub.id} has no associated user or telegram_id")

            except Exception as e:
                print(f"Error processing subscription {sub.id}: {str(e)}")
                continue
                
    except Exception as e:
        print(f"Error in check_expiring_subscriptions: {str(e)}")

async def run_backup(bot: Bot):
    """Run database backup"""
    print("Starting scheduled database backup...")
    success = await create_backup(bot)
    if success:
        print("Scheduled backup completed successfully")
    else:
        print("Scheduled backup failed")

def setup_scheduler(bot: Bot):
    """Setup the scheduler with all scheduled tasks"""
    scheduler = AsyncIOScheduler(timezone="Europe/Moscow")
    
    # Schedule subscription checks twice a day (10:00 and 18:00)
    scheduler.add_job(
        check_expiring_subscriptions,
        trigger="cron",
        hour="10,18",
        minute="15",
        args=[bot]
    )
    
    # Schedule daily database backup at 03:00
    scheduler.add_job(
        run_backup,
        trigger="cron",
        hour="0",
        minute="01",
        args=[bot]
    )
    
    return scheduler 