"""FastAPI application entry point (spec §50 API, §51 Security)."""
from __future__ import annotations

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded

from app.api.v1 import auth, companies, health, rankings, screeners, search, watchlist
from app.api.v1.deps import limiter
from app.core.config import get_settings
from app.core.logging import configure_logging

settings = get_settings()
configure_logging(json_logs=settings.ENVIRONMENT != "development")

# AUDIT FIX (StockLab overhaul, security audit): settings.DEBUG existed in config.py before this
# pass but was never read anywhere -- FastAPI's own `debug` param (which controls whether an
# unhandled exception returns a full traceback in the response body) defaulted to False
# regardless of the env var, so DEBUG=true in .env silently did nothing. Wiring it here makes the
# setting meaningful for local debugging; Settings._validate_production_safety() (config.py)
# refuses to start at all if ENVIRONMENT=production and DEBUG=true, so this can never leak
# tracebacks in production even if an operator misconfigures it.
app = FastAPI(
    title="StockLab API",
    description=(
        "StockLab — global equity intelligence platform API. See /docs for the interactive "
        "OpenAPI reference. docs/API.md has the narrative version."
    ),
    version="0.1.0",
    docs_url="/docs",
    redoc_url="/redoc",
    debug=settings.DEBUG,
)

app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_origins_list,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(health.router)
app.include_router(auth.router)
app.include_router(companies.router)
app.include_router(screeners.router)
app.include_router(rankings.router)
app.include_router(watchlist.router)
app.include_router(search.router)


@app.get("/")
def root():
    return {"name": "StockLab API", "docs": "/docs"}
