#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
TravelContentCreator API服务
主入口文件
"""

import logging
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager

from api import dependencies

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S"
)
logger = logging.getLogger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用生命周期管理
    在应用启动时初始化全局依赖，在应用关闭时清理资源
    """
    # 初始化配置
    logger.info("正在初始化API服务...")
    dependencies.initialize_dependencies()
    logger.info("API服务初始化完成")
    yield
    
    # 清理资源
    logger.info("正在关闭API服务...")
    # 这里可以添加需要清理的资源
    logger.info("API服务已关闭")

# 创建FastAPI应用
app = FastAPI(
    title="TravelContentCreator API",
    description="旅游内容自动创作API服务",
    version="1.0.0",
    lifespan=lifespan
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该限制来源
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 导入路由
from api.routers import tweet, poster, prompt, document, data

# 包含路由
app.include_router(tweet.router, prefix="/api/v1/tweet", tags=["tweet"])
app.include_router(poster.router, prefix="/api/v1/poster", tags=["poster"])
app.include_router(prompt.router, prefix="/api/v1/prompt", tags=["prompt"])
app.include_router(document.router, prefix="/api/v1/document", tags=["document"])
app.include_router(data.router, prefix="/api/v1", tags=["data"])

@app.get("/")
async def root():
    """API根路径，返回简单的欢迎信息"""
    return {"message": "欢迎使用TravelContentCreator API服务"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("api.main:app", host="0.0.0.0", port=8000, reload=True) 