from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import logging

from models import OpenAICompatibleProvider
from core import ContentGenerator, TemplateManager
from api.schemas import (
    GenerateRequest, GenerateResponse,
    OptimizeRequest, RewriteRequest,
    BatchGenerateRequest,
    GenerateTitleRequest, TitleResponse,
    GenerateTagsRequest, TagsResponse,
    HealthResponse, ContentTypeListResponse
)
from config import settings

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 创建应用
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.VERSION,
    docs_url="/docs",
    redoc_url="/redoc"
)

# CORS 中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# 初始化组件
llm_provider = OpenAICompatibleProvider(
    api_key=settings.API_KEY,
    base_url=settings.API_BASE_URL,
    model=settings.MODEL
)
generator = ContentGenerator(llm_provider)
template_manager = TemplateManager()


# ===== 异常处理 =====

@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
    logger.error(f"Unhandled exception: {exc}")
    return JSONResponse(
        status_code=500,
        content={"success": False, "message": str(exc)}
    )


# ===== 根路由 =====

@app.get("/", response_model=HealthResponse)
async def root():
    """健康检查"""
    return HealthResponse(
        service=settings.APP_NAME,
        version=settings.VERSION,
        status="running",
        model=settings.MODEL
    )


# ===== 内容类型管理 =====

@app.get("/api/v1/content/types", response_model=ContentTypeListResponse)
async def list_content_types():
    """获取所有内容类型"""
    return ContentTypeListResponse(
        types=template_manager.list_types(),
        descriptions={
            "product_review": "产品测评",
            "lifestyle": "生活方式",
            "knowledge": "知识科普",
            "ootd": "穿搭分享",
            "food": "美食探店",
            "travel": "旅行攻略",
            "coffee_culture": "咖啡文化"
        }
    )


# ===== 内容生成 =====

@app.post("/api/v1/content/generate", response_model=GenerateResponse)
async def generate_content(request: GenerateRequest):
    """生成单篇内容"""
    try:
        result = generator.generate(
            content_type=request.content_type,
            params=request.params,
            style=request.style,
            temperature=request.temperature,
            max_tokens=request.max_tokens
        )
        return GenerateResponse(success=True, data=result)
    except Exception as e:
        logger.error(f"Generation failed: {e}")
        return GenerateResponse(success=False, message=str(e))


@app.post("/api/v1/content/generate/batch", response_model=GenerateResponse)
async def generate_content_batch(request: BatchGenerateRequest):
    """批量生成多个版本"""
    try:
        results = generator.generate_batch(
            content_type=request.content_type,
            params=request.params,
            count=request.count,
            style=request.style
        )
        return GenerateResponse(success=True, data={"versions": results})
    except Exception as e:
        logger.error(f"Batch generation failed: {e}")
        return GenerateResponse(success=False, message=str(e))


# ===== 内容优化 =====

@app.post("/api/v1/content/optimize", response_model=GenerateResponse)
async def optimize_content(request: OptimizeRequest):
    """优化已有内容"""
    try:
        optimized = generator.optimize(request.content, request.instruction)
        return GenerateResponse(success=True, data={"content": optimized})
    except Exception as e:
        logger.error(f"Optimization failed: {e}")
        return GenerateResponse(success=False, message=str(e))


@app.post("/api/v1/content/rewrite", response_model=GenerateResponse)
async def rewrite_content(request: RewriteRequest):
    """改写内容风格"""
    try:
        rewritten = generator.rewrite(request.content, request.target_style)
        return GenerateResponse(success=True, data={"content": rewritten})
    except Exception as e:
        logger.error(f"Rewrite failed: {e}")
        return GenerateResponse(success=False, message=str(e))


# ===== 辅助功能 =====

@app.post("/api/v1/content/titles", response_model=TitleResponse)
async def generate_titles(request: GenerateTitleRequest):
    """生成标题选项"""
    try:
        titles = generator.generate_title(request.content, request.count)
        return TitleResponse(titles=titles)
    except Exception as e:
        logger.error(f"Title generation failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.post("/api/v1/content/tags", response_model=TagsResponse)
async def generate_tags(request: GenerateTagsRequest):
    """生成话题标签"""
    try:
        tags = generator.generate_hashtags(request.content, request.count)
        return TagsResponse(tags=tags)
    except Exception as e:
        logger.error(f"Tag generation failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


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