#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试Cloudflare网关的Gemini API
使用用户提供的新配置
"""

import requests
import json
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def test_cloudflare_gemini():
    """测试Cloudflare网关的Gemini API"""
    
    # 用户提供的新配置
    API_KEY = "AIzaSyAQ2TXFAzmTKm4aFqgrjkhjgsp95bDsAyE"
    BASE_URL = "https://gateway.ai.cloudflare.com/v1/e167cb36a5b95cb3cc8daf77a3f7d0b3/default/google-ai-studio"
    MODEL = "models/gemini-2.5-pro"
    
    logger.info(f"🧪 测试Cloudflare Gemini配置:")
    logger.info(f"📡 BASE_URL: {BASE_URL}")
    logger.info(f"🔑 API_KEY: {API_KEY[:10]}...")
    logger.info(f"🤖 MODEL: {MODEL}")
    
    # 构建请求
    url = f"{BASE_URL}/v1beta/{MODEL}:generateContent"
    
    headers = {
        "Content-Type": "application/json",
        "x-goog-api-key": API_KEY
    }
    
    payload = {
        "contents": [
            {
                "parts": [
                    {
                        "text": "你好，请简单介绍一下你自己"
                    }
                ]
            }
        ],
        "generationConfig": {
            "maxOutputTokens": 1000,
            "temperature": 0.7
        }
    }
    
    try:
        logger.info("🚀 发送请求到Cloudflare网关...")
        logger.info(f"📍 请求URL: {url}")
        
        response = requests.post(
            url,
            json=payload,
            headers=headers,
            timeout=60
        )
        
        logger.info(f"📊 状态码: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            logger.info(f"✅ 请求成功!")
            logger.info(f"📋 完整响应: {json.dumps(result, ensure_ascii=False, indent=2)}")
            
            # 提取内容
            if 'candidates' in result and len(result['candidates']) > 0:
                candidate = result['candidates'][0]
                if 'content' in candidate and 'parts' in candidate['content']:
                    content = candidate['content']['parts'][0].get('text', '')
                    logger.info(f"🗣️ Gemini回应: {content}")
                    return True, content
            
            return True, "响应格式异常"
            
        else:
            logger.error(f"❌ 请求失败: {response.status_code}")
            logger.error(f"📋 错误响应: {response.text}")
            return False, response.text
            
    except requests.exceptions.Timeout:
        logger.error(f"⏰ 请求超时 (60秒)")
        return False, "请求超时"
    except requests.exceptions.ConnectionError as e:
        logger.error(f"🔌 连接错误: {e}")
        return False, str(e)
    except Exception as e:
        logger.error(f"💥 未知错误: {e}")
        return False, str(e)

def test_gemini_breakdown():
    """测试Gemini的问题分解能力"""
    
    API_KEY = "AIzaSyAQ2TXFAzmTKm4aFqgrjkhjgsp95bDsAyE"
    BASE_URL = "https://gateway.ai.cloudflare.com/v1/e167cb36a5b95cb3cc8daf77a3f7d0b3/default/google-ai-studio"
    MODEL = "models/gemini-2.5-pro"
    
    url = f"{BASE_URL}/v1beta/{MODEL}:generateContent"
    
    headers = {
        "Content-Type": "application/json",
        "x-goog-api-key": API_KEY
    }
    
    topic = "工作量证明vs无限制爬虫：从李时珍采药到AI数据获取的激励机制变革"
    
    payload = {
        "contents": [
            {
                "parts": [
                    {
                        "text": f"你是太上老君，负责将复杂问题分解为多个子问题。请将以下问题分解为3-5个子问题，以JSON格式返回：\n\n{topic}\n\n返回格式：{{\"subtopics\": [{{\"title\": \"子问题标题\", \"description\": \"详细描述\"}}]}}"
                    }
                ]
            }
        ],
        "generationConfig": {
            "maxOutputTokens": 2000,
            "temperature": 0.7
        }
    }
    
    try:
        logger.info("🧠 测试Gemini问题分解能力...")
        
        response = requests.post(
            url,
            json=payload,
            headers=headers,
            timeout=60
        )
        
        logger.info(f"📊 状态码: {response.status_code}")
        
        if response.status_code == 200:
            result = response.json()
            logger.info(f"✅ 分解测试成功!")
            
            # 提取内容
            if 'candidates' in result and len(result['candidates']) > 0:
                candidate = result['candidates'][0]
                if 'content' in candidate and 'parts' in candidate['content']:
                    content = candidate['content']['parts'][0].get('text', '')
                    logger.info(f"📋 分解结果:\n{content}")
                    
                    # 尝试解析JSON
                    try:
                        # 提取JSON部分
                        if '```json' in content:
                            json_start = content.find('```json') + 7
                            json_end = content.find('```', json_start)
                            json_content = content[json_start:json_end].strip()
                        elif '{' in content and '}' in content:
                            json_start = content.find('{')
                            json_end = content.rfind('}') + 1
                            json_content = content[json_start:json_end]
                        else:
                            json_content = content
                        
                        parsed_json = json.loads(json_content)
                        logger.info(f"🎯 JSON解析成功: {json.dumps(parsed_json, ensure_ascii=False, indent=2)}")
                        return True, parsed_json
                        
                    except json.JSONDecodeError as e:
                        logger.warning(f"⚠️ JSON解析失败: {e}")
                        logger.warning(f"📝 原始内容: {content}")
                        return True, content
            
            return True, "响应格式异常"
            
        else:
            logger.error(f"❌ 分解测试失败: {response.status_code}")
            logger.error(f"📋 错误响应: {response.text}")
            return False, response.text
            
    except Exception as e:
        logger.error(f"💥 分解测试错误: {e}")
        return False, str(e)

if __name__ == "__main__":
    logger.info("🎯 开始Cloudflare Gemini API测试")
    
    # 基础连接测试
    success1, result1 = test_cloudflare_gemini()
    
    if success1:
        logger.info("🎉 基础测试通过！")
        
        # 问题分解测试
        success2, result2 = test_gemini_breakdown()
        
        if success2:
            logger.info("🎉 所有测试通过！Gemini API工作正常")
            logger.info("✅ 可以安全运行完整的循环赛系统")
        else:
            logger.error("💀 问题分解测试失败")
    else:
        logger.error("💀 基础连接测试失败")
    
    logger.info("🏁 测试完成")