#!/usr/bin/env python3
"""测试MiniMax URL修复"""

import asyncio
from unittest.mock import Mock, patch
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent))

async def test_minimax_url_fix():
    """测试MiniMax URL修复"""
    print("🚀 测试MiniMax URL修复")
    print("="*60)
    
    try:
        from core.main_agent import MainAgent
        
        # 模拟依赖
        mock_context = Mock()
        mock_safety = Mock()
        
        # 测试不同的URL配置
        test_cases = [
            {
                "name": "标准MiniMax URL (带/v1)",
                "base_url": "https://api.minimax.chat/v1",
                "expected_adjustment": "应该去掉/v1"
            },
            {
                "name": "MiniMax不带/v1",
                "base_url": "https://api.minimax.chat",
                "expected_adjustment": "应该添加/v1/anthropic"
            },
            {
                "name": "MiniMax带/anthropic",
                "base_url": "https://api.minimax.chat/v1/anthropic",
                "expected_adjustment": "应该保持不变"
            },
            {
                "name": "非MiniMax URL",
                "base_url": "https://api.openai.com/v1",
                "expected_adjustment": "应该保持不变"
            },
        ]
        
        for test_case in test_cases:
            print(f"\n🔍 测试: {test_case['name']}")
            print(f"   原始URL: {test_case['base_url']}")
            print(f"   预期调整: {test_case['expected_adjustment']}")
            
            model_config = {
                "name": "MiniMax-M2.5",
                "gateway": "anthropic",
                "api_key": "test_key",
                "base_url": test_case["base_url"],
                "temperature": 0.1,
                "max_tokens": 100
            }
            
            # 创建Agent
            with patch('anthropic.Anthropic') as mock_anthropic:
                mock_client = Mock()
                mock_anthropic.return_value = mock_client
                mock_messages = Mock()
                mock_client.messages = mock_messages
                
                # 捕获base_url参数
                captured_base_url = None
                
                def capture_base_url(**kwargs):
                    nonlocal captured_base_url
                    captured_base_url = kwargs.get('base_url')
                    return mock_client
                
                mock_anthropic.side_effect = capture_base_url
                
                try:
                    agent = MainAgent(
                        project_path=Path.cwd(),
                        context_manager=mock_context,
                        safety_guard=mock_safety,
                        model_config=model_config,
                    )
                    
                    print(f"   ✅ Agent创建成功")
                    print(f"   实际传递的base_url: {captured_base_url}")
                    
                    # 验证URL调整
                    if "minimax" in test_case["base_url"].lower():
                        if test_case["base_url"].endswith("/v1") and not test_case["base_url"].endswith("/v1/anthropic"):
                            # 应该被调整
                            if captured_base_url != test_case["base_url"]:
                                print(f"   ✅ URL已正确调整")
                            else:
                                print(f"   ⚠️  URL未调整，可能有问题")
                        elif "/anthropic" in test_case["base_url"]:
                            # 应该保持不变
                            if captured_base_url == test_case["base_url"]:
                                print(f"   ✅ URL保持不变（正确）")
                            else:
                                print(f"   ⚠️  URL被修改，可能有问题")
                    else:
                        # 非MiniMax URL应该保持不变
                        if captured_base_url == test_case["base_url"]:
                            print(f"   ✅ 非MiniMax URL保持不变")
                        else:
                            print(f"   ⚠️  非MiniMax URL被修改，可能有问题")
                            
                except Exception as e:
                    print(f"   ❌ Agent创建失败: {type(e).__name__}: {e}")
        
        print("\n" + "="*60)
        print("测试完成！")
        
        # 实际测试API调用
        print("\n🔧 测试实际API调用...")
        
        # 使用最常见的MiniMax配置
        model_config = {
            "name": "MiniMax-M2.5",
            "gateway": "anthropic",
            "api_key": "test_key",
            "base_url": "https://api.minimax.chat/v1",
            "temperature": 0.1,
            "max_tokens": 100
        }
        
        agent = MainAgent(
            project_path=Path.cwd(),
            context_manager=mock_context,
            safety_guard=mock_safety,
            model_config=model_config,
        )
        
        # 模拟Anthropic响应
        with patch('anthropic.Anthropic') as mock_anthropic:
            mock_client = Mock()
            mock_anthropic.return_value = mock_client
            mock_messages = Mock()
            mock_client.messages = mock_messages
            
            # 模拟流式响应
            mock_stream = Mock()
            mock_stream.text_stream = iter(["测试响应"])
            mock_stream.__enter__ = Mock(return_value=mock_stream)
            mock_stream.__exit__ = Mock(return_value=None)
            mock_messages.stream.return_value = mock_stream
            
            # 模拟run_in_executor
            with patch('asyncio.get_event_loop') as mock_loop:
                mock_loop_instance = Mock()
                mock_loop.return_value = mock_loop_instance
                mock_loop_instance.run_in_executor.return_value = asyncio.Future()
                mock_loop_instance.run_in_executor.return_value.set_result("测试响应")
                
                test_messages = [{"role": "user", "content": "测试"}]
                
                try:
                    response = await agent.model_caller(test_messages)
                    print(f"✅ API调用成功: {response}")
                except Exception as e:
                    print(f"❌ API调用失败: {type(e).__name__}: {e}")
        
        return True
        
    except Exception as e:
        print(f"❌ 测试失败: {str(e)}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = asyncio.run(test_minimax_url_fix())
    sys.exit(0 if success else 1)