"""
AIGC视频生成模块 - 视频生成相关业务逻辑
"""
from typing import Dict, Any, Optional
import httpx
from loguru import logger
import asyncio
import os

class AigcVideoClient:
    """AIGC视频生成API客户端"""
    
    def __init__(self, base_url: Optional[str] = None):
        # 优先级: 参数 > 环境变量 > 默认值
        self.base_url = (
            base_url or 
            os.environ.get("AIGC_SERVICE_URL") or 
            "https://openapi.growone.sg/aigc"
        )
        self.timeout = float(os.environ.get("AIGC_TIMEOUT", "600.0"))  # 视频生成可能需要较长时间
        
        logger.info(f"AIGC服务地址: {self.base_url}")
        
    async def generate_video(
        self,
        product_image_url: str,
        video_title: str,
        video_content: str,
        narration_script: str
    ) -> Dict[str, Any]:
        """
        生成视频
        
        Args:
            product_image_url: 产品图片URL
            video_title: 视频标题
            video_content: 视频内容
            narration_script: 旁白脚本
            
        Returns:
            包含task_id的响应数据
        """
        url = f"{self.base_url}/generate-video"
        
        payload = {
            "productImageUrl": product_image_url,
            "videoPrompts": {
                "title": video_title,
                "content": video_content
            },
            "narrationScript": narration_script
        }
        
        try:
            logger.info(f"发送视频生成请求: {url}")
            logger.debug(f"请求参数: {payload}")
            
            async with httpx.AsyncClient() as client:
                response = await client.post(
                    url,
                    json=payload,
                    timeout=self.timeout
                )
                
                response.raise_for_status()
                response_data = response.json()
                
                logger.info(f"视频生成请求成功, task_id: {response_data.get('analysisResult', {}).get('task_id')}")
                
                return {
                    "success": True,
                    "task_id": response_data.get("analysisResult", {}).get("task_id"),
                    "message": "视频生成任务已提交"
                }
                
        except httpx.HTTPStatusError as e:
            logger.error(f"视频生成请求失败: HTTP {e.response.status_code}")
            return {
                "success": False,
                "error": f"HTTP错误: {e.response.status_code}",
                "message": str(e)
            }
        except httpx.RequestError as e:
            logger.error(f"视频生成请求错误: {str(e)}")
            return {
                "success": False,
                "error": "网络请求错误",
                "message": str(e)
            }
        except Exception as e:
            logger.error(f"视频生成异常: {str(e)}")
            return {
                "success": False,
                "error": "处理请求异常",
                "message": str(e)
            }
    
    async def get_video_task_status(self, task_id: str) -> Dict[str, Any]:
        """
        查询视频生成任务状态
        
        Args:
            task_id: 任务ID
            
        Returns:
            任务状态信息
        """
        url = f"{self.base_url}/video-task/{task_id}"
        
        try:
            logger.info(f"查询视频任务状态: {task_id}")
            
            async with httpx.AsyncClient() as client:
                response = await client.get(
                    url,
                    timeout=30.0
                )
                
                response.raise_for_status()
                response_data = response.json()
                
                status = response_data.get("status", "unknown")
                logger.info(f"任务 {task_id} 状态: {status}")
                
                # 格式化返回数据
                result = {
                    "success": True,
                    "task_id": response_data.get("task_id"),
                    "status": status,
                    "created_at": response_data.get("created_at"),
                    "updated_at": response_data.get("updated_at"),
                }
                
                # 如果有结果数据
                if "result" in response_data and response_data["result"]:
                    result["result"] = response_data["result"]
                    if response_data["result"].get("video_url"):
                        result["video_url"] = response_data["result"]["video_url"]
                        result["video_status"] = response_data["result"].get("status")
                        result["video_status_message"] = response_data["result"].get("status_message")
                
                # 如果有错误信息
                if response_data.get("error_message"):
                    result["error_message"] = response_data["error_message"]
                
                return result
                
        except httpx.HTTPStatusError as e:
            logger.error(f"查询任务状态失败: HTTP {e.response.status_code}")
            return {
                "success": False,
                "error": f"HTTP错误: {e.response.status_code}",
                "message": str(e)
            }
        except httpx.RequestError as e:
            logger.error(f"查询任务状态请求错误: {str(e)}")
            return {
                "success": False,
                "error": "网络请求错误",
                "message": str(e)
            }
        except Exception as e:
            logger.error(f"查询任务状态异常: {str(e)}")
            return {
                "success": False,
                "error": "处理请求异常",
                "message": str(e)
            }
    
    async def wait_for_video_completion(
        self,
        task_id: str,
        max_wait_seconds: int = 600,
        poll_interval: int = 10
    ) -> Dict[str, Any]:
        """
        等待视频生成完成（轮询）
        
        Args:
            task_id: 任务ID
            max_wait_seconds: 最大等待时间（秒），默认600秒（10分钟）
            poll_interval: 轮询间隔（秒），默认10秒
            
        Returns:
            最终的任务状态
        """
        logger.info(f"开始等待视频生成完成: {task_id}, 最大等待{max_wait_seconds}秒")
        
        start_time = asyncio.get_event_loop().time()
        attempts = 0
        
        while True:
            elapsed = asyncio.get_event_loop().time() - start_time
            
            if elapsed >= max_wait_seconds:
                logger.warning(f"等待超时: {task_id}")
                return {
                    "success": False,
                    "error": "等待超时",
                    "message": f"视频生成超过最大等待时间 {max_wait_seconds} 秒",
                    "task_id": task_id
                }
            
            # 查询状态
            attempts += 1
            result = await self.get_video_task_status(task_id)
            
            if not result.get("success"):
                return result
            
            status = result.get("status", "unknown")
            logger.debug(f"第 {attempts} 次查询, 状态: {status}, 已等待: {int(elapsed)}秒")
            
            # 检查是否完成
            if status == "success" or status == "completed":
                logger.info(f"视频生成成功: {task_id}")
                return result
            elif status == "failed" or status == "error":
                logger.error(f"视频生成失败: {task_id}")
                return result
            elif status in ["pending", "processing", "running"]:
                # 继续等待
                await asyncio.sleep(poll_interval)
            else:
                # 未知状态，继续等待
                logger.warning(f"未知状态: {status}")
                await asyncio.sleep(poll_interval)

# 创建全局客户端实例
video_client = AigcVideoClient()

