"""
API Application Entrypoint and Router Wiring.

This module initializes the core FastAPI application instance, loads
configuration, applies middleware, and wires up all defined API routers.
"""

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

from api.v1.router import router as api_v1_router
from operations.health.router import router as health_router
from core.config import get_settings, Settings # Import Settings type for clarity

def create_app(settings: Settings = get_settings()) -> FastAPI:
    """
    Create and configure the FastAPI application instance.

    Args:
        settings: Configuration object from core.config. Defaults to current settings.

    Returns:
        A configured FastAPI application instance.
    """
    app = FastAPI(
        title=settings.title,
        description=settings.description,
        version=settings.version,
        docs_url="/docs",
        redoc_url=None,
        openapi_url="/openapi.json",
    )

    # Define allowed origins dynamically based on local dev environment needs
    # In a production setting, this list would typically be sourced from environment variables.
    allowed_origins: List[str] = ["http://localhost:3000", "http://127.0.0.1:3000"]
    
    # Configure CORS middleware
    # TODO: Tightly restrict origins in production deployment.
    app.add_middleware(
        CORSMiddleware,
        allow_origins=allowed_origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    # Include API routers
    app.include_router(health_router)
    app.include_router(api_v1_router, prefix="/api/v1")

    return app

# Main entry point for services like Uvicorn (e.g., `uvicorn main:app --reload`)
app = create_app()
