""" 模型Scope Parameter Adapter

Transforms standard parameters into ModelScope 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 ModelScopeVideoAdapter(ParameterAdapter):
    """ 适配器 for ModelScope video generation API."""
    provider_name = "modelscope"
    
    def adapt_generate_params(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """ 转换 standard params to ModelScope format."""
        result = {
            "input": {}
        }
        
        if params.get("prompt"):
            result["input"]["prompt"] = params["prompt"]
        
        # Image input
        image_inputs = params.get("image_inputs") or []
        
        if image_inputs:
            result["input"]["image_url"] = image_inputs[0]
        
        # 参数s
        if params.get("duration"):
            result["parameters"] = result.get("parameters", {})
            result["parameters"]["duration"] = params["duration"]
        
        if params.get("seed") is not None:
            result["parameters"] = result.get("parameters", {})
            result["parameters"]["seed"] = params["seed"]
        
        return result
    
    def adapt_response(self, raw_response: Dict[str, Any]) -> ServiceResponse:
        """ 转换 ModelScope response to standard format."""
        task_id = raw_response.get("task_id")
        status_str = raw_response.get("task_status", "PENDING")
        
        # 模型Scope uses "SUCCEED" (not SUCCEEDED)
        status_map = {
            "PENDING": TaskStatus.PENDING,
            "RUNNING": TaskStatus.PROCESSING,
            "SUCCEED": TaskStatus.SUCCEEDED,
            "FAILED": TaskStatus.FAILED,
        }
        status = status_map.get(status_str, TaskStatus.UNKNOWN)
        
        results = []
        if status == TaskStatus.SUCCEEDED:
            output = raw_response.get("output", {})
            video_url = output.get("video_url")
            if video_url:
                results.append(GenerationResult(url=video_url))
        
        error = raw_response.get("message") if status == TaskStatus.FAILED else None
        
        return ServiceResponse(
            status=status,
            task_id=task_id,
            results=results if results else None,
            error=error
        )


class ModelScopeImageAdapter(ParameterAdapter):
    """ 适配器 for ModelScope image generation API."""
    provider_name = "modelscope"
    
    def adapt_generate_params(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """ 转换 standard params to ModelScope image format."""
        result = {
            "input": {}
        }
        
        if params.get("prompt"):
            result["input"]["prompt"] = params["prompt"]
        
        if params.get("negative_prompt"):
            result["input"]["negative_prompt"] = params["negative_prompt"]
        
        # Reference image
        ref_images = params.get("image_inputs")
        if ref_images:
            result["input"]["image_url"] = ref_images[0]
        
        # 参数s
        if params.get("size"):
            result["parameters"] = result.get("parameters", {})
            # 解析 size string like "1024*1024"
            size = params["size"]
            if "*" in size:
                w, h = size.split("*")
                result["parameters"]["width"] = int(w)
                result["parameters"]["height"] = int(h)
        
        if params.get("seed") is not None:
            result["parameters"] = result.get("parameters", {})
            result["parameters"]["seed"] = params["seed"]
        
        if params.get("steps"):
            result["parameters"] = result.get("parameters", {})
            result["parameters"]["steps"] = params["steps"]
        
        return result
    
    def adapt_response(self, raw_response: Dict[str, Any]) -> ServiceResponse:
        """ 转换 ModelScope image response to standard format."""
        task_id = raw_response.get("task_id")
        status_str = raw_response.get("task_status", "PENDING")
        
        status_map = {
            "PENDING": TaskStatus.PENDING,
            "RUNNING": TaskStatus.PROCESSING,
            "SUCCEED": TaskStatus.SUCCEEDED,
            "FAILED": TaskStatus.FAILED,
        }
        status = status_map.get(status_str, TaskStatus.UNKNOWN)
        
        results = []
        if status == TaskStatus.SUCCEEDED:
            output = raw_response.get("output", {})
            # 模型Scope may return image_url or results array
            image_url = output.get("image_url")
            if image_url:
                results.append(GenerationResult(url=image_url))
            else:
                for item in output.get("results", []):
                    if item.get("url"):
                        results.append(GenerationResult(url=item["url"]))
        
        error = raw_response.get("message") if status == TaskStatus.FAILED else None
        
        return ServiceResponse(
            status=status,
            task_id=task_id,
            results=results if results else None,
            error=error
        )
