"""
Video Generation Endpoints - 视频生成模块

包含视频生成相关的端点:
- POST /generations/video - 视频生成
"""
import logging

from fastapi import APIRouter, Depends

from src.models.schemas import ResponseModel, VideoGenerationRequest
from src.services.provider.registry import ModelType
from src.services.task_manager import task_manager
from src.auth.dependencies import get_current_user, UserAuth

from .helpers import resolve_service, ensure_url, check_user_api_key
from src.utils.errors import ErrorCode, AppException

router = APIRouter()
logger = logging.getLogger(__name__)


@router.post("/generations/video", response_model=ResponseModel)
async def generate_video(
    request: VideoGenerationRequest,
    current_user: UserAuth = Depends(get_current_user)
):
    """ 泛型 Video Generation Endpoint.
    """
    # 0. Sanitize URLs Early (Convert Base64 -> URL)
    try:
        if request.image_inputs:
            request.image_inputs = [ensure_url(url) for url in request.image_inputs if url]
        if request.video_inputs:
            request.video_inputs = [ensure_url(url) for url in request.video_inputs if url]
        if request.audio_inputs:
            request.audio_inputs = [ensure_url(url) for url in request.audio_inputs if url]
        
        # Also check extra_params for common image keys
        if request.extra_params:
            for key in ["image_url", "video_url", "input_image", "input_video", "audio_url"]:
                 if key in request.extra_params and isinstance(request.extra_params[key], str):
                     request.extra_params[key] = ensure_url(request.extra_params[key])
    except Exception as e:
        logger.error(f"Failed to sanitize inputs: {e}")

    # 1. Resolve Model - 使用统一的路由逻辑
    video_service = resolve_service(request.model, ModelType.VIDEO)

    if not video_service:
        raise AppException(
                message="Video service not configured",
                code=ErrorCode.INTERNAL_ERROR,
                status_code=500
            )

    # 1.5 检查用户是否配置了 API Key
    # 从 video_service 获取 provider_id
    provider = getattr(video_service, 'provider_id', None)
    if provider:
        check_user_api_key(current_user.id, provider)
    
    # 2. Resolve size from aspect_ratio (BEFORE creating task)
    aspect_ratio = request.aspect_ratio
    size = None
    
    if aspect_ratio:
        # Look up resolution in model config
        model_config = getattr(video_service, "config", {}) or {}
        if isinstance(model_config, dict):
            resolutions_config = model_config.get("resolutions") or {}
        else:
            resolutions_config = {}
        
        # Use provided resolution level (e.g. "720P", "1080P") or default to "720P"
        res_level = request.resolution or "720P"
        
        if resolutions_config and res_level in resolutions_config and isinstance(resolutions_config[res_level], dict):
            ratio_map = resolutions_config[res_level]
            if aspect_ratio in ratio_map:
                size = ratio_map[aspect_ratio]

        if not size:
            defaults = {
                "16:9": "1280*720",
                "9:16": "720*1280",
                "1:1": "1280*1280",
                "4:3": "1280*960",
                "3:4": "960*1280"
            }
            size = defaults.get(aspect_ratio)
    
    # 3. Create Task in DB with resolved params
    try:
        model_name = request.model or getattr(video_service, "model_id", "default_video")
        
        # 构建 params dict with resolved size
        task_params = request.model_dump()
        if size:
             task_params["size"] = size  # Override with resolved size
        
        # Use unified task manager
        # Get user_id from authenticated user
        user_id = current_user.id

        # Handle project_id from multiple sources
        # Priority 1: request.project_id (from request body, alias="projectId")
        # Priority 2: request.source_id if source=='project' (from extra_params, alias="sourceId")
        project_id = request.project_id
        if not project_id and request.source == 'project':
            project_id = request.source_id

        task = await task_manager.create_task(
            task_type="video",
            model=model_name,
            params=task_params,
            user_id=user_id,
            project_id=project_id
        )
    except Exception as e:
        logger.error(f"Failed to create task: {e}")
        raise AppException(
            message=f"Failed to create task: {e}",
            code=ErrorCode.INTERNAL_ERROR,
            status_code=500
        )
    
    # 日志 context if provided
    if request.source and request.source_id:
        logger.info(f"Video generation started for {request.source}:{request.source_id}, task_id: {task.id}")
    
    # Unified task manager handles execution automatically
    return ResponseModel(data={
        "task_id": task.id, 
        "status": task.status
    })
