import os
import sys

# Ensure project root is in python path
project_root = os.path.dirname(os.path.abspath(__file__))
if project_root not in sys.path:
    sys.path.insert(0, project_root)

from modules.config import ConfigManager
from modules.telegram import TelegramManager
from modules.webpanel import app as application
from modules.database import init_db

# Initialize database tables on startup if not already initialized
config = ConfigManager()
if config.get('installed', False):
    try:
        init_db()
        # Automatically launch background Telegram bot daemon
        if config.get('enabled', True):
            tg = TelegramManager()
            if not tg.is_connected():
                tg.start_bot()
    except Exception as e:
        print(f"Startup warning: Could not initialize background bot on load: {e}")

if __name__ == '__main__':
    # Local fallback execution
    application.run(host='0.0.0.0', port=5000, debug=False)
