import os
import argparse
from modules.config import ConfigManager
from modules.logger import logger
from modules.database import init_db
from modules.telegram import TelegramManager
from modules.webpanel import app

def main():
    parser = argparse.ArgumentParser(description="TG Auto Reply Pro Server Daemon")
    parser.add_argument('--host', type=str, default='0.0.0.0', help='Host to bind the web server to')
    parser.add_argument('--port', type=int, default=5000, help='Port to run the web server on')
    args = parser.parse_args()

    logger.info("Starting TG Auto Reply Pro...")
    
    # Initialize Configuration and Database
    config = ConfigManager()
    
    # Run DB checks/creation
    try:
        if config.get('installed', False):
            init_db()
            
            # Start background Telegram Client
            if config.get('enabled', True):
                tg = TelegramManager()
                tg.start_bot()
        else:
            logger.info("Application is not installed yet. Launching installer on the web panel...")
    except Exception as e:
        logger.error(f"Error during initialization check: {e}")

    logger.info(f"Launching Web Administration Panel on http://{args.host}:{args.port}")
    
    try:
        # Run Flask server
        app.run(host=args.host, port=args.port, debug=False, use_reloader=False)
    except KeyboardInterrupt:
        logger.info("Stopping Telegram client and shutting down...")
        tg = TelegramManager()
        tg.stop_bot()
        logger.info("Application terminated.")

if __name__ == '__main__':
    main()
