#!/usr/bin/env python3
"""
通过Google Cloud Console查看Memory Bank资源
"""

import sys
import os
import asyncio
import json
import subprocess
from datetime import datetime
sys.path.append('src')

from config.doppler_config import get_google_genai_config

def get_access_token():
    """获取Google Cloud访问令牌"""
    try:
        result = subprocess.run(
            ['gcloud', 'auth', 'print-access-token'],
            capture_output=True,
            text=True,
            check=True
        )
        return result.stdout.strip()
    except subprocess.CalledProcessError as e:
        print(f"❌ 获取访问令牌失败: {e}")
        return None

def make_api_request(url, token):
    """发起API请求"""
    import requests
    
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json'
    }
    
    try:
        response = requests.get(url, headers=headers)
        return response.status_code, response.json() if response.content else {}
    except Exception as e:
        return None, str(e)

def main():
    print("🔍 通过GCP API查看Memory Bank资源")
    print("=" * 60)
    
    # 获取配置
    config = get_google_genai_config()
    project_id = config.get('project_id')
    location = config.get('location', 'us-central1')
    
    print(f"📊 项目ID: {project_id}")
    print(f"📍 位置: {location}")
    print(f"🕐 查询时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print()
    
    # 获取访问令牌
    print("🔑 获取访问令牌...")
    token = get_access_token()
    if not token:
        print("❌ 无法获取访问令牌")
        return
    print(f"✅ 访问令牌: {token[:20]}...")
    print()
    
    # 尝试不同的API端点
    api_endpoints = [
        # Vertex AI API
        f"https://aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/operations",
        f"https://aiplatform.googleapis.com/v1beta1/projects/{project_id}/locations/{location}/operations",
        
        # Generative Language API
        f"https://generativelanguage.googleapis.com/v1beta/projects/{project_id}/locations/{location}/operations",
        
        # 尝试Memory Bank相关端点
        f"https://aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/memoryBanks",
        f"https://aiplatform.googleapis.com/v1beta1/projects/{project_id}/locations/{location}/memoryBanks",
        
        # 尝试其他可能的端点
        f"https://generativelanguage.googleapis.com/v1beta/projects/{project_id}/locations/{location}/memoryBanks",
        f"https://generativelanguage.googleapis.com/v1/projects/{project_id}/locations/{location}/memoryBanks",
    ]
    
    print("🌐 测试API端点...")
    print("-" * 40)
    
    for i, endpoint in enumerate(api_endpoints, 1):
        print(f"{i}. 测试: {endpoint.split('/')[-2]}/{endpoint.split('/')[-1]}")
        
        status_code, response = make_api_request(endpoint, token)
        
        if status_code == 200:
            print(f"   ✅ 成功 (200): 找到 {len(response.get('operations', response.get('memoryBanks', [])))} 个资源")
            if response:
                print(f"   📄 响应预览: {str(response)[:100]}...")
        elif status_code == 404:
            print(f"   ⚠️ 未找到 (404): 端点不存在")
        elif status_code == 403:
            print(f"   🚫 权限不足 (403): 需要更多权限")
        elif status_code:
            print(f"   ❌ 错误 ({status_code}): {str(response)[:50]}...")
        else:
            print(f"   💥 请求失败: {response}")
        print()
    
    # 查看项目信息
    print("📋 项目信息...")
    project_url = f"https://cloudresourcemanager.googleapis.com/v1/projects/{project_id}"
    status_code, response = make_api_request(project_url, token)
    
    if status_code == 200:
        print(f"   ✅ 项目名称: {response.get('name', 'N/A')}")
        print(f"   📊 项目编号: {response.get('projectNumber', 'N/A')}")
        print(f"   🏷️ 项目ID: {response.get('projectId', 'N/A')}")
        print(f"   📅 创建时间: {response.get('createTime', 'N/A')}")
        print(f"   🔄 生命周期: {response.get('lifecycleState', 'N/A')}")
    else:
        print(f"   ❌ 无法获取项目信息: {status_code}")
    print()
    
    # 查看启用的服务
    print("🔧 查看启用的AI相关服务...")
    services_url = f"https://serviceusage.googleapis.com/v1/projects/{project_id}/services"
    status_code, response = make_api_request(services_url, token)
    
    if status_code == 200:
        services = response.get('services', [])
        ai_services = [s for s in services if 'ai' in s.get('config', {}).get('name', '').lower() or 'generative' in s.get('config', {}).get('name', '').lower()]
        
        print(f"   📊 总服务数: {len(services)}")
        print(f"   🤖 AI相关服务: {len(ai_services)}")
        
        for service in ai_services[:10]:  # 显示前10个
            name = service.get('config', {}).get('name', 'Unknown')
            state = service.get('state', 'Unknown')
            print(f"      • {name}: {state}")
    else:
        print(f"   ❌ 无法获取服务信息: {status_code}")
    
    print()
    print("🎯 Memory Bank访问建议:")
    print("   1. 在Google Cloud Console中访问:")
    print(f"      https://console.cloud.google.com/vertex-ai/generative/memory-banks?project={project_id}")
    print("   2. 或者访问Vertex AI主页:")
    print(f"      https://console.cloud.google.com/vertex-ai?project={project_id}")
    print("   3. Memory Bank功能可能在'生成式AI'或'实验性功能'部分")
    print()
    print("🎉 GCP API查询完成!")
    print("=" * 60)

if __name__ == "__main__":
    main()