import json
import base64
import requests
import uuid
from typing import Dict, List, Any, Optional

from jingrow.utils.auth import get_jingrow_cloud_api_headers, get_jingrow_cloud_api_url

# 定义配置变量
images_per_prompt = 4  # 默认值，可以从Config中获取
add_title_to_image_name = 0  # 默认值，可以从Config中获取

def call_jingrow_jart_api(prompts: List[str], config: Dict = None, callback = None) -> Dict:
    try:
        # 获取API URL
        api_url = f"{get_jingrow_cloud_api_url()}/jart/batch"
        
        headers = get_jingrow_cloud_api_headers()
        
        default_config = {"images_per_prompt": images_per_prompt}
        if config:
            default_config.update(config)
        
        request_data = {
            "prompts": prompts,
            "config": default_config
        }
        
        images_data = []
        total_processed = 0
        total_success = 0
        
        response = requests.post(
            api_url, 
            json=request_data, 
            headers=headers, 
            stream=True
        )
        
        if response.status_code != 200:
            try:
                error_data = response.json()
                error_message = error_data.get("message") or error_data.get("error") or f"API请求失败 (HTTP {response.status_code})"
            except:
                error_message = f"API请求失败 (HTTP {response.status_code})"
            
            if response.status_code in [401, 403]:
                auth_error_message = "API认证失败，请检查认证信息"
                return {"success": False, "message": auth_error_message}
            
            return {"success": False, "message": error_message}
        
        for line in response.iter_lines():
            if line:
                try:
                    result = json.loads(line)
                    total_processed += 1
                    
                    if result.get('status') == 'success' and 'image_content' in result:
                        image_base64 = result['image_content'].split(',')[1]
                        img_data = base64.b64decode(image_base64)
                        
                        if callback:
                            callback({
                                "success": True,
                                "image_data": img_data
                            })
                        else:
                            images_data.append({
                                "image_data": img_data
                            })
                        total_success += 1
                    else:
                        error_message = result.get('message', '未知错误')
                        if "余额不足" in error_message:
                            return {"success": False, "message": error_message}
                        elif callback:
                            callback({
                                "success": False,
                                "message": error_message
                            })
                except Exception:
                    continue
        
        if callback:
            return {
                "success": True,
                "total_processed": total_processed,
                "total_success": total_success
            }
            
        if not images_data and not callback:
            return {"success": False, "message": "未能获取到任何图像数据"}
        
        return {"success": True, "data": images_data}
        
    except Exception as e:
        return {"success": False, "message": f"调用批量图像生成API异常：{str(e)}"}