"""
FastAPI 应用主入口
启动命令: uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
"""

from contextlib import asynccontextmanager
from collections.abc import AsyncIterator

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

from app.core.config import settings
from app.core.exceptions import register_exception_handlers
from app.api.auth import router as auth_router
from app.api.customers import router as customers_router
from app.api.products import router as products_router
from app.api.orders import router as orders_router
from app.api.shipping import router as shipping_router
from app.api.finance import router as finance_router
from app.api.sys_settings import router as sys_settings_router
from app.api.chat import router as chat_router
from app.api.dify_tools import router as dify_tools_router
from app.api.sales_logs import router as sales_logs_router
from app.api.import_export import router as import_export_router
from app.api.sales_invoice import router as sales_invoice_router
from app.api.reports import router as reports_router
from app.api.contacts import router as contacts_router
from app.api.dashboard import router as dashboard_router


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    """应用生命周期：启动/关闭时的钩子"""
    # ── startup ──
    print(f"🚀 {settings.APP_NAME} v{settings.APP_VERSION} 启动中...")
    yield
    # ── shutdown ──
    print("👋 服务正在关闭...")


from fastapi.staticfiles import StaticFiles
import os

app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan,
)

# 挂载上传文件目录
os.makedirs("uploads", exist_ok=True)
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")

# ── CORS（仅允许内网生产地址） ──
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://192.168.1.100"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# ── 注册全局异常处理器 ──
register_exception_handlers(app)

# ── 注册路由 ──
app.include_router(auth_router, prefix="/api")
app.include_router(customers_router, prefix="/api")
app.include_router(products_router, prefix="/api")
app.include_router(orders_router, prefix="/api")
app.include_router(shipping_router, prefix="/api")
app.include_router(finance_router, prefix="/api")
app.include_router(sys_settings_router, prefix="/api")
app.include_router(chat_router, prefix="/api")
app.include_router(dify_tools_router, prefix="/api")
app.include_router(sales_logs_router, prefix="/api")
app.include_router(import_export_router, prefix="/api")
app.include_router(sales_invoice_router, prefix="/api")
app.include_router(reports_router, prefix="/api")
app.include_router(contacts_router, prefix="/api")
app.include_router(dashboard_router, prefix="/api")


# ── 健康检查 ──
@app.get("/health", tags=["系统"])
async def health_check() -> dict:
    return {"status": "ok", "version": settings.APP_VERSION}
