"""FastAPI 应用入口。"""
import sys
import time
from pathlib import Path

# 兼容直接运行 `python app/main.py`：把 code 目录加入 sys.path，保证 `app` 包可被导入
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from contextlib import asynccontextmanager

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

from app.api import convert, countries, enterprise, health, records, template
from app.core.config import settings
from app.core.logger import logger
from app.core.response import ok, register_exception_handlers


def create_app() -> FastAPI:
    @asynccontextmanager
    async def lifespan(app: FastAPI):
        logger.info("服务启动: %s v%s", settings.app_name, settings.app_version)
        yield
        logger.info("服务关闭")

    app = FastAPI(
        title=settings.app_name,
        version=settings.app_version,
        description="荷兰 VAT/EPR 申报文档自动化服务：双库（源/目标）+ 企业文档生成（OCR / 模板渲染 / COS）+ API",
        lifespan=lifespan,
    )

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

    @app.middleware("http")
    async def _log_requests(request: Request, call_next):
        """记录每个请求的方法、路径、状态码与耗时。"""
        start = time.perf_counter()
        try:
            response = await call_next(request)
        except Exception:
            logger.exception("请求异常 %s %s", request.method, request.url.path)
            raise
        duration = (time.perf_counter() - start) * 1000
        logger.info("%s %s -> %d (%.1fms)", request.method, request.url.path, response.status_code, duration)
        return response

    @app.middleware("http")
    async def _json_charset(request: Request, call_next):
        """给 JSON 响应补上 charset=utf-8，避免 Windows PowerShell 显示中文乱码。"""
        response = await call_next(request)
        content_type = response.headers.get("content-type", "")
        if content_type.startswith("application/json") and "charset" not in content_type:
            response.headers["content-type"] = "application/json; charset=utf-8"
        return response

    register_exception_handlers(app)

    app.include_router(health.router, prefix="/api")
    app.include_router(template.router, prefix="/api")
    app.include_router(records.router, prefix="/api")
    app.include_router(enterprise.router, prefix="/api")
    app.include_router(countries.router, prefix="/api")
    app.include_router(convert.router, prefix="/api")

    @app.get("/", tags=["首页"], summary="服务信息")
    def root():
        return ok({"app": settings.app_name, "version": settings.app_version, "docs": "/docs"})

    return app


app = create_app()


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8000)