#!/home/superti/miniconda3/envs/pedidos_express/bin/python

from config.settings import PORT, BG_DATA_PATH,  validate_config, DEVELOPMENT
import os
import uvicorn
from app import create_app, setup_routes
from logging import getLogger

from services.data_service import initialize_db
import redis
logger = getLogger("main")

def main():
    """testing Main application entry point"""
    try:
        # Validate configuration
        if not validate_config():
            logger.critical("FATAL: Configuration validation failed.")
            logger.error("Please create a .env file with OPENAI_API_KEY='your_key_here'")
            with open(".env", "w") as f:
                f.write("OPENAI_API_KEY='your_key_here'")
            return None
        logger.info("Creating FastAPI application")
        app = create_app()
        logger.info("Setting up application routes")
        setup_routes(app)
        # Initialize database
        logger.info("Initializing database")
        redis_client = redis.Redis(host='localhost', port=6379, db=1 if DEVELOPMENT else 0)
        # eliminar la lista de usuarios conectados al iniciar
        redis_client.delete("connected_users")
        redis_client.delete("chat_history")
        initialize_db()
        # Display startup information
        logger.info(f"Server starting on http://localhost:{PORT}")
        if not os.path.exists(BG_DATA_PATH):
            logger.warning(f"WARNING: {BG_DATA_PATH} not found. AI assistant will not have specific menu data.")
        else:
            logger.info(f"AI assistant data loaded from: {os.path.abspath(BG_DATA_PATH)}")


        logger.info("Pedidos Express application ready to serve requests")
        return app
    except Exception as e:
        error_msg = f"Critical error during application startup: - {e}"
        logger.critical(error_msg)
        raise e

app = main()

if not app:
    logger.critical("FATAL: Failed to create FastAPI app.")

    exit(1)

logger.info("Application initialized successfully")

if __name__ == "__main__":
    logger.info(f"Starting server with uvicorn on port {PORT}")
    uvicorn.run(app, host="0.0.0.0", port=PORT, log_level="info", access_log=False)
