"""设备信息 Mixin — imei, screen_info, touch_mode, network 等"""

from __future__ import annotations

from typing import TYPE_CHECKING, Any, Dict, Optional

if TYPE_CHECKING:
    from ..device import Device


def _unwrap(result: Any, key: str = "data") -> Any:
    """解包服务器的 {'ok': True, 'data': 'xxx'} 格式响应"""
    if isinstance(result, dict) and "data" in result:
        return result["data"]
    return result


class DeviceInfoMixin:
    """设备信息与系统级 API"""

    _client: ...

    @property
    def imei(self) -> str:
        """获取设备 IMEI / 设备标识码"""
        result = self._client.auto_api("/imei")
        return str(_unwrap(result)) if result else ""

    def screen_info(self) -> Dict[str, int]:
        """获取屏幕宽高信息

        Returns:
            {"width": 1080, "height": 2340}
        """
        result = self._client.auto_api("/screen_size")
        data = _unwrap(result)
        if isinstance(data, dict):
            return {
                "width": int(data.get("width", 0)),
                "height": int(data.get("height", 0)),
            }
        # 解析 "1080x2340" 格式
        if isinstance(data, str) and "x" in data:
            parts = data.strip().split("x")
            try:
                return {"width": int(parts[0]), "height": int(parts[1])}
            except (ValueError, IndexError):
                pass
        return {"width": 0, "height": 0}

    def device_info(self) -> Dict[str, Any]:
        """获取引擎基本信息"""
        return {
            "pid": self.pid(),
            "version": self.version(),
        }

    def get_touch_mode(self) -> Dict[str, Any]:
        """获取当前触控模式"""
        result = self._client.auto_api("/get_touch_mode")
        data = _unwrap(result)
        if isinstance(data, dict):
            return data
        return {"mode": str(data) if data else "unknown"}

    def set_touch_mode(self, mode: str = "auto") -> Dict[str, Any]:
        """设置触控模式"""
        result = self._client.auto_api("/set_touch_mode", {"mode": mode})
        data = _unwrap(result)
        if isinstance(data, dict):
            return data
        return {}

    def is_net_online(self) -> bool:
        """检查设备网络是否连通"""
        result = self._client.auto_api("/is_net_online")
        data = _unwrap(result)
        if isinstance(data, bool):
            return data
        return str(data).lower() in ("true", "1", "yes")

    def http_get(self, url: str) -> str:
        """在设备端发起 HTTP GET 请求"""
        result = self._client.auto_api("/http_get", {"url": url})
        return str(_unwrap(result)) if result else ""

    def foreground(self) -> Dict[str, str]:
        """获取当前前台应用信息

        Returns:
            {"package": "com.xxx", "activity": ".MainActivity"}
        """
        result = self._client.auto_api("/foreground")
        data = _unwrap(result)
        return _parse_foreground(data)

    def foreground_package(self) -> str:
        """获取当前前台应用包名"""
        result = self._client.auto_api("/foreground_package")
        data = _unwrap(result)
        if data:
            # 可能是 "package activity pid" 格式
            s = str(data).strip().split()
            if s:
                return s[0]
        return ""

    def version(self) -> str:
        """获取 yyds.auto 引擎版本号"""
        result = self._client.auto_api("/version")
        return str(_unwrap(result)) if result else ""

    def pid(self) -> int:
        """获取引擎进程 PID"""
        result = self._client.auto_api("/pid")
        data = _unwrap(result)
        try:
            return int(str(data).strip())
        except (TypeError, ValueError):
            return -1

    @property
    def wlan_ip(self) -> str:
        """设备 WLAN IP 地址"""
        from .device_info import _unwrap  # noqa
        info = {}
        try:
            info = self._client.get_json("/")
        except Exception:
            pass
        if isinstance(info, dict):
            return info.get("wlanIp", info.get("wlan_ip", ""))
        return ""

    def update_language(self, code: str) -> bool:
        """设置安卓系统语言, 如 "en-us" """
        result = self._client.auto_api("/engine/update_language", {"language": code})
        return str(_unwrap(result)).lower() in ("true", "1", "yes")

    def media_scan_file(self, path: str) -> bool:
        """通知安卓系统扫描新文件, 多个路径以分号分隔"""
        result = self._client.auto_api("/engine/media_scan_file", {"path": path})
        return str(_unwrap(result)).lower() in ("true", "1", "yes")


def _parse_foreground(data: Any) -> Dict[str, str]:
    """解析前台应用信息，支持多种响应格式"""
    if isinstance(data, dict):
        # 已是 dict 且有 package 字段
        if "package" in data:
            return data
        # {'packageName': ..., 'className': ...} 格式
        pkg = data.get("packageName", data.get("pkg", ""))
        act = data.get("className", data.get("activity", ""))
        return {"package": str(pkg), "activity": str(act)}
    if isinstance(data, str):
        # "com.android.launcher .Launcher 4932" 格式
        parts = data.strip().split()
        pkg = parts[0] if len(parts) > 0 else ""
        act = parts[1] if len(parts) > 1 else ""
        return {"package": pkg, "activity": act}
    return {"package": "", "activity": ""}
