import os
from contextlib import asynccontextmanager

# pyrefly: ignore [missing-import]
from dotenv import load_dotenv

# Load .env before app modules read env vars at import time (e.g. DATABASE_PATH).
# Real environment variables take precedence over values in .env.
load_dotenv()

import logging

# pyrefly: ignore [missing-import]
from fastapi import FastAPI, Request

# pyrefly: ignore [missing-import]
from fastapi.exceptions import RequestValidationError

# pyrefly: ignore [missing-import]
from fastapi.middleware.cors import CORSMiddleware

# pyrefly: ignore [missing-import]
from fastapi.responses import JSONResponse

# pyrefly: ignore [missing-import]
from starlette.exceptions import HTTPException as StarletteHTTPException

from app.lvar.router import router as lvar_router
from app.ocr import config as ocr_config
from app.ocr import database as ocr_database
from app.ocr.router import public_router as ocr_public_router
from app.ocr.router import router as ocr_router
from app.security import warn_if_insecure

_DEFAULT_CORS_ORIGINS = "http://localhost:3030,http://127.0.0.1:3030"


@asynccontextmanager
async def lifespan(_app: FastAPI):
    warn_if_insecure()
    ocr_config.init()
    ocr_database.init_db()
    yield


# Interactive docs / schema are hidden in production.
_is_production = os.getenv("ENV", "").strip().lower() == "production"
app = FastAPI(
    lifespan=lifespan,
    docs_url=None if _is_production else "/docs",
    redoc_url=None if _is_production else "/redoc",
    openapi_url=None if _is_production else "/openapi.json",
)

# Browser front-ends (e.g. the OCR UI) - origins come from CORS_ORIGINS (comma separated).
_cors_origins = [
    o.strip() for o in os.getenv("CORS_ORIGINS", _DEFAULT_CORS_ORIGINS).split(",") if o.strip()
]
app.add_middleware(
    CORSMiddleware,
    allow_origins=_cors_origins,
    allow_credentials=False,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["X-API-Key", "X-Username", "Content-Type"],
    expose_headers=["Content-Disposition"],
)

_logger = logging.getLogger("app")


def _format_validation_errors(errors) -> str:
    parts = []
    for err in errors:
        loc = ".".join(str(p) for p in err.get("loc", ()) if p not in ("body", "query", "path"))
        msg = err.get("msg", "Invalid value")
        parts.append(f"{loc}: {msg}" if loc else msg)
    return "; ".join(parts) or "Invalid request"


# Every error response is JSON with a human-readable string ``detail``.
@app.exception_handler(RequestValidationError)
async def _validation_error_handler(_request: Request, exc: RequestValidationError):
    errors = jsonable_errors(exc.errors())
    return JSONResponse(
        status_code=422,
        content={"detail": _format_validation_errors(errors), "errors": errors},
    )


@app.exception_handler(StarletteHTTPException)
async def _http_error_handler(_request: Request, exc: StarletteHTTPException):
    detail = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
    return JSONResponse(
        status_code=exc.status_code, content={"detail": detail}, headers=getattr(exc, "headers", None)
    )


@app.exception_handler(Exception)
async def _unhandled_error_handler(request: Request, exc: Exception):
    _logger.exception("Unhandled error on %s %s", request.method, request.url.path)
    return JSONResponse(status_code=500, content={"detail": "Internal server error"})


def jsonable_errors(errors):
    # ``ctx`` may carry exception objects that are not JSON serialisable.
    return [{k: (str(v) if k == "ctx" else v) for k, v in e.items() if k != "input"} for e in errors]


app.include_router(lvar_router)
app.include_router(ocr_public_router)
app.include_router(ocr_router)


@app.get("/")
def read_root():
    return {"message": "Hello World"}
