#!/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.mqtt_service import MQTTService
from datetime import datetime
import json
import time


def test_message_handler(topic: str, payload: str):
    """测试消息处理器"""
    print(f"[消息处理器] 收到消息:")
    print(f"  主题: {topic}")
    print(f"  内容: {payload}")
    print(f"  时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("-" * 50)


def test_mqtt_service():
    """测试独立MQTT服务"""
    print("=== MQTT服务独立测试 ===")
    
    # 创建MQTT服务
    mqtt_service = MQTTService()
    
    try:
        # 连接到服务器
        print("连接MQTT服务器...")
        if mqtt_service.connect():
            print("MQTT连接成功")
            
            # 订阅主题并添加处理器
            test_topics = [
                "vwed/test/message",
                "vwed/device/+/status",
                "vwed/task/status"
            ]
            
            for topic in test_topics:
                mqtt_service.subscribe(topic, test_message_handler)
                print(f"已订阅主题: {topic}")
            
            # 等待订阅完成
            time.sleep(2)
            
            # 发布测试消息
            print("\n发布测试消息...")
            test_messages = [
                {
                    "topic": "vwed/test/message",
                    "payload": {
                        "message": "Hello MQTT Service!",
                        "timestamp": datetime.now().isoformat(),
                        "test_id": "test_001"
                    }
                },
                {
                    "topic": "vwed/device/robot_001/status",
                    "payload": {
                        "device_id": "robot_001",
                        "status": "online",
                        "battery": 85,
                        "position": {"x": 100, "y": 200}
                    }
                },
                {
                    "topic": "vwed/task/status",
                    "payload": {
                        "task_id": "task_001",
                        "status": "running",
                        "progress": 75
                    }
                }
            ]
            
            for msg in test_messages:
                success = mqtt_service.publish(msg["topic"], msg["payload"])
                if success:
                    print(f"✓ 成功发布消息到: {msg['topic']}")
                else:
                    print(f"✗ 发布消息失败: {msg['topic']}")
                time.sleep(1)
            
            # 保持连接，监听消息
            print("\n保持连接30秒，监听消息...")
            time.sleep(30)
            
            # 显示连接信息
            print("\n=== 连接信息 ===")
            info = mqtt_service.get_connection_info()
            print(json.dumps(info, ensure_ascii=False, indent=2))
            
        else:
            print("MQTT连接失败")
            
    except Exception as e:
        print(f"测试过程中出错: {e}")
        import traceback
        traceback.print_exc()
        
    finally:
        # 断开连接
        print("\n断开MQTT连接...")
        mqtt_service.disconnect()
        print("测试完成")


if __name__ == "__main__":
    test_mqtt_service()