"""设备信息 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


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

    _client: ...

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

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

        Returns:
            {"width": 1080, "height": 2340}
        """
        result = self._client.auto_api("/screen_size")
        if isinstance(result, dict):
            return {
                "width": int(result.get("width", 0)),
                "height": int(result.get("height", 0)),
            }
        return {"width": 0, "height": 0}

    def device_info(self) -> Dict[str, Any]:
        """获取引擎基本信息 (PID / UID / 版本等)

        Returns:
            {"pid": ..., "uid": ..., "version": ..., ...}
        """
        pid = self._client.auto_api("/pid")
        uid = self._client.auto_api("/uid")
        version = self._client.auto_api("/version")
        return {
            "pid": pid,
            "uid": uid,
            "version": version,
        }

    def get_touch_mode(self) -> Dict[str, Any]:
        """获取当前触控模式

        Returns:
            {"mode": "kernel|uinput|java", "use_ra": bool, ...}
        """
        result = self._client.auto_api("/get_touch_mode")
        if isinstance(result, dict):
            return result
        return {"mode": "unknown"}

    def set_touch_mode(self, mode: str = "auto") -> Dict[str, Any]:
        """设置触控模式

        Args:
            mode: "auto" / "kernel" / "uinput" / "java"
                  - auto: 自动选择最佳模式
                  - kernel: 直写 /dev/input/eventX（最自然）
                  - uinput: 克隆真实设备的 uinput
                  - java: InputManager Java API（兼容性最好）

        Returns:
            {"mode": "kernel", "use_ra": true}
        """
        result = self._client.auto_api("/set_touch_mode", {"mode": mode})
        if isinstance(result, dict):
            return result
        return {}

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

    def http_get(self, url: str) -> str:
        """在设备端发起 HTTP GET 请求

        Args:
            url: 要请求的 URL

        Returns:
            响应文本
        """
        result = self._client.auto_api("/http_get", {"url": url})
        return str(result) if result else ""

    def foreground(self) -> Dict[str, str]:
        """获取当前前台应用信息（含 package 和 activity）

        Returns:
            {"package": "com.xxx", "activity": ".MainActivity"}
        """
        result = self._client.auto_api("/foreground")
        if isinstance(result, dict):
            return result
        if isinstance(result, str) and "/" in result:
            parts = result.split("/", 1)
            return {"package": parts[0], "activity": parts[1]}
        return {"package": str(result) if result else "", "activity": ""}

    def foreground_package(self) -> str:
        """获取当前前台应用包名"""
        result = self._client.auto_api("/foreground_package")
        return str(result) if result else ""

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

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