import uuid
import time
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError
from core.config import get_settings
from core.exceptions import AppException
from core.tenant_context import set_current_request_id
from core.logging import get_logger
from apps.api.lifespan import lifespan
from apps.api.exception_handlers import (
    app_exception_handler,
    validation_exception_handler,
    generic_exception_handler,
)
from apps.api.routes import api_v1_router, webhooks_router
from modules.i18n.middleware import LocalizationMiddleware
from core.rate_limit import RateLimitMiddleware

logger = get_logger(__name__)


def create_app() -> FastAPI:
    settings = get_settings()

    app = FastAPI(
        title=settings.APP_NAME,
        version="0.1.0",
        description="Commercial-grade Multi-Tenant Telegram Bot SaaS Platform API",
        docs_url="/docs" if settings.APP_DEBUG or settings.APP_ENV != "production" else None,
        redoc_url="/redoc" if settings.APP_DEBUG or settings.APP_ENV != "production" else None,
        lifespan=lifespan,
    )

    # CORS - Spec-compliant with credentials
    allowed_origins = [
        "http://localhost:3000",
        "http://localhost:5173",
        "http://127.0.0.1:3000",
        "http://127.0.0.1:5173",
        "https://dashboard.yourdomain.com",
    ] if not settings.APP_DEBUG else ["*"]

    # When allowing credentials, cannot use wildcard '*' per W3C CORS spec
    if settings.APP_DEBUG:
        app.add_middleware(
            CORSMiddleware,
            allow_origin_regex=r"^https?://(localhost|127\.0\.0\.1)(:\d+)?$",
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )
    else:
        app.add_middleware(
            CORSMiddleware,
            allow_origins=["https://dashboard.yourdomain.com"],
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )

    # Multi-language i18n Middleware
    app.add_middleware(LocalizationMiddleware)

    # In-App Defense-in-Depth Rate Limiting Middleware
    app.add_middleware(RateLimitMiddleware)

    # Request ID and Timing Middleware
    @app.middleware("http")
    async def request_context_middleware(request: Request, call_next):
        request_id = request.headers.get("X-Request-ID") or str(uuid.uuid4())
        set_current_request_id(request_id)

        start_time = time.time()
        response = await call_next(request)
        process_time_ms = round((time.time() - start_time) * 1000, 2)

        response.headers["X-Request-ID"] = request_id
        response.headers["X-Process-Time-Ms"] = str(process_time_ms)
        return response

    # Exception Handlers
    app.add_exception_handler(AppException, app_exception_handler)
    app.add_exception_handler(RequestValidationError, validation_exception_handler)
    app.add_exception_handler(Exception, generic_exception_handler)

    # Routes
    app.include_router(api_v1_router, prefix=settings.API_V1_PREFIX)
    app.include_router(webhooks_router)

    # Mount Frontend SPA if built
    import os
    from fastapi.staticfiles import StaticFiles
    from fastapi.responses import FileResponse
    from fastapi.exceptions import HTTPException

    frontend_dist = os.path.abspath(os.path.join(os.path.dirname(__file__), "../frontend/dist"))
    if os.path.exists(frontend_dist):
        assets_dir = os.path.join(frontend_dist, "assets")
        if os.path.exists(assets_dir):
            app.mount("/assets", StaticFiles(directory=assets_dir), name="assets")

        @app.api_route("/{full_path:path}", methods=["GET", "HEAD"], include_in_schema=False)
        async def serve_spa(full_path: str):
            if full_path.startswith("api/") or full_path.startswith("webhooks/"):
                raise HTTPException(status_code=404, detail="API route not found")
            file_path = os.path.join(frontend_dist, full_path)
            if full_path and os.path.exists(file_path) and os.path.isfile(file_path):
                return FileResponse(file_path)
            return FileResponse(
                os.path.join(frontend_dist, "index.html"),
                headers={
                    "Cache-Control": "no-cache, no-store, must-revalidate",
                    "Pragma": "no-cache",
                    "Expires": "0",
                },
            )

    return app


app = create_app()
