from typing import Any, Dict, List, Optional

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware


def create_app(config: Optional[Dict[str, Any]] = None) -> FastAPI:
    """
    Erzeugt und konfiguriert die FastAPI-Anwendung.

    Args:
        config: Konfigurations-Dictionary (z. B. aus app/config/config.yaml geladen).

    Returns:
        FastAPI: Konfigurierte FastAPI-App.
    """
    cfg: Dict[str, Any] = config or {}
    meta: Dict[str, Any] = cfg.get("meta", {})
    app_cfg: Dict[str, Any] = cfg.get("app", {})
    cors_cfg: Dict[str, Any] = cfg.get("cors", {})

    app = FastAPI(
        title=app_cfg.get("name", "entworfener_code_service"),
        version=str(meta.get("version", "0.1.0")),
        docs_url="/docs",
        redoc_url="/redoc",
    )

    # CORS
    allow_origins: List[str] = cors_cfg.get("allow_origins", ["*"])
    allow_credentials: bool = bool(cors_cfg.get("allow_credentials", True))
    allow_methods: List[str] = cors_cfg.get("allow_methods", ["*"])
    allow_headers: List[str] = cors_cfg.get("allow_headers", ["*"])

    app.add_middleware(
        CORSMiddleware,
        allow_origins=allow_origins,
        allow_credentials=allow_credentials,
        allow_methods=allow_methods,
        allow_headers=allow_headers,
    )

    # Router registrieren (unter app/code/api)
    try:
        from api.router import api_router

        app.include_router(api_router, prefix="/api")
    except Exception:
        # Router existiert evtl. noch nicht beim ersten Scaffold
        pass

    try:
        import agent_api

        app.include_router(agent_api.agent_router, prefix="/api")
    except Exception:
        # Agenten-API ist optional und wird bei fehlender Implementierung ignoriert
        pass

    @app.get("/health", tags=["health"])
    async def health() -> Dict[str, str]:
        """
        Einfache Health-Check-Route.
        """
        return {"status": "ok"}

    return app