#!/usr/bin/env python3
"""真实测试MiniMax API调用"""

import anthropic
import os
import sys

def test_minimax_direct():
    """直接测试MiniMax API"""
    print("🚀 直接测试MiniMax API")
    print("="*60)
    
    # 测试不同的URL和端点
    test_cases = [
        {
            "name": "标准OpenAI格式",
            "url": "https://api.minimax.chat/v1",
            "api_type": "openai",
            "description": "使用OpenAI客户端测试"
        },
        {
            "name": "Anthropic格式 - 基础URL",
            "url": "https://api.minimax.chat",
            "api_type": "anthropic",
            "description": "使用Anthropic客户端，基础URL"
        },
        {
            "name": "Anthropic格式 - 带/v1",
            "url": "https://api.minimax.chat/v1",
            "api_type": "anthropic",
            "description": "使用Anthropic客户端，带/v1"
        },
        {
            "name": "Anthropic格式 - 带/anthropic",
            "url": "https://api.minimax.chat/v1/anthropic",
            "api_type": "anthropic",
            "description": "使用Anthropic客户端，带/anthropic路径"
        },
    ]
    
    api_key = os.getenv("MINIMAX_API_KEY", "test-key")
    
    for test in test_cases:
        print(f"\n🔍 测试: {test['name']}")
        print(f"   URL: {test['url']}")
        print(f"   类型: {test['api_type']}")
        print(f"   描述: {test['description']}")
        
        try:
            if test['api_type'] == 'anthropic':
                # 测试Anthropic客户端
                client = anthropic.Anthropic(
                    api_key=api_key,
                    base_url=test['url'],
                )
                
                print(f"   ✅ Anthropic客户端创建成功")
                print(f"   客户端base_url: {client.base_url}")
                
                # 尝试调用API
                try:
                    # 使用非流式调用，更容易调试
                    response = client.messages.create(
                        model="MiniMax-M2.5",
                        max_tokens=10,
                        messages=[{"role": "user", "content": "测试"}]
                    )
                    print(f"   ✅ API调用成功")
                    print(f"   响应类型: {type(response)}")
                except Exception as e:
                    print(f"   ❌ API调用失败: {type(e).__name__}: {e}")
                    
                    # 如果是认证错误，至少说明URL正确
                    if "401" in str(e) or "authentication" in str(e):
                        print(f"   ℹ️  认证失败但URL正确（API密钥无效）")
                    elif "404" in str(e):
                        print(f"   ❗ 404错误 - 端点不存在")
                    elif "Not Found" in str(e):
                        print(f"   ❗ 未找到端点")
                        
            else:
                # 测试OpenAI客户端
                import openai
                
                client = openai.OpenAI(
                    api_key=api_key,
                    base_url=test['url'],
                )
                
                print(f"   ✅ OpenAI客户端创建成功")
                
                try:
                    response = client.chat.completions.create(
                        model="MiniMax-M2.5",
                        max_tokens=10,
                        messages=[{"role": "user", "content": "测试"}]
                    )
                    print(f"   ✅ API调用成功")
                except Exception as e:
                    print(f"   ❌ API调用失败: {type(e).__name__}: {e}")
                    
        except Exception as e:
            print(f"   ❌ 客户端创建失败: {type(e).__name__}: {e}")

def test_anthropic_sdk_internals():
    """测试Anthropic SDK内部URL构建"""
    print("\n🔧 测试Anthropic SDK内部URL构建")
    print("="*60)
    
    # 创建客户端
    client = anthropic.Anthropic(
        api_key="test-key",
        base_url="https://api.minimax.chat/v1",
    )
    
    print(f"客户端base_url: {client.base_url}")
    
    # 尝试查看内部URL构建
    try:
        # Anthropic SDK使用资源模式
        print(f"\n检查messages资源:")
        print(f"  client.messages类型: {type(client.messages)}")
        
        # 查看messages的客户端引用
        if hasattr(client.messages, '_client'):
            print(f"  messages._client: {client.messages._client}")
            
        # 尝试查看请求构建
        import inspect
        print(f"\n检查可用方法:")
        methods = [m for m in dir(client.messages) if not m.startswith('_')]
        print(f"  {', '.join(methods[:5])}...")
        
    except Exception as e:
        print(f"检查失败: {e}")

def test_with_real_request():
    """使用真实请求测试（需要有效API密钥）"""
    print("\n🔐 使用真实请求测试（需要有效API密钥）")
    print("="*60)
    
    api_key = os.getenv("MINIMAX_API_KEY")
    if not api_key:
        print("⚠️  未设置MINIMAX_API_KEY环境变量，跳过真实请求测试")
        print("💡 设置方式: export MINIMAX_API_KEY=your-key")
        return
    
    print(f"使用API密钥: {api_key[:10]}...")
    
    # 测试最可能的配置
    test_urls = [
        "https://api.minimax.chat/v1",
        "https://api.minimax.chat",
        "https://api.minimax.chat/v1/anthropic",
    ]
    
    for url in test_urls:
        print(f"\n🔗 测试URL: {url}")
        
        try:
            client = anthropic.Anthropic(
                api_key=api_key,
                base_url=url,
            )
            
            print(f"  ✅ 客户端创建成功")
            
            # 尝试调用
            try:
                response = client.messages.create(
                    model="MiniMax-M2.5",
                    max_tokens=10,
                    messages=[{"role": "user", "content": "Hello"}]
                )
                print(f"  🎉 API调用成功!")
                print(f"    响应ID: {response.id}")
                print(f"    模型: {response.model}")
                print(f"    内容: {response.content[0].text if response.content else '无内容'}")
                return True  # 找到正确配置
                
            except Exception as e:
                print(f"  ❌ API调用失败: {type(e).__name__}")
                print(f"     错误: {str(e)[:100]}...")
                
        except Exception as e:
            print(f"  ❌ 客户端创建失败: {type(e).__name__}: {e}")
    
    return False

if __name__ == "__main__":
    print("🚀 MiniMax API真实测试")
    print("="*60)
    
    # 运行测试
    test_minimax_direct()
    test_anthropic_sdk_internals()
    
    # 只有有API密钥时才运行真实请求测试
    if os.getenv("MINIMAX_API_KEY"):
        success = test_with_real_request()
        if success:
            print("\n🎉 找到可用的MiniMax配置!")
        else:
            print("\n⚠️  未找到可用的MiniMax配置")
    else:
        print("\n💡 提示: 设置MINIMAX_API_KEY环境变量进行真实API测试")
    
    print("\n" + "="*60)
    print("基于测试的建议:")
    print("1. 尝试使用OpenAI格式: https://api.minimax.chat/v1")
    print("2. 如果Anthropic格式失败，系统会自动回退到OpenAI格式")
    print("3. 检查MiniMax官方文档获取最新API信息")