#!/usr/bin/env python3
"""
Discord Bot 测试脚本
用于本地测试bot功能，不连接Discord
"""

import asyncio
import sys
from pathlib import Path
import logging

# 添加项目路径
sys.path.append(str(Path(__file__).parent))

from slash_commands.terminal.terminal_handler import TerminalHandler
from utils.database import DatabaseManager
from utils.token_reader import TokenReader

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

logger = logging.getLogger(__name__)

async def test_terminal_handler():
    """测试Terminal处理器"""
    print("\n🧪 测试Terminal处理器...")
    
    handler = TerminalHandler()
    test_user_id = "test_user_123"
    
    # 测试命令列表
    test_commands = [
        "ls",
        "pwd", 
        "docker ps",
        "查看当前目录文件",
        "查看Docker容器状态",
        "rm -rf /",  # 应该被拒绝
    ]
    
    for command in test_commands:
        print(f"\n🔧 测试命令: {command}")
        try:
            result = await handler.handle_command(command, test_user_id)
            print(f"✅ 结果: {result[:200]}...")
        except Exception as e:
            print(f"❌ 错误: {e}")

def test_database():
    """测试数据库功能"""
    print("\n🧪 测试数据库功能...")
    
    try:
        # 使用测试数据库
        db_manager = DatabaseManager("./test.db")
        
        # 测试术语查询
        term_def = db_manager.get_term_definition("docker ps")
        print(f"✅ 术语定义: {term_def}")
        
        # 测试添加术语
        success = db_manager.add_term("test_term", "测试术语定义", "test", 1)
        print(f"✅ 添加术语: {'成功' if success else '失败'}")
        
        # 测试命令日志
        db_manager.log_command("test_user", "test command", "terminal", "success", "测试结果", 1.5)
        print("✅ 命令日志记录成功")
        
    except Exception as e:
        print(f"❌ 数据库测试失败: {e}")

def test_token_reader():
    """测试Token读取器"""
    print("\n🧪 测试Token读取器...")
    
    try:
        token_reader = TokenReader("/home/will/docker/tokens.txt")
        
        # 测试读取token
        tu_token = token_reader.get_token("tu_discord_token")
        print(f"✅ Tu Token: {tu_token[:20]}..." if tu_token else "❌ Tu Token读取失败")
        
        claude_api = token_reader.get_token("claude_API")
        print(f"✅ Claude API: {claude_api[:20]}..." if claude_api else "❌ Claude API读取失败")
        
    except Exception as e:
        print(f"❌ Token读取测试失败: {e}")

async def main():
    """主测试函数"""
    print("🚀 Discord Bot 功能测试")
    print("=" * 50)
    
    # 测试各个组件
    test_token_reader()
    test_database()
    await test_terminal_handler()
    
    print("\n" + "=" * 50)
    print("✅ 测试完成")

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