import os
import sys
import logging
import atexit
import tempfile
from telegram.ext import Application, CommandHandler, CallbackQueryHandler
from bot.config import Config
from bot.handlers import start, button_handler

# =============================================================================
# PROTECCIÓN CONTRA MÚLTIPLES INSTANCIAS (PID LOCK)
# =============================================================================
PID_FILE = os.path.join(tempfile.gettempdir(), "krakeneye_bot.pid")

def check_single_instance():
    if os.path.exists(PID_FILE):
        with open(PID_FILE, 'r') as f:
            pid = f.read().strip()
        try:
            os.kill(int(pid), 0)
            print(f"⚠️ El bot ya está corriendo con PID {pid}. Esta instancia se cierra.")
            sys.exit(0)
        except OSError:
            os.remove(PID_FILE)
            
    with open(PID_FILE, 'w') as f:
        f.write(str(os.getpid()))

def remove_pid_file():
    if os.path.exists(PID_FILE):
        try:
            os.remove(PID_FILE)
        except:
            pass

atexit.register(remove_pid_file)
check_single_instance()
# =============================================================================

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO,
    handlers=[
        logging.FileHandler(Config.LOG_FILE),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

async def error_handler(update, context):
    logger.error(f"Exception while handling an update: {context.error}")

def main():
    logger.info("🚀 Iniciando KrakenEye Bot...")
    
    if not Config.TELEGRAM_TOKEN:
        logger.error("❌ TELEGRAM_TOKEN no configurado. El bot no puede iniciar.")
        return
    
    application = Application.builder().token(Config.TELEGRAM_TOKEN).build()

    application.add_handler(CommandHandler("start", start))
    application.add_handler(CallbackQueryHandler(button_handler))
    application.add_error_handler(error_handler)

    logger.info(" Iniciando en modo POLLING...")
    try:
        application.run_polling(drop_pending_updates=True, allowed_updates=["message", "callback_query"])
    except Exception as e:
        logger.error(f"❌ Error crítico al iniciar el bot: {e}")

if __name__ == '__main__':
    main()