#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
脚本基础功能测试
快速验证脚本创建、编辑和执行的基本功能
"""

import asyncio
import sys
import os
from pathlib import Path

# 添加项目根目录到 Python 路径
sys.path.insert(0, str(Path(__file__).parent.parent))

print("开始脚本基础功能测试...")

async def test_basic_functionality():
    """测试基础功能"""
    try:
        # 测试导入
        print("1. 测试模块导入...")
        from services.online_script.script_file_service import get_file_service
        from services.online_script.script_engine_service import get_script_engine
        from services.online_script.script_registry_service import get_global_registry
        from utils.api_response import success_response, error_response
        print("✓ 模块导入成功")
        
        # 测试API响应函数
        print("\n2. 测试API响应函数...")
        success_resp = success_response(data={"test": "ok"}, message="测试成功")
        error_resp = error_response(message="测试错误", error="详细错误信息")
        
        assert success_resp["success"] == True
        assert success_resp["data"]["test"] == "ok"
        assert error_resp["success"] == False
        print("✓ API响应函数工作正常")
        
        # 测试服务实例化
        print("\n3. 测试服务实例化...")
        file_service = get_file_service()
        script_engine = get_script_engine()
        registry = get_global_registry()
        
        assert file_service is not None
        assert script_engine is not None
        assert registry is not None
        print("✓ 服务实例创建成功")
        
        # 测试注册中心基本功能
        print("\n4. 测试注册中心基本功能...")
        
        # 模拟注册一个函数
        def test_function(args):
            return {"result": "test_success", "args": args}
        
        registry.register_function(
            name="test_func",
            handler=test_function,
            script_id="test_script_123",
            description="测试函数"
        )
        
        # 验证函数注册
        func_info = registry.get_function_info("test_func")
        assert func_info is not None
        assert func_info["script_id"] == "test_script_123"
        print("✓ 注册中心功能正常")
        
        # 测试获取注册状态
        print("\n5. 测试获取注册状态...")
        registrations = registry.get_all_registrations()
        assert "registered_functions" in registrations
        assert "test_func" in registrations["registered_functions"]
        print("✓ 注册状态获取成功")
        
        # 清理测试数据
        print("\n6. 清理测试数据...")
        registry.clear_all()
        print("✓ 测试数据清理完成")
        
        return True
        
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False


async def test_script_content_validation():
    """测试脚本内容验证"""
    print("\n7. 测试脚本内容验证...")
    
    try:
        from services.online_script.script_file_service import get_file_service
        file_service = get_file_service()
        
        # 测试有效脚本
        valid_script = '''
def boot():
    print("Hello VWED!")
    
def test_function():
    return "test"
'''
        
        result = await file_service.validate_script_syntax(valid_script)
        assert result["success"] == True
        assert result["valid"] == True
        print("✓ 有效脚本验证通过")
        
        # 测试无效脚本
        invalid_script = '''
def boot():
    print("Hello VWED!"
    # 缺少闭合括号
'''
        
        result = await file_service.validate_script_syntax(invalid_script)
        assert result["success"] == True
        assert result["valid"] == False
        print("✓ 无效脚本验证正确识别")
        
        return True
        
    except Exception as e:
        print(f"❌ 脚本验证测试失败: {e}")
        return False


def create_sample_script_content():
    """创建示例脚本内容"""
    return '''def boot():
    """示例脚本启动函数"""
    VWED.log.sync_info("示例脚本启动")
    
    # 注册一个简单的API接口
    @VWED.api.get("/sample/hello", description="示例问候接口")
    def hello(request_data):
        name = request_data["query_params"].get("name", "World")
        return {"message": f"Hello, {name} from VWED Script!"}
    
    # 注册一个计算函数
    @VWED.function.register("sample_add", description="示例加法函数")
    def add_numbers(args):
        a = args.get("a", 0)
        b = args.get("b", 0)
        result = a + b
        VWED.log.sync_info(f"计算: {a} + {b} = {result}")
        return {"result": result, "operation": "addition"}
    
    # 注册事件监听器
    @VWED.event.listen("sample_event")
    def on_sample_event(event_data):
        VWED.log.sync_info(f"接收到示例事件: {event_data}")
    
    # 设置定时任务
    @VWED.timer.interval(60)
    def sample_timer():
        VWED.log.sync_info("示例定时任务执行")
    
    VWED.log.sync_info("示例脚本注册完成")

# 辅助函数示例
def helper_function(data):
    """辅助函数示例"""
    return {"processed": True, "data": data}
'''


async def main():
    """主测试函数"""
    print("🚀 开始脚本基础功能测试")
    print("="*50)
    
    # 基础功能测试
    basic_test = await test_basic_functionality()
    
    # 脚本验证测试
    validation_test = await test_script_content_validation()
    
    # 显示示例脚本内容
    print("\n8. 示例脚本内容:")
    print("-"*30)
    sample_content = create_sample_script_content()
    print(sample_content[:500] + "..." if len(sample_content) > 500 else sample_content)
    print("-"*30)
    print("✓ 示例脚本内容生成完成")
    
    # 测试结果
    print("\n" + "="*50)
    if basic_test and validation_test:
        print("🎉 所有基础功能测试通过！")
        print("\n可以继续进行以下测试:")
        print("1. 运行 test_script_integration.py 进行完整集成测试")
        print("2. 启动服务器后测试实际API调用")
        print("3. 通过WebSocket测试实时日志推送")
        success = True
    else:
        print("❌ 部分测试失败，请检查错误信息")
        success = False
    
    print("="*50)
    return success


if __name__ == "__main__":
    success = asyncio.run(main())
    sys.exit(0 if success else 1)