"""智能体元数据（对齐 Java ``AgentMeta``）。

机器人上线时通过 ``PassiveCallback.on_robot_online(agent_id, agent_meta)`` 交给二开侧。
"""

from __future__ import annotations

from typing import Any, Dict, Optional


class AgentMeta:
    """只读元数据视图。

    Java 版直接复用 fastjson2 的 JSONObject 取值；Python 版做一层 dict 包装，
    并提供 ``get_wakeup_word`` 等便捷访问器。
    """

    __slots__ = ("_meta",)

    def __init__(self, meta: Optional[Dict[str, Any]] = None) -> None:
        self._meta: Dict[str, Any] = dict(meta) if meta else {}

    # --- well-known keys ---------------------------------------------------------

    def get_wakeup_word(self) -> Optional[str]:
        return self._meta.get("def.wakeupWord")

    def get_city(self) -> Optional[str]:
        return self._meta.get("def.city")

    def get_robot_name(self) -> Optional[str]:
        return self._meta.get("def.robotName")

    def get_buzz_word(self) -> Optional[str]:
        return self._meta.get("def.buzzWord")

    # --- generic typed getters ---------------------------------------------------

    def get_string(self, key: str) -> Optional[str]:
        value = self._meta.get(key)
        return None if value is None else str(value)

    def get_integer(self, key: str) -> Optional[int]:
        value = self._meta.get(key)
        if value is None or isinstance(value, bool):
            return None
        try:
            return int(value)
        except (TypeError, ValueError):
            return None

    get_long = get_integer

    def get_short(self, key: str) -> Optional[int]:
        return self.get_integer(key)

    def get_double(self, key: str) -> Optional[float]:
        value = self._meta.get(key)
        if value is None or isinstance(value, bool):
            return None
        try:
            return float(value)
        except (TypeError, ValueError):
            return None

    def get_boolean(self, key: str) -> Optional[bool]:
        value = self._meta.get(key)
        if value is None:
            return None
        if isinstance(value, bool):
            return value
        if isinstance(value, str):
            lo = value.lower()
            if lo == "true":
                return True
            if lo == "false":
                return False
            return None
        return bool(value)

    def raw(self) -> Dict[str, Any]:
        """底层 dict（**不拷贝**）。"""
        return self._meta

    def __contains__(self, key: str) -> bool:
        return key in self._meta

    def __repr__(self) -> str:
        return f"AgentMeta({self._meta!r})"

    def __str__(self) -> str:
        import json
        return json.dumps(self._meta, ensure_ascii=False)
