# 宇之然内容创作平台 - 主应用入口

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import uvicorn

from .database import init_db
from .core.security import SECRET_KEY
from .api import auth, topics, system, generate, publishing, articles, logs, admin

@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时初始化数据库
    print("正在初始化数据库...")
    init_db()
    print("数据库初始化完成")
    
    yield
    
    # 关闭时清理资源
    print("应用关闭")

app = FastAPI(
    title="宇之然内容创作平台 API",
    description="企业级内容创作管理系统",
    version="1.0.0",
    lifespan=lifespan
)

# CORS配置（允许前端访问）
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应指定具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 路由注册
app.include_router(auth.router, prefix="/api/auth", tags=["认证"])
app.include_router(topics.router, prefix="/api/topics", tags=["选题管理"])
app.include_router(system.router, prefix="/api/system", tags=["系统状态"])
app.include_router(generate.router, prefix="/api/system", tags=["批量操作"])
app.include_router(publishing.router, prefix="/api/publishing", tags=["文章发布"])
app.include_router(articles.router, prefix="/api/articles", tags=["文章预览"])
app.include_router(logs.router, prefix="/api/logs", tags=["日志系统"])
app.include_router(admin.router, prefix="/api/admin", tags=["管理员"])

@app.get("/health")
async def health_check():
    """健康检查接口"""
    return {"status": "healthy", "timestamp": __import__('datetime').datetime.now().isoformat()}

@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    """全局异常处理器"""
    import traceback
    print(f"全局异常: {exc}")
    print(f"堆栈跟踪:\n{traceback.format_exc()}")
    return {
        "error": "服务器内部错误",
        "message": str(exc),
        "path": request.url.path
    }

if __name__ == "__main__":
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8001,
        reload=True,  # 开发环境启用热重载
        log_level="info"
    )