"""文件操作 Mixin — 设备端文件系统操作（通过引擎 HTTP API）

注意: PC ↔ 设备文件传输（push/pull）在 remote.py (RemoteMixin) 中实现，
因为这些操作只能从 PC 侧发起，不能在设备端 Python 内调用。
"""

from __future__ import annotations

from typing import TYPE_CHECKING, List, Optional

from ..types import FileInfo

if TYPE_CHECKING:
    from ..device import Device


class FileMixin:
    """设备文件系统操作（读、写、列目录、删除等）"""

    _client: ...

    def list_files(self, path: str = "/sdcard") -> List[FileInfo]:
        """列出目录内容

        Args:
            path: 设备目录路径

        Returns:
            文件信息列表
        """
        result = self._client.get_json("/file/list", params={"path": path})
        files = []
        if isinstance(result, list):
            for item in result:
                if isinstance(item, dict):
                    files.append(FileInfo(
                        name=item.get("name", ""),
                        path=item.get("path", ""),
                        is_dir=item.get("isDir", item.get("is_dir", False)),
                        size=int(item.get("size", 0)),
                        modified=item.get("modified", ""),
                    ))
        return files

    def read_file(self, path: str) -> str:
        """读取设备上的文本文件"""
        return self._client.get_text("/file/read-text", params={"path": path})

    def write_file(self, path: str, content: str) -> None:
        """写入文本文件到设备"""
        self._client.post_json("/file/write-text", {"path": path, "content": content})

    def file_exists(self, path: str) -> bool:
        """检查文件或目录是否存在"""
        try:
            result = self._client.get_json("/file/exists", params={"path": path})
            if isinstance(result, dict):
                return bool(result.get("exists", False))
            # 兼容旧版本文本响应
            return str(result).strip().lower() in ("true", "1", "yes")
        except Exception:
            return False

    def mkdir(self, path: str) -> None:
        """创建目录（递归创建）"""
        self._client.get_json("/file/mkdir", params={"path": path})

    def remove(self, path: str) -> None:
        """删除文件或目录"""
        self._client.get_json("/file/delete", params={"path": path})

    def rename(self, old_path: str, new_name: str) -> Optional[str]:
        """重命名文件或目录

        Args:
            old_path: 原路径
            new_name: 新文件名（不含路径）

        Returns:
            新路径，失败返回 None
        """
        result = self._client.post_json("/file/rename", {"oldPath": old_path, "newName": new_name})
        if isinstance(result, dict):
            return result.get("newPath") if result.get("success") else None
        return None

    def file_last_modified(self, path: str) -> float:
        """获取文件最后修改时间戳（Unix 秒）"""
        result = self._client.get_json("/file/last-modified", params={"path": path})
        if isinstance(result, dict):
            return float(result.get("lastModified", 0))
        return 0.0

    def media_scan(self, path: str) -> None:
        """通知系统媒体扫描（用于使新增图片出现在相册）"""
        self._client.auto_api("/media_scan", {"path": path})
