"""脚本项目管理 Mixin"""

from __future__ import annotations

from typing import TYPE_CHECKING, Dict, List, Optional

from ..types import ProjectInfo

if TYPE_CHECKING:
    from ..device import Device


class ProjectMixin:
    """脚本项目管理"""

    _client: ...

    def list_projects(self) -> List[ProjectInfo]:
        """列出设备上的脚本项目"""
        result = self._client.get_json("/project/list")
        projects: List[ProjectInfo] = []
        if isinstance(result, list):
            for item in result:
                if isinstance(item, dict):
                    projects.append(ProjectInfo(
                        name=item.get("name", ""),
                        path=item.get("path", ""),
                        running=item.get("running", False),
                    ))
        return projects

    def start_project(self, name: str) -> None:
        """启动脚本项目"""
        self._client.get_text("/project/start", params={"name": name})

    def stop_project(self) -> None:
        """停止当前运行的脚本项目"""
        self._client.get_text("/project/stop")

    def project_status(self, name: Optional[str] = None) -> Optional[Dict]:
        """获取项目运行状态

        Args:
            name: 项目名称，None 则返回当前运行项目状态

        Returns:
            状态 dict，或 None（无项目运行）
        """
        try:
            if name:
                result = self._client.get_json("/project/status", params={"name": name})
            else:
                result = self._client.get_json("/project/status")
            return result if isinstance(result, dict) else None
        except Exception:
            return None

    def run_code(self, code: str, timeout: float = 30) -> str:
        """在设备上执行 Python 代码片段

        Args:
            code: Python 代码（print() 输出会被捕获返回）
            timeout: 超时秒数

        Returns:
            stdout 输出文本
        """
        result = self._client.post_json("/engine/run-code", {"code": code}, timeout=timeout)
        # 服务器返回可能是:
        # - 字符串直接是输出
        # - {"output": "...", "success": true}
        # - {"success": true} (无输出)
        if isinstance(result, dict):
            output = result.get("output", result.get("result", ""))
            return str(output) if output else ""
        return str(result) if result else ""
