"""
Volcengine Parameter Adapter

Transforms standard parameters into Volcengine (ByteDance) API format.
"""

from typing import Dict, Any, Optional
from src.services.provider.adapters import ParameterAdapter, register_adapter
from src.services.provider.base import ServiceResponse, TaskStatus, GenerationResult


class VolcengineVideoAdapter(ParameterAdapter):
    """ 适配器 for Volcengine (ByteDance) video generation API."""
    provider_name = "volcengine"
    
    def adapt_generate_params(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """ 转换 standard params to Volcengine format.
        
        Volcengine expects content array with text and image_url objects.
        Parameters are appended to prompt as command flags (--rt, --dur, etc.)
        """
        prompt = params.get("prompt", "")
        
        # 构建 command flags for parameters
        cmd_flags = []
        
        if params.get("aspect_ratio"):
            cmd_flags.append(f"--rt {params['aspect_ratio']}")
        
        if params.get("resolution"):
            cmd_flags.append(f"--rs {params['resolution']}")
        
        if params.get("duration"):
            cmd_flags.append(f"--dur {params['duration']}")
        
        if params.get("fps"):
            cmd_flags.append(f"--fps {params['fps']}")
        
        if params.get("seed") is not None:
            cmd_flags.append(f"--seed {params['seed']}")
        
        # Append flags to prompt
        if cmd_flags:
            prompt = f"{prompt} {' '.join(cmd_flags)}"
        
        # 构建 content array
        content = [{"type": "text", "text": prompt}]
        
        # Handle image inputs
        image_inputs = params.get("image_inputs") or []
        
        if image_inputs:
            if len(image_inputs) == 1:
                content.append({
                    "type": "image_url",
                    "image_url": {"url": image_inputs[0]},
                    "role": "first_frame"
                })
            elif len(image_inputs) >= 2:
                content.append({
                    "type": "image_url",
                    "image_url": {"url": image_inputs[0]},
                    "role": "first_frame"
                })
                content.append({
                    "type": "image_url",
                    "image_url": {"url": image_inputs[1]},
                    "role": "last_frame"
                })
        
        result = {"content": content}
        
        # 生成 audio option
        if params.get("enable_audio") is not None:
            result["generate_audio"] = params["enable_audio"]
        
        return result
    
    def adapt_response(self, raw_response: Dict[str, Any]) -> ServiceResponse:
        """ 转换 Volcengine response to standard format."""
        task_id = raw_response.get("id")
        status_str = raw_response.get("status", "unknown")
        
        status_map = {
            "queued": TaskStatus.QUEUED,
            "running": TaskStatus.PROCESSING,
            "succeeded": TaskStatus.SUCCEEDED,
            "failed": TaskStatus.FAILED,
            "cancelled": TaskStatus.CANCELLED,
            "expired": TaskStatus.FAILED,
        }
        status = status_map.get(status_str, TaskStatus.UNKNOWN)
        
        results = []
        if status == TaskStatus.SUCCEEDED:
            content = raw_response.get("content", {})
            video_url = content.get("video_url")
            if video_url:
                results.append(GenerationResult(url=video_url))
        
        error = None
        if status == TaskStatus.FAILED:
            error_obj = raw_response.get("error")
            if error_obj:
                error = f"{error_obj.get('code')}: {error_obj.get('message')}"
        
        return ServiceResponse(
            status=status,
            task_id=task_id,
            results=results if results else None,
            error=error
        )
    
    def get_actual_model(self, base_model: str, params: Dict[str, Any], variants: Optional[Dict[str, str]] = None) -> str:
        """Determine Volcengine model variant based on inputs."""
        if not variants:
            return base_model
        
        # Unified input names
        image_inputs = params.get("image_inputs") or []
        
        has_multiple_images = len(image_inputs) > 1
        has_image = len(image_inputs) > 0
        
        if has_multiple_images and "kf2v" in variants:
            return variants["kf2v"]
        elif has_image and "i2v" in variants:
            return variants["i2v"]
        else:
            return variants.get("t2v", base_model)


class VolcengineImageAdapter(ParameterAdapter):
    """ 适配器 for Volcengine image generation API.""" 
    provider_name = "volcengine"
    
    def adapt_generate_params(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """ 转换 standard params to Volcengine image format."""
        result = {
            "prompt": params.get("prompt", ""),
        }
        
        # 大小 - Volcengine requires minimum 3686400 pixels
        if params.get("size"):
            result["size"] = params["size"]
        
        # Reference image for I2I
        ref_images = params.get("image_inputs")
        if ref_images:
            result["image"] = ref_images[0]
        
        # 数字 of images
        if params.get("n"):
            result["n"] = params["n"]
        
        return result
    
    def adapt_response(self, raw_response: Dict[str, Any]) -> ServiceResponse:
        """ 转换 Volcengine image response to standard format."""
        # Volcengine image API is synchronous
        results = []
        for item in raw_response.get("data", []):
            if item.get("url"):
                results.append(GenerationResult(url=item["url"]))
        
        if results:
            return ServiceResponse(
                status=TaskStatus.SUCCEEDED,
                results=results
            )
        
        return ServiceResponse(
            status=TaskStatus.FAILED,
            error="No results in response"
        )
