from math import log
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware
from config.settings import DEVELOPMENT, SECRET_KEY
from middleware.in_time import InTimeMiddleware
from routes import store
from routes import sales
from routes import debug
from services.email_service import initialize_email_sender
from middleware.no_cache import NoCacheMiddleware
from logging import getLogger

logger = getLogger(__name__)

def create_app() -> FastAPI:
    """Create and configure FastAPI application"""
    logger.info("Creating FastAPI application")
    
    try:
        if DEVELOPMENT:
            logger.info("Creating FastAPI app in development mode")
            app = FastAPI(
                title="Web Pedidos Klein - FastAPI Backend",
                description="Backend for the Web Pedidos Klein application using FastAPI"
            )
        else:
            logger.info("Creating FastAPI app in production mode")
            app = FastAPI(
                title="Web Pedidos Klein - FastAPI Backend",
                description="Backend for the Web Pedidos Klein application using FastAPI",
                version="1.0.0"
            )


        # Initialize email sender
        logger.info("Initializing email sender")
        initialize_email_sender()

        logger.info("Email sender initialized")

        # Add CORS middleware
        logger.info("Adding CORS middleware")
        app.add_middleware(
            CORSMiddleware,
            allow_origins=["https://admin.kleinexpress.store", "https://kleinexpress.store", "http://localhost:8000"],
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )
        
        
        
        # Add SessionMiddleware
        logger.info("Adding session middleware")
        app.add_middleware(
            SessionMiddleware,
            secret_key=SECRET_KEY,
            max_age=60 * 60  # max_age in seconds for Starlette
        )
        
        
        # Add NoCacheMiddleware
        logger.info("Adding no-cache middleware")
        app.add_middleware(NoCacheMiddleware)
        
        # Add InTimeMiddleware
        logger.info("Adding in-time middleware")
        app.add_middleware(InTimeMiddleware)
        # disable docs
        app.docs_url = None
        app.redoc_url = None
        app.openapi_url = None
        
        
        logger.info("FastAPI application created successfully")
        return app
        
    except Exception as e:
        error_msg = f"Error creating FastAPI application: {e}"
        logger.error(error_msg)
        
        raise


def setup_routes(app: FastAPI):
    """Setup all application routes"""
    logger.info("Setting up application routes")
    
    try:
        from routes import chat, users, products, orders, static
        from fastapi import Depends
        from auth.security import get_current_user
        
        # Chat routes
        logger.info("Setting up chat routes")
        app.include_router(
            chat.chat_router, 
            prefix="/api/chat",
            tags=["Chat"]
        )

        # User routes
        logger.info("Setting up user routes")
        app.include_router(users.user_router, prefix="/api/users", tags=["Users"])

        # Product routes
        logger.info("Setting up product routes")
        app.include_router(
            products.product_router, 
            prefix="/api/products", 
            tags=["Products"],
            dependencies=[Depends(get_current_user)]
        )

        # Order routes
        logger.info("Setting up order routes")
        app.include_router(
            orders.order_router, 
            prefix="/api/orders", 
            tags=["Orders"], 
            dependencies=[Depends(get_current_user)]
        )
        
        # Sales routes
        logger.info("Setting up sales routes")
        app.include_router(
            sales.sales_router, 
            prefix="/api/sales", 
            tags=["Sales"], 
            dependencies=[Depends(get_current_user)]
        )
        # Debug routes
        logger.info("Setting up debug routes")
        app.include_router(debug.debug_router, prefix="/api/debug", tags=["Debug"])
        
        #debug router

        logger.info("Seeting store management routes")
        app.include_router(store.store_router, prefix="/api/store", tags=["Store Management"])
        # Verification routes
        logger.info("Setting up verification routes")
        app.include_router(users.verify_router, prefix="/verify", tags=["Verification"])

        app.include_router(users.recovery_pin_router, prefix="/recovery", tags=["Recovery PIN"])

        # Static routes
        logger.info("Setting up static routes")
        from fastapi.responses import HTMLResponse
        app.add_api_route("/", static.serve_app_html, methods=["GET"], 
                         response_class=HTMLResponse, include_in_schema=False)
        app.add_api_route("/register", static.serve_register_html, methods=["GET"],
                         response_class=HTMLResponse, include_in_schema=False)
        app.add_api_route("/images/{image_path:path}", static.serve_image, methods=["GET"],
                         response_class=HTMLResponse, include_in_schema=False)

        # Mount static files
        logger.info("Mounting static file directories")
        static.mount_main_static_files(app)
        static.mount_register_static_files(app)

        
        logger.info("Application routes setup completed successfully")
        
    except Exception as e:
        error_msg = f"Error setting up application routes: - {e}"
        logger.error(error_msg)
    
        raise e
