#!/usr/bin/env python3
"""测试Anthropic SDK实际请求的URL"""

import anthropic
from unittest.mock import patch
import json

def test_anthropic_request_url():
    """测试Anthropic SDK实际构建的URL"""
    
    print("🔍 测试Anthropic SDK实际请求URL")
    print("="*60)
    
    # 使用httpx的mock来捕获实际请求
    import httpx
    
    captured_request = None
    
    class MockTransport(httpx.AsyncHTTPTransport):
        async def handle_async_request(self, request):
            nonlocal captured_request
            captured_request = request
            print(f"📡 捕获到请求:")
            print(f"   方法: {request.method}")
            print(f"   URL: {request.url}")
            print(f"   头部: {dict(request.headers)}")
            
            # 返回模拟响应
            return httpx.Response(
                status_code=200,
                json={
                    "id": "test",
                    "type": "message",
                    "role": "assistant",
                    "content": [{"type": "text", "text": "测试响应"}],
                    "model": "claude-3-5-sonnet-20241022",
                    "stop_reason": "end_turn",
                    "usage": {"input_tokens": 10, "output_tokens": 5}
                }
            )
    
    # 测试不同的base_url
    test_cases = [
        ("https://api.minimax.chat/v1", "MiniMax标准URL"),
        ("https://api.minimax.chat", "MiniMax基础URL"),
        ("https://api.minimax.chat/v1/anthropic", "MiniMax Anthropic端点"),
        ("https://api.anthropic.com", "官方Anthropic"),
    ]
    
    for base_url, description in test_cases:
        print(f"\n🧪 测试: {description}")
        print(f"   base_url: {base_url}")
        
        captured_request = None
        
        try:
            # 创建客户端
            client = anthropic.Anthropic(
                api_key="test-key",
                base_url=base_url,
                http_client=httpx.AsyncClient(transport=MockTransport())
            )
            
            print(f"   ✅ 客户端创建成功")
            
            # 尝试发送请求（异步）
            import asyncio
            
            async def make_request():
                try:
                    response = await client.messages.create(
                        model="claude-3-5-sonnet-20241022",
                        max_tokens=10,
                        messages=[{"role": "user", "content": "测试"}]
                    )
                    return response
                except Exception as e:
                    print(f"   ❌ 请求失败: {type(e).__name__}: {e}")
                    return None
            
            # 运行异步请求
            response = asyncio.run(make_request())
            
            if captured_request:
                print(f"   📤 实际请求URL: {captured_request.url}")
                
                # 分析URL路径
                url_str = str(captured_request.url)
                if base_url in url_str:
                    print(f"   ✅ base_url包含在请求URL中")
                else:
                    print(f"   ⚠️  base_url不在请求URL中")
                
                # 检查路径
                path = captured_request.url.path
                print(f"   📍 请求路径: {path}")
                
                # 检查是否有重复的/v1
                if "/v1/v1/" in url_str:
                    print(f"   ❌ 检测到重复的/v1路径!")
                elif path.count("/v1") > 1:
                    print(f"   ⚠️  可能有多个/v1路径")
                else:
                    print(f"   ✅ 路径正常")
            
        except Exception as e:
            print(f"   ❌ 客户端创建失败: {type(e).__name__}: {e}")

def test_minimax_actual_endpoint():
    """测试MiniMax实际的Anthropic兼容端点"""
    print("\n🔧 测试MiniMax实际端点")
    print("="*60)
    
    # 根据MiniMax文档，可能的端点
    endpoints = [
        "https://api.minimax.chat/v1",
        "https://api.minimax.chat/v1/anthropic",
        "https://api.minimaxi.com/v1",
        "https://api.minimaxi.com/v1/anthropic",
    ]
    
    for endpoint in endpoints:
        print(f"\n🔗 测试端点: {endpoint}")
        
        try:
            client = anthropic.Anthropic(
                api_key="test-key",
                base_url=endpoint,
            )
            
            print(f"   ✅ 客户端创建成功")
            
            # 检查客户端配置
            print(f"   客户端base_url: {client.base_url}")
            
            # 尝试查看内部URL构建
            if hasattr(client, '_client'):
                print(f"   内部客户端: {type(client._client)}")
                
        except Exception as e:
            print(f"   ❌ 失败: {type(e).__name__}: {e}")

if __name__ == "__main__":
    print("🚀 测试Anthropic SDK实际请求URL")
    print("="*60)
    
    # 由于需要异步，简化测试
    print("\n📝 基于错误日志的分析:")
    print("-"*40)
    print("从错误日志看:")
    print("  请求URL: https://api.minimax.chat/v1/v1/messages")
    print("  问题: 重复的/v1路径")
    print("\n💡 原因分析:")
    print("  1. base_url配置为: https://api.minimax.chat/v1")
    print("  2. Anthropic SDK可能自动添加: /v1/messages")
    print("  3. 结果: https://api.minimax.chat/v1/v1/messages")
    print("\n🔧 解决方案:")
    print("  1. 使用 base_url = 'https://api.minimax.chat'")
    print("  2. 或使用 base_url = 'https://api.minimax.chat/v1/anthropic'")
    print("  3. 或在代码中自动调整URL")
    
    # 测试我们的修复
    print("\n✅ 我们的修复:")
    print("  在 _call_anthropic_api 方法中:")
    print("  - 检测到MiniMax URL时自动调整")
    print("  - https://api.minimax.chat/v1 -> https://api.minimax.chat")
    print("  - 避免重复的/v1路径")