#!/usr/bin/env python3
"""
测试 imagen 预制件调用
验证 SDK 调用预制件的完整流程和响应解析
"""

import sys
import os

# 添加 SDK 路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))

from gateway_sdk import GatewayClient
import json


def test_imagen_edit_image():
    """测试 imagen 预制件的 edit_image 功能"""

    print("=" * 80)
    print("🧪 测试 imagen 预制件调用")
    print("=" * 80)

    # 初始化客户端（使用 API Key）
    api_key = "sk-fhFyesl_X-tD6kNaNbPsJGRyOGsBMr7My-KSGU0jGfs"
    gateway_url = "http://agent-builder-gateway.sensedeal.vip"

    print(f"\n📝 配置信息:")
    print(f"   Gateway URL: {gateway_url}")
    print(f"   API Key: {api_key[:20]}...")

    print(f"\n🔐 转换 API Key 为内部 Token...")

    try:
        client = GatewayClient.from_api_key(
            api_key=api_key,
            base_url=gateway_url
        )
        print(f"   ✅ Token 转换成功")
    except Exception as e:
        print(f"   ❌ Token 转换失败: {e}")
        return False

    # 准备调用参数
    prefab_id = "imagen"
    version = "0.1.2"
    function_name = "edit_image"

    # 测试图片 S3 URL
    input_image_url = "s3://agent-builder-pro/the-agent-builder/prefab-inputs/f94d31c2-154d-4363-8450-cc907117cbcb/2025/11/26/1764149552573-___.png"

    files = {
        "input_image": [input_image_url]
    }

    parameters = {
        "prompt": "生成海马体证件照"
    }

    print(f"\n📦 调用参数:")
    print(f"   Prefab ID: {prefab_id}")
    print(f"   Version: {version}")
    print(f"   Function: {function_name}")
    print(f"   Files: {json.dumps(files, indent=6, ensure_ascii=False)}")
    print(f"   Parameters: {json.dumps(parameters, indent=6, ensure_ascii=False)}")

    print(f"\n⏳ 调用预制件...")

    try:
        # 调用预制件
        result = client.run(
            prefab_id=prefab_id,
            version=version,
            function_name=function_name,
            parameters=parameters,
            files=files
        )

        print(f"\n📥 SDK 调用结果:")
        print(f"   Call Status: {result.status}")
        print(f"   Job ID: {result.job_id}")

        # 第 1 步：检查 SDK 调用是否成功
        print(f"\n📊 第 1 步：检查 SDK 调用状态")
        print(f"   result.is_success(): {result.is_success()}")

        if not result.is_success():
            print(f"   ❌ SDK 调用失败!")
            print(f"   错误: {result.error}")
            return False

        print(f"   ✅ SDK 调用成功")

        # 第 2 步：获取函数返回值
        print(f"\n📊 第 2 步：获取函数返回值")
        function_result = result.get_function_result()
        print(f"   function_result type: {type(function_result)}")
        print(f"   function_result is None: {function_result is None}")

        if function_result is None:
            print(f"   ❌ 函数返回值为 None!")
            print(f"\n🔍 完整响应数据:")
            print(json.dumps(result.output, indent=2, ensure_ascii=False))
            return False

        print(f"   function_result 内容:")
        print(json.dumps(function_result, indent=6, ensure_ascii=False))

        # 第 3 步：检查业务成功状态
        print(f"\n📊 第 3 步：检查业务成功状态")
        try:
            business_success = result.get_business_success()
            print(f"   result.get_business_success(): {business_success}")
        except AttributeError as e:
            print(f"   ❌ get_business_success() 出错: {e}")
            print(f"   这说明 function_result 为 None!")
            return False

        if business_success:
            print(f"   ✅ 业务执行成功!")

            # 第 4 步：获取业务数据
            print(f"\n📊 第 4 步：获取业务数据")
            message = result.get_business_message()
            print(f"   业务消息: {message}")

            # 第 5 步：获取输出文件
            print(f"\n📊 第 5 步：获取输出文件")
            output_files = result.get_files()
            print(f"   输出文件: {json.dumps(output_files, indent=6, ensure_ascii=False)}")

            if 'output' in output_files:
                s3_url = output_files['output'][0]
                print(f"   ✅ 生成的图片: {s3_url}")

            print(f"\n🎉 测试完全成功!")
            return True

        else:
            print(f"   ❌ 业务执行失败!")
            error = result.get_business_error()
            error_code = result.get_business_error_code()
            print(f"   错误: {error}")
            print(f"   错误码: {error_code}")
            return False

    except Exception as e:
        print(f"\n❌ 调用异常: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_empty_response():
    """测试空响应或 None 的情况"""

    print("\n" + "=" * 80)
    print("🧪 测试 SDK 空值处理")
    print("=" * 80)

    # 模拟一个返回 None 的情况
    from gateway_sdk.models import PrefabResult, CallStatus

    # 场景 1: output 为 None
    print(f"\n📊 场景 1: output 为 None")
    result1 = PrefabResult(
        status=CallStatus.SUCCESS,
        job_id="test-job-1",
        output=None,
        error=None
    )

    print(f"   result.is_success(): {result1.is_success()}")
    function_result1 = result1.get_function_result()
    print(f"   function_result type: {type(function_result1)}")
    print(f"   function_result: {function_result1}")

    try:
        business_success1 = result1.get_business_success()
        print(f"   ✅ get_business_success() 正常: {business_success1}")
    except AttributeError as e:
        print(f"   ❌ get_business_success() 报错: {e}")

    # 场景 2: output['output'] 为 None
    print(f"\n📊 场景 2: output['output'] 为 None")
    result2 = PrefabResult(
        status=CallStatus.SUCCESS,
        job_id="test-job-2",
        output={'output': None, 'files': {}},
        error=None
    )

    function_result2 = result2.get_function_result()
    print(f"   function_result type: {type(function_result2)}")
    print(f"   function_result: {function_result2}")

    try:
        business_success2 = result2.get_business_success()
        print(f"   ✅ get_business_success() 正常: {business_success2}")
    except AttributeError as e:
        print(f"   ❌ get_business_success() 报错: {e}")

    # 场景 3: 正常的响应
    print(f"\n📊 场景 3: 正常响应")
    result3 = PrefabResult(
        status=CallStatus.SUCCESS,
        job_id="test-job-3",
        output={
            'output': {
                'success': True,
                'message': '测试成功'
            },
            'files': {}
        },
        error=None
    )

    function_result3 = result3.get_function_result()
    print(f"   function_result: {function_result3}")

    try:
        business_success3 = result3.get_business_success()
        print(f"   ✅ get_business_success() 正常: {business_success3}")
    except AttributeError as e:
        print(f"   ❌ get_business_success() 报错: {e}")


def main():
    """主函数"""
    print("\n" + "=" * 80)
    print("🚀 Gateway SDK 预制件调用测试")
    print("=" * 80)

    # 测试 1: 实际调用预制件
    success = test_imagen_edit_image()

    # 测试 2: 测试空值处理
    test_empty_response()

    print("\n" + "=" * 80)
    if success:
        print("✅ 所有测试通过!")
    else:
        print("❌ 测试失败，请检查错误信息")
    print("=" * 80)

    return success


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
