import logging
from typing import Optional, Dict, Any
from alibabacloud_videoenhan20200320.client import Client as VideoEnhanClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_videoenhan20200320 import models as video_enhan_models
from alibabacloud_tea_util import models as util_models

from src.config.settings import (
    ALIBABA_CLOUD_ACCESS_KEY_ID, 
    ALIBABA_CLOUD_ACCESS_KEY_SECRET, 
    OSS_REGION
)

logger = logging.getLogger(__name__)

class SuperResolutionService:
    def __init__(self):
        """ 初始化 Alibaba Cloud Video Enhancement Client (used for Image Super Resolution too).
        """
        if not ALIBABA_CLOUD_ACCESS_KEY_ID or not ALIBABA_CLOUD_ACCESS_KEY_SECRET:
            logger.warning("Alibaba Cloud credentials missing. Super Resolution will be disabled.")
            self.client = None
            return

        config = open_api_models.Config(
            access_key_id=ALIBABA_CLOUD_ACCESS_KEY_ID,
            access_key_secret=ALIBABA_CLOUD_ACCESS_KEY_SECRET
        )
        # 端点 for videoenhan is usually videoenhan.<region>.aliyuncs.com
        # Strip 'oss-' prefix if present (e.g. oss-cn-shanghai -> cn-shanghai)
        region = OSS_REGION
        if region and region.startswith('oss-'):
            region = region[4:]
        config.endpoint = f'videoenhan.{region}.aliyuncs.com'
        
        try:
            self.client = VideoEnhanClient(config)
            logger.info("Super Resolution Service (VideoEnhan) initialized.")
        except Exception as e:
            logger.error(f"Failed to initialize Super Resolution Service: {e}")
            self.client = None

    async def upscale_image(self, image_url: str, rate: int = 2, **kwargs) -> Optional[str]:
        """
        Upscale image using Alibaba Cloud Super Resolution (EnhanceImageQuality).
        
        Args:
            image_url: URL of the input image (must be accessible by Alibaba Cloud)
            rate: Upscaling rate (Not all APIs support explicit rate, usually it enhances quality/resolution)
            **kwargs: Extra parameters for the API request
            
        Returns:
            URL of the upscaled image or None if failed.
        """
        if not self.client:
            logger.error("Super Resolution Client not initialized.")
            return None

        # 注意: Alibaba Cloud 'EnhanceImageQuality' or 'SuperResolution'
        # 'GenerateSuperResolutionImage' is typically for increasing resolution.
        
        # Prepare request args
        req_args = {
            "image_url": image_url,
            "scale": rate
        }
        # 更新 with any extra params provided
        req_args.update(kwargs)
        
        request = video_enhan_models.GenerateSuperResolutionImageRequest(**req_args)
        
        runtime = util_models.RuntimeOptions()
        
        try:
            # Using async call if supported or synchronous wrapped
            # The SDK is typically synchronous, so we might need to run it in executor if strictly async
            # For now, we call it directly.
            response = self.client.generate_super_resolution_image_with_options(request, runtime)
            
            if response.body and response.body.data and response.body.data.image_url:
                return response.body.data.image_url
            else:
                logger.error(f"Super Resolution returned no URL. Request ID: {response.body.request_id}")
                return None
                
        except Exception as e:
            logger.error(f"Super Resolution Failed: {e}")
            return None
