#!/usr/bin/env python3
"""
使用项目现有的Memory Bank代码来查看实例
"""

import sys
import os
import asyncio
sys.path.append('src')

from jixia.memory.factory import get_memory_backend
from config.doppler_config import get_google_genai_config

async def list_memory_banks():
    """使用项目的Memory Bank工厂来查看实例"""
    
    print("🧠 使用项目Memory Bank工厂查看实例")
    print("="*50)
    
    try:
        # 获取配置
        config = get_google_genai_config()
        print(f"📊 项目ID: {config.get('project_id')}")
        print(f"📍 位置: {config.get('location')}")
        print(f"🔑 Memory Bank启用: {config.get('memory_bank_enabled')}")
        
        # 获取Memory Bank后端
        print("\n🔍 正在获取Memory Bank后端...")
        memory_backend = get_memory_backend()
        print(f"✅ 成功获取Memory Bank后端: {type(memory_backend).__name__}")
        
        # 八仙列表
        immortals = [
            "tieguaili", "zhongliquan", "lvdongbin", "hehe_erxian", 
            "lantsaihe", "hanxiangzi", "caoguo_jiu", "hexiangu"
        ]
        
        print(f"\n🔍 正在检查八仙的Memory Bank实例...")
        print("="*50)
        
        for immortal in immortals:
            try:
                print(f"\n🧙‍♂️ {immortal}:")
                
                # 尝试创建Memory Bank
                memory_bank_id = await memory_backend.create_memory_bank(immortal)
                print(f"   ✅ Memory Bank ID: {memory_bank_id}")
                
                # 尝试搜索一些记忆（如果有的话）
                try:
                    memories = await memory_backend.search_memories(immortal, "投资", limit=3)
                    if memories:
                        print(f"   📝 找到 {len(memories)} 条记忆")
                        for i, memory in enumerate(memories[:2], 1):
                            content = memory.get('content', '无内容')[:50]
                            print(f"      {i}. {content}...")
                    else:
                        print(f"   📭 暂无记忆")
                except Exception as e:
                    print(f"   ⚠️  无法搜索记忆: {str(e)[:50]}...")
                    
            except Exception as e:
                print(f"   ❌ 错误: {str(e)[:50]}...")
        
        print(f"\n🎉 Memory Bank检查完成!")
        
    except Exception as e:
        print(f"\n❌ 主要错误: {str(e)}")
        print(f"🔧 错误类型: {type(e).__name__}")
        
        # 显示一些调试信息
        print("\n🔍 调试信息:")
        print(f"   Python路径: {sys.path[:3]}...")
        print(f"   当前目录: {os.getcwd()}")
        print(f"   环境变量:")
        for key in ['GOOGLE_API_KEY', 'GOOGLE_CLOUD_PROJECT_ID', 'VERTEX_MEMORY_BANK_ENABLED']:
            value = os.getenv(key, '未设置')
            if 'API_KEY' in key and value != '未设置':
                value = value[:10] + '...' if len(value) > 10 else value
            print(f"     {key}: {value}")

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