
import os
import base64
import logging
from urllib.parse import urlparse
from src.config.settings import STORAGE_TYPE, DATA_DIR, UPLOAD_DIR
from src.services.storage_service import storage_manager

logger = logging.getLogger(__name__)

def resolve_image_param(img: str) -> str:
    """
    Resolve image parameter:
    1. If local path/URL -> Convert to Base64
    2. If OSS URL -> Sign it
    """
    if not img:
        return img
        
    # 2. Check if already a data URI, return as is
    if img.startswith("data:"):
        return img

    final_img = img
    
    # Check if it is a local URL (localhost/127.0.0.1) or relative path
    # Also consider paths that don't start with http/https as local file paths
    is_local_url = "localhost" in img or "127.0.0.1" in img or not img.startswith("http")
    
    # 1. Attempt Local File Conversion
    if is_local_url or (STORAGE_TYPE == "local" and not img.startswith("http")):
        try:
            # 提取 relative path
            if img.startswith("http"):
                parsed = urlparse(img)
                path = parsed.path
            else:
                path = img
                
            # Handle virtual paths (starting with /files/ or /uploads/)
            if path.startswith("/files/") or path.startswith("/uploads/"):
                path = path[1:]
            
            # Robust Path Resolution
            if path.startswith("files/"):
                rel_path = path[6:]
                file_path = os.path.join(DATA_DIR, rel_path)
            elif path.startswith("uploads/"):
                 rel_path = path[8:]
                 file_path = os.path.join(UPLOAD_DIR, rel_path)
            else:
                 if os.path.exists(path):
                     file_path = path
                 else:
                     file_path = os.path.join(UPLOAD_DIR, path)
            
            if os.path.exists(file_path):
                with open(file_path, "rb") as f:
                    img_data = f.read()
                    b64_data = base64.b64encode(img_data).decode("utf-8")
                    # Determine mime type
                    mime_type = "image/png"
                    if file_path.lower().endswith(".jpg") or file_path.lower().endswith(".jpeg"):
                        mime_type = "image/jpeg"
                    elif file_path.lower().endswith(".webp"):
                        mime_type = "image/webp"
                        
                    final_img = f"data:{mime_type};base64,{b64_data}"
                    logger.debug(f"Converted local file {file_path} to Base64")
            else:
                # File not found locally, maybe it's a raw relative path intended for URL construction
                # But here we only warn if we were pretty sure it was a local file
                logger.warning(f"Local file not found for {img} at {file_path}")
        except Exception as e:
            logger.error(f"Failed to process local image {img}: {e}")

    # 2. Attempt OSS URL Signing
    # Only sign if it's an HTTP URL and not a data URI
    if not final_img.startswith("data:") and final_img.startswith("http"):
         try:
             signed = storage_manager.sign_url(final_img)
             if signed and signed != final_img:
                 final_img = signed
         except Exception as e:
             logger.warning(f"Failed to sign OSS URL: {e}")

    return final_img
