"""
FastAPI 应用入口 — 挂载中间件、路由
"""

from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware

from fastapi.staticfiles import StaticFiles
from pathlib import Path

from app.api.auth import router as auth_router
from app.api.episodes import router as episodes_router
from app.api.imports import router as imports_router
from app.api.users import router as users_router
from app.api.yearly_targets import router as yearly_targets_router
from app.api.dashboard import router as dashboard_router
from app.api.schedules import router as schedules_router
from app.api.knowledge import router as knowledge_router
from app.core.config import settings

app = FastAPI(title="军事科技工作台", version="0.1.0")

# ---- CORS 中间件 ----
# 显式列 origins 不能用 ['*']，否则 credentials=True 时浏览器拒绝携带 cookie
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# ---- Session 中间件 ----
# 密钥来自 .env，用于签名 session cookie
app.add_middleware(
    SessionMiddleware,
    secret_key=settings.SECRET_KEY,
    session_cookie="milsci_session",
    max_age=settings.SESSION_MAX_AGE,
    same_site="lax",
    https_only=False,  # 本地开发用 HTTP
)

# ---- 注册路由 ----
app.include_router(auth_router)
app.include_router(episodes_router)
app.include_router(imports_router)
app.include_router(yearly_targets_router)
app.include_router(users_router)
app.include_router(dashboard_router)
app.include_router(schedules_router)
app.include_router(knowledge_router)

# 挂载静态文件目录（题图海报）
_static_dir = Path(__file__).parent.parent / "static"
if _static_dir.exists():
    app.mount("/static", StaticFiles(directory=str(_static_dir)), name="static")
