from lila.core.app import App
from app.routes.routes import routes
from app.routes.api import routes as api_routes
from lila.core.middleware import Middleware
from app.config import PORT, HOST, DEBUG
from app.middlewares.security import (
    LoggingMiddleware, 
    SecurityHeadersMiddleware,
    SecurityShieldMiddleware,
    RateLimitMiddleware,
    ErrorHandlerMiddleware,
)
from lila.core.logger import delete_old_logs
import itertools
import uvicorn
import asyncio
import os

# English: Combining application and API routes into a single list.
# Español: Combinando las rutas de la aplicación y la API en una única lista.
all_routes = list(itertools.chain(routes, api_routes))

#English : Marker for the api routes in main.py (also used by scaffold generator)
#Español: Marcardor para añadir automaticamente rutas api en main.py (también usado por generador de scaffold)
# api_marker

#English : Marker for the auth routes in main.py
#Español: Marcardor para añadir automaticamente rutas auth en main.py
# auth_marker 

# English: Marker for the admin routes in main.py.
# Español: Marcador para las rutas de administrador en main.py.
# admin_marker

from app.routes.admin import Admin
from app.models.user import User
admin_routes = Admin(models=[User])
all_routes = list(itertools.chain(all_routes, admin_routes))
    
   
cors = None

# English: CORS usage example
# Español : Ejemplo de utilización de CORS
# cors={
#     "origin": ["*"],
#     "allow_credentials" : True,
#     "allow_methods":["*"],
#     "allow_headers": ["*"]
# }
# app = App(debug=True, routes=all_routes,cors=cors)

# English:necessary for cli command modify react cors for development
# Español:necesario para el comando cli modificar cors de react para desarrollo
# react_marker

middlewares = [
    Middleware(LoggingMiddleware),
    Middleware(SecurityHeadersMiddleware),
    Middleware(SecurityShieldMiddleware),
    Middleware(RateLimitMiddleware),
    Middleware(ErrorHandlerMiddleware)
]

# English: Initializing the application with debugging enabled and the combined routes.
# Español: Inicializando la aplicación con la depuración activada y las rutas combinadas.
app = App(debug=DEBUG, routes=all_routes, cors=cors, middleware=middlewares, on_startup=[delete_old_logs])

def main():
    # English: Starting the Uvicorn server with the application instance.
    # Español: Iniciando el servidor Uvicorn con la instancia de la aplicación.
    uvicorn.run("main:app", host=HOST, port=PORT, reload=DEBUG)

if __name__ == "__main__":
    try:
        #os.environ["PYTHON_JIT"] = "1"
        main()
    except KeyboardInterrupt:
        print("Shutting down the application...")
        pass
