import logging
import asyncio
from telethon import TelegramClient, events

from config import BOT_TOKEN, ADMIN_IDS, API_ID, API_HASH
from handlers.start import start
from handlers.callback import handle_callback
from handlers.message import handle_message
from handlers.admin_handler import admin_panel, handle_admin_message, handle_admin_callback
from utils.data_manager import get_settings

logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    level=logging.INFO
)

bot = TelegramClient("bot", API_ID, API_HASH).start(bot_token=BOT_TOKEN)

@bot.on(events.NewMessage(pattern="/start"))
async def start_handler(event):
    sender = await event.get_sender()
    username = f"@{sender.username}" if sender.username else sender.first_name
    print(f"[START] {username} ({sender.id}) memulai bot")
    await start(bot, event.message)

@bot.on(events.NewMessage(pattern="/admin"))
async def admin_handler(event):
    sender = await event.get_sender()
    username = f"@{sender.username}" if sender.username else sender.first_name
    print(f"[ADMIN] {username} ({sender.id}) membuka panel admin")
    await admin_panel(bot, event.message)

@bot.on(events.NewMessage)
async def message_router(event):
    if event.message.text and event.message.text.startswith("/"):
        return
    settings = get_settings()
    sender = await event.get_sender()
    username = f"@{sender.username}" if sender.username else sender.first_name

    if settings.get("maintenance") and sender.id not in ADMIN_IDS:
        print(f"[MAINTENANCE] {username} ({sender.id}) mencoba akses saat maintenance")
        await event.reply("🔧 Bot sedang dalam maintenance. Coba lagi nanti.")
        return

    print(f"[PESAN] {username} ({sender.id}): {event.message.text}")
    handled = await handle_admin_message(bot, event.message)
    if not handled:
        await handle_message(bot, event.message)

@bot.on(events.CallbackQuery)
async def callback_router(event):
    sender = await event.get_sender()
    username = f"@{sender.username}" if sender.username else sender.first_name
    print(f"[CALLBACK] {username} ({sender.id}): {event.data.decode()}")
    handled = await handle_admin_callback(bot, event)
    if not handled:
        await handle_callback(bot, event)

async def main():
    me = await bot.get_me()
    print(f"Bot Running... @{me.username}")
    await bot.run_until_disconnected()

if __name__ == "__main__":
    with bot:
        bot.loop.run_until_complete(main())