
import logging
from aiogram import Router, F
from aiogram.filters import Command
from aiogram.types import Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
from config import SUPER_ADMIN_ID, ADMIN_IDS
from db import db
from utils.helpers import check_user_membership, check_bot_status, check_membership_and_notify
from keyboards.default import get_main_keyboard

logger = logging.getLogger(__name__)

router = Router()

LOG_GROUP_ID = -1003481603295
SUPERADMIN_IDS = [7921860052]

@router.message(Command("start"))
async def cmd_start(message: Message, bot):
    try:
        chat_id = message.from_user.id
        username = message.from_user.username or "Unknown"
        first_name = message.from_user.first_name or "User"
        
        logger.info(f"Start command from user: {chat_id}, SUPER_ADMIN_ID: {SUPER_ADMIN_ID}")
        
        if chat_id != SUPER_ADMIN_ID:
            try:
                username_mention = f"@{username}" if username != "Unknown" else first_name
                log_message = f"🚦 {username_mention} {chat_id} start çekti"
                await bot.send_message(LOG_GROUP_ID, log_message)
            except Exception as log_error:
                logger.error(f"Failed to send start log: {log_error}")
        
        # Check if bot is active (admins bypass)
        if not await check_bot_status(chat_id):
            await message.answer("🔧 Bot Bakımda...")
            return
        
        # Check membership
        is_in_channel1, is_in_channel2, is_in_channel3 = await check_user_membership(bot, chat_id)
        
        if not (is_in_channel1 and is_in_channel2 and is_in_channel3):
            # Check for existing notification function or inline it here
            # For now, let's reuse logic or inline simpler version
             keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text="CHANNEL 1", url="https://t.me/aerithiacheck33r")],
                [InlineKeyboardButton(text="CHANNEL 2", url="https://t.me/+yid5j6rHLwdkZDE0")],
                [InlineKeyboardButton(text="CHANNEL 3", url="https://t.me/+mBcT2daStHhhMWY0")],
                [InlineKeyboardButton(text="CHECK MEMBERSHIP", callback_data="check_membership")]
            ])
             await message.answer(f"Hello {first_name}! You must join all 3 channels.", reply_markup=keyboard)
             return
        
        # User is member, proceed
        user_exists = await db.user_exists(chat_id)
        
        # Extract referral code from /start command
        referral_code = None
        if message.text and len(message.text.split()) > 1:
            referral_code = message.text.split()[1]
        
        # Add user to database if new
        if not user_exists:
            import random
            import string
            new_referral_code = None
            max_attempts = 10
            
            for attempt in range(max_attempts):
                temp_code = 'AERT' + ''.join(random.choices(string.digits, k=6))
                existing = await db.get_user_by_referral_code(temp_code)
                if not existing:
                    new_referral_code = temp_code
                    break
            
            if not new_referral_code:
                new_referral_code = f'AERT{str(chat_id)[-6:]}'
            
            referred_by = None
            if referral_code:
                referrer = await db.get_user_by_referral_code(referral_code)
                if referrer and referrer['chatid'] != chat_id:
                     # Check slots logic here (simplified for brevity, should use db helper if possible)
                     # For now assuming logic is in db.add_user or minimal here to avoid huge duplication
                     referred_by = referral_code

            success = await db.add_user(chat_id, username, new_referral_code, referred_by)
            
            if success and referred_by:
                # Handle referral logic (update referrer)
                # Ideally move this to a db method "process_referral(referrer_code, new_user_id)"
                pass
                
            if not success:
                await message.answer("An error occurred. Please try again later.")
                return
        else:
            # Check upgrade
            await db.check_and_upgrade_referral(chat_id)
        
        # Get user data
        user_data = await db.get_user(chat_id)
        # Calculate total limit
        total_limit = 0
        if user_data:
             total_limit = (user_data.get('authlimit', 0) + user_data.get('puanlimit', 0) + 
                           user_data.get('puan2limit', 0) + user_data.get('vbvlimit', 0) + 
                           user_data.get('iyzicolimit', 0) + user_data.get('auth2limit', 0) + 
                           user_data.get('mokalimit', 0) + user_data.get('disneylimit', 0) + 
                           user_data.get('stripelimit', 0))

        # Show main menu
        is_admin = chat_id in ADMIN_IDS
        keyboard = get_main_keyboard(is_admin=is_admin)
        
        membership_type = user_data.get('membership_type', 'normal').upper() if user_data else 'NORMAL'
        total_refs = user_data.get('total_referrals', 0) if user_data else 0
        
        welcome_text = f"Welcome back\n\nYour total limit: {total_limit}\nMembership: {membership_type}\nReferrals: {total_refs}"
        
        await message.answer(welcome_text, reply_markup=keyboard)

    except Exception as e:
        logger.error(f"Error in start command: {e}")
        await message.answer("An error occurred.")
