import asyncio
import logging
import sys
from nicegui import ui, app
from ui import layout, dashboard, settings, manual_tools
from database import init_db
from core.bot import TelegramManager
from core.watcher import DirectoryWatcher
from core.state import state

# Inicializa Banco
init_db()

# Instâncias Globais
bot = TelegramManager()
watcher = DirectoryWatcher(bot)

# --- CONFIGURAÇÃO DE LOG REATIVA ---
class NiceGuiLogHandler(logging.Handler):
    def emit(self, record):
        try:
            msg = self.format(record)
            # Enviamos para o estado que o Dashboard lê
            state.log(msg)
        except Exception:
            pass

async def startup():
    # CONFIGURAR LOGS AQUI (Depois que o servidor iniciou)
    root_logger = logging.getLogger()
    
    # Adiciona o handler que manda para o Dashboard
    ui_handler = NiceGuiLogHandler()
    ui_handler.setFormatter(logging.Formatter('%(message)s'))
    root_logger.addHandler(ui_handler)
    
    logging.info("🚀 Dashboard conectado aos logs do sistema.")
    
    # Inicia os serviços
    asyncio.create_task(watcher.start())
    asyncio.create_task(delayed_bot_start())

async def delayed_bot_start():
    logging.info("⏳ Aguardando rede estabilizar (5s)...")
    await asyncio.sleep(5) 
    await bot.start()

async def shutdown():
    await bot.stop()

app.on_startup(startup)
app.on_shutdown(shutdown)

# --- ROTAS (Permanecem iguais) ---
@ui.page('/')
def index_page():
    ui.colors(primary='#5898d4', secondary='#263238')
    ui.page_title('Clei-Flow')
    layout.create_interface()
    dashboard.show()

@ui.page('/settings')
def settings_page():
    ui.colors(primary='#5898d4', secondary='#263238')
    ui.page_title('Configurações')
    layout.create_interface()
    settings.show()

@ui.page('/explorer')
def explorer_page():
    ui.colors(primary='#5898d4', secondary='#263238')
    ui.page_title('Explorador')
    layout.create_interface()
    manual_tools.show()

if __name__ in {"__main__", "__mp_main__"}:
    # reload=False é essencial em Docker para evitar processos duplicados
    ui.run(title='Clei-Flow', port=8080, storage_secret='clei-secret', reload=False)