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

"""
Content Generation Router
内容生成路由 - API v2
"""

import logging
from typing import Dict, Any
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import JSONResponse

from ..models import (
    TopicGenerationRequest,
    ContentGenerationRequest,
    ContentJudgingRequest,
    TopicGenerationResponse,
    ContentGenerationResponse,
    ContentJudgingResponse,
    ApiResponse
)

logger = logging.getLogger(__name__)

router = APIRouter()


@router.post("/topics", response_model=TopicGenerationResponse, summary="生成主题")
async def generate_topics(
    request: TopicGenerationRequest,
    pipeline: Dict[str, Any] = Depends(__import__('api_v2.main', fromlist=['get_content_pipeline']).get_content_pipeline)
):
    """
    生成旅游内容主题
    
    - **creative_materials**: 创意素材描述
    - **num_topics**: 要生成的主题数量 (1-20)
    - **month**: 可选的月份限制
    - **style**: 内容风格
    """
    try:
        logger.info(f"开始生成主题，数量: {request.num_topics}")
        
        # 获取主题生成器
        topic_generator = pipeline["topic_generator"]
        
        # 生成主题
        request_id, topics_data = await topic_generator.generate_topics(
            creative_materials=request.creative_materials,
            num_topics=request.num_topics,
            month=request.month,
            style=request.style
        )
        
        logger.info(f"主题生成完成，请求ID: {request_id}")
        
        return TopicGenerationResponse(
            success=True,
            message=f"成功生成 {len(topics_data.get('topics', []))} 个主题",
            data=topics_data,
            request_id=request_id
        )
        
    except Exception as e:
        error_msg = f"主题生成失败: {str(e)}"
        logger.error(error_msg, exc_info=True)
        
        return JSONResponse(
            status_code=500,
            content=TopicGenerationResponse(
                success=False,
                message="主题生成失败",
                error=error_msg
            ).dict()
        )


@router.post("/generate", response_model=ContentGenerationResponse, summary="生成内容")
async def generate_content(
    request: ContentGenerationRequest,
    pipeline: Dict[str, Any] = Depends(__import__('api_v2.main', fromlist=['get_content_pipeline']).get_content_pipeline)
):
    """
    生成旅游内容文案
    
    - **scenic_info**: 景区信息
    - **product_info**: 产品信息  
    - **additional_requirements**: 额外要求
    - **style**: 内容风格
    - **target_audience**: 目标受众
    """
    try:
        logger.info("开始生成内容")
        
        # 获取内容生成器
        content_generator = pipeline["content_generator"]
        
        # 构建主题信息
        topic_info = {
            "scenic_info": request.scenic_info,
            "product_info": request.product_info,
            "style": request.style,
            "target_audience": request.target_audience
        }
        
        # 生成内容
        request_id, content_data = await content_generator.generate_content(
            topic=topic_info,
            scenic_info=request.scenic_info,
            product_info=request.product_info,
            additional_requirements=request.additional_requirements
        )
        
        logger.info(f"内容生成完成，请求ID: {request_id}")
        
        return ContentGenerationResponse(
            success=True,
            message="内容生成成功",
            data=content_data,
            request_id=request_id
        )
        
    except Exception as e:
        error_msg = f"内容生成失败: {str(e)}"
        logger.error(error_msg, exc_info=True)
        
        return JSONResponse(
            status_code=500,
            content=ContentGenerationResponse(
                success=False,
                message="内容生成失败",
                error=error_msg
            ).dict()
        )


@router.post("/judge", response_model=ContentJudgingResponse, summary="评判内容")
async def judge_content(
    request: ContentJudgingRequest,
    pipeline: Dict[str, Any] = Depends(__import__('api_v2.main', fromlist=['get_content_pipeline']).get_content_pipeline)
):
    """
    评判内容质量和合规性
    
    - **product_info**: 产品信息作为评判标准
    - **content_to_judge**: 待评判的内容
    """
    try:
        logger.info("开始评判内容")
        
        # 获取内容评判器
        content_judger = pipeline["content_judger"]
        
        # 评判内容
        request_id, judge_data = await content_judger.judge_content(
            product_info=request.product_info,
            content_to_judge=request.content_to_judge
        )
        
        logger.info(f"内容评判完成，请求ID: {request_id}")
        
        return ContentJudgingResponse(
            success=True,
            message="内容评判完成",
            data=judge_data,
            request_id=request_id
        )
        
    except Exception as e:
        error_msg = f"内容评判失败: {str(e)}"
        logger.error(error_msg, exc_info=True)
        
        return JSONResponse(
            status_code=500,
            content=ContentJudgingResponse(
                success=False,
                message="内容评判失败",
                error=error_msg
            ).dict()
        )


@router.get("/pipeline/stats", response_model=ApiResponse, summary="获取流水线统计")
async def get_pipeline_stats(
    pipeline: Dict[str, Any] = Depends(__import__('api_v2.main', fromlist=['get_content_pipeline']).get_content_pipeline)
):
    """获取内容生成流水线的统计信息"""
    try:
        stats = {
            "topic_generator": pipeline["topic_generator"].get_generation_stats(),
            "content_generator": pipeline["content_generator"].get_generation_stats(),
            "content_judger": pipeline["content_judger"].get_judging_stats(),
            "ai_service": pipeline["ai_service"].get_model_info(),
            "config": pipeline["config"].content_generation.dict()
        }
        
        return ApiResponse(
            success=True,
            message="统计信息获取成功",
            data=stats
        )
        
    except Exception as e:
        error_msg = f"获取统计信息失败: {str(e)}"
        logger.error(error_msg, exc_info=True)
        
        return JSONResponse(
            status_code=500,
            content=ApiResponse(
                success=False,
                message="获取统计信息失败",
                error=error_msg
            ).dict()
        ) 