"""
工作手机SDK v3.0 - 闲鱼技能（服务端）

与设备端 agent/skills/xianyu/skill.py 对应；
实际执行以设备端为准，本模块供 unified 路由与 ADB 模式占位。
"""

from typing import Dict, Any, List
from skills.base import BaseSkill
import logging

logger = logging.getLogger(__name__)


class XianyuSkill(BaseSkill):
    """闲鱼控制技能（服务端定义，执行在设备端或 ADB）"""

    PACKAGE = "com.taobao.idlefish"
    NAME = "闲鱼"

    async def send_message(self, to_id: str, content: str, msg_type: str = "text") -> Dict[str, Any]:
        """发送闲鱼私信（设备端执行或 ADB UI 自动化）"""
        try:
            self.launch()
            self.sleep(2)
            self.click_text("消息")
            self.sleep(1)
            self.click_text("搜索")
            self.sleep(0.5)
            self.input_text(to_id)
            self.sleep(1)
            if not self.click_text(to_id):
                return {"success": False, "error": f"未找到用户: {to_id}"}
            self.sleep(1)
            self.input_text(content, clear=False)
            self.sleep(0.3)
            self.click_text("发送")
            logger.info(f"闲鱼私信发送成功: {to_id}")
            return {"success": True, "message_id": f"xy_{int(self.d.info.get('currentTime', 0))}"}
        except Exception as e:
            logger.error(f"闲鱼发送失败: {e}")
            return {"success": False, "error": str(e)}

    async def get_messages(self, limit: int = 20) -> Dict[str, Any]:
        """获取私信列表（设备端或 UI 树解析）"""
        try:
            self.launch()
            self.sleep(2)
            self.click_text("消息")
            self.sleep(1)
            ui_tree = self.get_ui_tree()
            messages = self._parse_messages_from_ui_tree(ui_tree, limit)
            return {"success": True, "messages": messages}
        except Exception as e:
            return {"success": False, "error": str(e), "messages": []}

    @staticmethod
    def _parse_messages_from_ui_tree(xml: str, limit: int) -> List[Dict[str, Any]]:
        """从 UI 树解析消息占位"""
        messages = []
        if not xml:
            return messages
        import re
        for i, m in enumerate(re.finditer(r'\btext="([^"]{1,200})"', xml)):
            if i >= limit:
                break
            text = m.group(1).strip()
            if text and text not in ("消息", "搜索", "发送", "私信"):
                messages.append({
                    "message_id": f"xy_ui_{i}",
                    "content": text,
                    "from_id": "",
                    "to_id": "",
                    "timestamp": 0,
                    "is_self": False,
                })
        return messages
