"""应用管理 Mixin"""

from __future__ import annotations

import time
from typing import TYPE_CHECKING, Dict, List, Optional

from ..types import AppInfo

if TYPE_CHECKING:
    from ..device import Device


def _unwrap(result):
    """解包 {'data': ..., 'ok': True} 格式响应"""
    if isinstance(result, dict) and "data" in result:
        return result["data"]
    return result


def _parse_foreground(data) -> Dict[str, str]:
    """解析前台应用信息，支持多种响应格式"""
    if isinstance(data, dict):
        if "package" in data:
            return data
        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": ""}


class AppMixin:
    """应用管理"""

    _client: ...

    def app_start(self, package: str, activity: Optional[str] = None, stop: bool = False) -> None:
        """启动应用"""
        if stop:
            self.app_stop(package)
            time.sleep(0.5)
        if activity:
            self._client.auto_api("/open_app", {"pkg": package, "activity": activity})
        else:
            self._client.auto_api("/open_app", {"pkg": package})

    def app_stop(self, package: str) -> None:
        """强制停止应用"""
        self._client.auto_api("/stop_app", {"pkg": package})

    def app_install(self, apk_path: str) -> None:
        """安装 APK（设备本地路径）"""
        self.shell(f"pm install -r {apk_path}")  # type: ignore

    def app_uninstall(self, package: str) -> None:
        """卸载应用"""
        self.shell(f"pm uninstall {package}")  # type: ignore

    def app_list(self, filter: Optional[str] = None) -> List[str]:
        """列出已安装的非系统应用包名"""
        result = self._client.get_json("/package/installed-apps")
        packages = result if isinstance(result, list) else []
        if filter:
            packages = [p for p in packages if filter.lower() in str(p).lower()]
        return packages

    def app_current(self) -> Dict[str, str]:
        """获取当前前台应用信息"""
        result = self._client.auto_api("/foreground")
        return _parse_foreground(_unwrap(result))

    def app_wait(self, package: str, timeout: float = 20) -> bool:
        """等待应用出现在前台"""
        deadline = time.time() + timeout
        while time.time() < deadline:
            current = self.app_current()
            if current.get("package") == package:
                return True
            time.sleep(0.5)
        return False

    def app_info(self, package: str) -> Dict:
        """获取应用详细信息（通过 dumpsys package）"""
        info: Dict = {"package": package}
        try:
            resp = self.shell(f"dumpsys package {package} | grep -E 'versionName|versionCode|firstInstall|lastUpdate|dataDir'")
            info["raw"] = resp.output[:500] if resp else ""
        except Exception:
            info["raw"] = ""
        return info

    def app_running(self, package: str) -> bool:
        """检查应用是否在运行"""
        result = self._client.auto_api("/is_app_running", {"pkg": package})
        data = _unwrap(result)
        if isinstance(data, bool):
            return data
        return str(data).lower() in ("true", "1")

    def bring_to_top(self, package: str) -> bool:
        """将指定应用移到前台"""
        result = self._client.auto_api("/bring_to_top", {"pkg": package})
        data = _unwrap(result)
        if isinstance(data, bool):
            return data
        return str(data).lower() in ("true", "1")

    def open_url(self, url: str) -> None:
        """用系统浏览器打开 URL"""
        self._client.auto_api("/open_url", {"url": url})
