#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MQTT设备处理服务测试
测试集成的MQTT服务功能
"""

import asyncio
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from services.online_script.device_handler_service import get_device_service, DeviceType
from services.online_script.mqtt_service import MQTTService
from datetime import datetime
import json
import time


def test_device_handler(message):
    """测试设备消息处理器"""
    print(f"[设备处理器] 收到消息:")
    print(f"  设备ID: {message.device_id}")
    print(f"  设备类型: {message.device_type.value}")
    print(f"  主题: {message.topic}")
    print(f"  载荷: {json.dumps(message.payload, ensure_ascii=False, indent=2)}")
    print(f"  时间戳: {datetime.fromtimestamp(message.timestamp).strftime('%Y-%m-%d %H:%M:%S')}")
    print("-" * 50)
    
    # 返回转发配置
    return {
        "forward": True,
        "payload": {
            "processed_by": "vwed_device_handler",
            "original_data": message.payload,
            "processed_time": datetime.now().isoformat()
        }
    }


async def test_mqtt_device_service():
    """测试MQTT设备处理服务"""
    print("=== MQTT设备处理服务测试 ===")
    
    # 获取设备服务实例
    device_service = get_device_service()
    
    try:
        # 启动服务
        print("启动设备处理服务...")
        await device_service.start_service()
        
        # 等待服务启动
        await asyncio.sleep(2)
        
        # 注册设备处理器
        print("注册设备处理器...")
        device_service.register_and_run(
            device_id="test_robot_001",
            device_type=DeviceType.ROBOT,
            listen_topics=["vwed/device/test_robot_001/data", "vwed/task/status"],
            forward_topics=["vwed/processed/test_robot_001"],
            handler=test_device_handler,
            script_id="test_script_001",
            description="测试机器人设备处理器"
        )
        
        # 等待注册完成
        await asyncio.sleep(1)
        
        # 发送测试消息
        print("发送测试消息...")
        
        test_messages = [
            {
                "topic": "vwed/device/test_robot_001/data",
                "payload": {
                    "robot_id": "test_robot_001",
                    "status": "running",
                    "battery": 75,
                    "position": {"x": 150, "y": 300},
                    "timestamp": datetime.now().isoformat()
                }
            },
            {
                "topic": "vwed/task/status", 
                "payload": {
                    "task_id": "task_001",
                    "status": "in_progress",
                    "progress": 60,
                    "timestamp": datetime.now().isoformat()
                }
            }
        ]
        
        for msg in test_messages:
            await device_service.publish_message(msg["topic"], msg["payload"])
            print(f"已发布消息到主题: {msg['topic']}")
            await asyncio.sleep(1)
        
        # 保持运行一段时间以接收消息
        print("保持服务运行30秒，等待消息处理...")
        await asyncio.sleep(30)
        
        # 查看统计信息
        print("\n=== 设备处理统计 ===")
        stats = device_service.get_running_handlers()
        print(json.dumps(stats, ensure_ascii=False, indent=2))
        
    except Exception as e:
        print(f"测试过程中出错: {e}")
        import traceback
        traceback.print_exc()
    
    finally:
        # 停止服务
        print("\n停止设备处理服务...")
        await device_service.stop_service()
        print("测试完成")


if __name__ == "__main__":
    # 运行测试
    asyncio.run(test_mqtt_device_service())