#!/usr/bin/env python3
"""
SDK 测试脚本 - 调用 video-processing-prefab
"""

import sys
from pathlib import Path

# 添加 src 到路径以便本地测试
sys.path.insert(0, str(Path(__file__).parent / "src"))

from gateway_sdk import GatewayClient
from gateway_sdk.exceptions import GatewayError


def test_parse_file():
    """测试文件解析功能"""
    
    # ============================================
    # 配置部分 - 使用 API Key
    # ============================================
    API_KEY = "sk-RblEJO35N0WBq1KIj0zF7Vm4g6LKzI68xWle2WgxrZE"
    BASE_URL = "http://nodeport.sensedeal.vip:30566" 
    
    # 测试参数
    PREFAB_ID = "file-processing-prefab"
    VERSION = "0.1.5"
    FUNCTION_NAME = "parse_file"
    INPUT_FILE = "s3://cubeflow-dev/prefab-gateway/prefab-inputs/f94d31c2-154d-4363-8450-cc907117cbcb/2025/10/28/1761659981781-_____________GF_2025_1301_.pdf"
    
    # ============================================
    # 初始化客户端
    # ============================================
    print("🔧 初始化 Gateway SDK 客户端...")
    print(f"   Base URL: {BASE_URL}")
    print(f"   Prefab: {PREFAB_ID} v{VERSION}")
    print()
    
    try:
        client = GatewayClient(
            base_url=BASE_URL,
            api_key=API_KEY,
            timeout=120  # 视频处理可能需要较长时间
        )
        print("✅ 客户端初始化成功")
        print()
        
    except Exception as e:
        print(f"❌ 客户端初始化失败: {e}")
        return False
    
    # ============================================
    # 调用预制件
    # ============================================
    print(f"🚀 调用预制件: {FUNCTION_NAME}")
    print(f"   输入文件: {INPUT_FILE}")
    print()
    
    try:
        result = client.run(
            prefab_id=PREFAB_ID,
            version=VERSION,
            function_name=FUNCTION_NAME,
            parameters={},  # parse_file 不需要额外参数
            files={
                "input": [INPUT_FILE]  # PDF 文件输入
            }
        )
        
        # ============================================
        # 处理结果
        # ============================================
        print("📊 调用结果:")
        print(f"   状态: {result.status}")
        print(f"   Job ID: {result.job_id}")
        print()
        
        if result.is_success():
            print("✅ SDK 调用成功！")
            print()
            
            # ========================================
            # 使用新的便捷方法
            # ========================================
            
            # 检查业务是否成功
            if result.get_business_success():
                print("🎉 业务执行成功！")
                print()
                
                # 获取业务消息
                message = result.get_business_message()
                if message:
                    print(f"📝 消息: {message}")
                    print()
                
                # 获取函数返回值（完整的业务数据）
                function_result = result.get_function_result()
                print("📄 函数返回值:")
                for key, value in function_result.items():
                    if key == 'content':
                        # 内容太长，只显示前100个字符
                        print(f"   {key}: {str(value)[:100]}...")
                    else:
                        print(f"   {key}: {value}")
                print()
                
                # 获取输出文件
                output_files = result.get_files()
                if output_files:
                    print("📁 输出文件:")
                    for key, files in output_files.items():
                        print(f"   {key}:")
                        for file_url in files:
                            print(f"      - {file_url}")
                    print()
                
                return True
                
            else:
                # 业务失败
                print("❌ 业务执行失败")
                error = result.get_business_error()
                error_code = result.get_business_error_code()
                if error:
                    print(f"   错误信息: {error}")
                if error_code:
                    print(f"   错误代码: {error_code}")
                print()
                return False
            
        else:
            print("❌ 调用失败")
            print(f"   错误信息: {result.error}")
            print()
            return False
            
    except GatewayError as e:
        print(f"❌ Gateway 错误: {e}")
        print(f"   错误类型: {type(e).__name__}")
        if hasattr(e, 'status_code'):
            print(f"   状态码: {e.status_code}")
        return False
        
    except Exception as e:
        print(f"❌ 未知错误: {e}")
        print(f"   错误类型: {type(e).__name__}")
        import traceback
        traceback.print_exc()
        return False


def test_list_prefabs():
    """测试列出预制件功能"""
    
    API_KEY = "sk-RblEJO35N0WBq1KIj0zF7Vm4g6LKzI68xWle2WgxrZE"
    BASE_URL = "http://nodeport.sensedeal.vip:30566"
    
    print("📋 测试列出预制件...")
    print()
    
    try:
        client = GatewayClient(
            base_url=BASE_URL,
            api_key=API_KEY,
            timeout=30
        )
        
        prefabs = client.list_prefabs()
        print(f"✅ 找到 {len(prefabs)} 个预制件:")
        print()
        
        for prefab in prefabs[:5]:  # 只显示前 5 个
            print(f"   • {prefab.prefab_id} v{prefab.version}")
            if hasattr(prefab, 'description'):
                print(f"     {prefab.description}")
        
        if len(prefabs) > 5:
            print(f"   ... 还有 {len(prefabs) - 5} 个")
        
        print()
        return True
        
    except Exception as e:
        print(f"❌ 失败: {e}")
        return False


def main():
    """主函数"""
    import sys
    
    print("=" * 60)
    print("  Gateway SDK 测试脚本")
    print("=" * 60)
    print()
    
    # 支持命令行参数
    if len(sys.argv) > 1:
        choice = sys.argv[1]
    else:
        print("⚠️  使用 API Key 进行测试")
        print()
        
        print("选择测试项目:")
        print("  1. 测试文件解析 (parse_file)")
        print("  2. 测试列出预制件 (list_prefabs)")
        print("  3. 运行所有测试")
        print()
        print("💡 命令行用法: python test_sdk_video_processing.py [1|2|3]")
        print()
        
        try:
            choice = input("请选择 (1-3, 默认 1): ").strip() or "1"
        except (EOFError, KeyboardInterrupt):
            print("\n使用默认选项: 1")
            choice = "1"
        print()
    
    success = True
    
    if choice == "1":
        success = test_parse_file()
    elif choice == "2":
        success = test_list_prefabs()
    elif choice == "3":
        success = test_parse_file() and test_list_prefabs()
    else:
        print("❌ 无效选择")
        success = False
    
    print()
    print("=" * 60)
    if success:
        print("  ✅ 测试完成")
    else:
        print("  ❌ 测试失败")
    print("=" * 60)


if __name__ == "__main__":
    main()

