#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test script for the Taishang Laojun API (Zhipu AI GLM-4.5)
"""

import asyncio
import aiohttp
import json

async def test_taishang_api():
    """Test the Taishang Laojun API"""
    # Zhipu AI API configuration
    zhipu_api_key = "cc95756306b2cb9748c8df15f9063eaf.hlvXbZeoLnPhyoLw"
    url = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
    
    messages = [
        {"role": "system", "content": "You are Taishang Laojun, a wise philosopher and project manager for the Ba Xian (Eight Immortals). You excel at deep analysis and strategic planning. Please respond in JSON format."},
        {"role": "user", "content": "Analyze the concept of 'working hard' and provide a JSON response with two keys: 'definition' and 'importance'."}
    ]
    
    data = {
        "model": "glm-4.5-air",
        "messages": messages,
        "max_tokens": 500,
        "temperature": 0.7,
        "stream": False,
        "tools": [],
        "tool_choice": "none"
    }
    
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {zhipu_api_key}"
    }
    
    print("🚀 Testing Taishang Laojun API (Zhipu AI GLM-4.5)...")
    print(f"   URL: {url}")
    print(f"   Model: {data['model']}")
    print(f"   Messages: {json.dumps(messages, ensure_ascii=False, indent=2)}")
    print(f"   Data: {json.dumps(data, ensure_ascii=False, indent=2)}")
    
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(url, headers=headers, json=data, timeout=30) as response:
                print(f"   Status: {response.status}")
                
                if response.status == 200:
                    result = await response.json()
                    print(f"   Full response: {json.dumps(result, ensure_ascii=False, indent=2)}")
                    
                    # Extract content
                    if 'choices' in result and len(result['choices']) > 0:
                        choice = result['choices'][0]
                        content = ""
                        
                        # Try to get content from different fields
                        if 'message' in choice and 'content' in choice['message']:
                            content = choice['message']['content']
                        
                        # If content is empty, try reasoning_content
                        if not content and 'message' in choice and 'reasoning_content' in choice['message']:
                            content = choice['message']['reasoning_content']
                        
                        if content:
                            print(f"✅ Success - Content: {content[:200]}...")  # Truncate for readability
                            return True
                    
                    print("❌ Content not found in response")
                    return False
                else:
                    error_text = await response.text()
                    print(f"❌ Status {response.status}: {error_text}")
                    return False
    except Exception as e:
        print(f"💥 Exception: {str(e)}")
        return False

async def main():
    """Main function"""
    await test_taishang_api()

if __name__ == "__main__":
    asyncio.run(main())