"""
SystemState - 机器人系统状态

存储机器人自身的状态信息，如电量、位置、任务等
"""

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
import time


class RobotMode(Enum):
    """机器人模式枚举"""
    IDLE = "idle"
    WORKING = "working"
    CHARGING = "charging"
    ERROR = "error"
    MAINTENANCE = "maintenance"


@dataclass
class SystemState:
    """
    系统状态类
    
    Attributes:
        battery: 电量 (0-100)
        position: 位置 [x, y, z]
        mode: 当前模式
        current_task: 当前任务
        error_code: 错误码 (0 表示无错误)
        timestamp: 状态时间戳
    """
    battery: float = 100.0
    position: list = field(default_factory=lambda: [0.0, 0.0, 0.0])
    mode: str = "idle"
    current_task: str = ""
    error_code: int = 0
    timestamp: float = field(default_factory=time.time)
    
    def update(self, new_data: dict, current_time: float | None = None) -> dict:
        """
        更新系统状态，返回变化部分
        
        Args:
            new_data: 新数据字典
            current_time: 当前时间戳
            
        Returns:
            变化的数据字典
        """
        if current_time is None:
            current_time = time.time()
            
        diff = {}
        for key, value in new_data.items():
            if hasattr(self, key):
                old_value = getattr(self, key)
                if old_value != value:
                    diff[key] = {'old': old_value, 'new': value}
                    setattr(self, key, value)
        
        self.timestamp = current_time
        return diff
    
    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            'battery': self.battery,
            'position': self.position,
            'mode': self.mode,
            'current_task': self.current_task,
            'error_code': self.error_code,
            'timestamp': self.timestamp,
        }
    
    @classmethod
    def from_dict(cls, data: dict) -> SystemState:
        """从字典创建"""
        return cls(
            battery=data.get('battery', 100.0),
            position=data.get('position', [0.0, 0.0, 0.0]),
            mode=data.get('mode', 'idle'),
            current_task=data.get('current_task', ''),
            error_code=data.get('error_code', 0),
            timestamp=data.get('timestamp', time.time()),
        )