"""
工作手机SDK v3.0 - 微信技能
"""

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

logger = logging.getLogger(__name__)


class WechatSkill(BaseSkill):
    """微信控制技能"""
    
    PACKAGE = "com.tencent.mm"
    NAME = "微信"
    
    # UI元素（需根据微信版本调整）
    RES_SEARCH = "com.tencent.mm:id/j6p"
    RES_CHAT_INPUT = "com.tencent.mm:id/bkk"
    RES_SEND_BTN = "com.tencent.mm:id/bko"
    
    async def send_message(self, to_id: str, content: str, msg_type: str = "text") -> Dict[str, Any]:
        """
        发送微信消息
        
        Args:
            to_id: 联系人名称或备注
            content: 消息内容
            msg_type: 消息类型 (text/image)
        """
        try:
            # 启动微信
            self.launch()
            self.sleep(2)
            
            # 搜索联系人
            if not self.click_text("搜索"):
                # 尝试点击放大镜图标
                self.click_resource_id(self.RES_SEARCH)
            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)
            
            # 输入消息
            if not self.click_resource_id(self.RES_CHAT_INPUT):
                # 尝试点击输入框区域
                self.click_text("输入")
            self.sleep(0.3)
            
            self.input_text(content, clear=False)
            self.sleep(0.3)
            
            # 发送
            if not self.click_resource_id(self.RES_SEND_BTN):
                self.click_text("发送")
            
            logger.info(f"微信消息发送成功: {to_id}")
            return {"success": True, "message_id": f"wx_{int(self.d.info['currentTime'])}"}
        
        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)
            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 树 XML 解析文本条目作为消息占位"""
        messages = []
        if not xml:
            return messages
        skip = {"搜索", "发送", "输入", "通讯录", "微信", "聊天", "我"}
        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 skip:
                messages.append({
                    "message_id": f"wx_ui_{i}",
                    "content": text,
                    "from_id": "",
                    "to_id": "",
                    "timestamp": 0,
                    "is_self": False,
                })
        return messages
    
    async def get_contacts(self, limit: int = 100) -> Dict[str, Any]:
        """获取联系人列表（从 UI 树解析文本占位）"""
        try:
            self.launch()
            self.sleep(2)
            self.click_text("通讯录")
            self.sleep(1)
            ui_tree = self.get_ui_tree()
            contacts = self._parse_contacts_from_ui_tree(ui_tree, limit)
            return {"success": True, "contacts": contacts}
        except Exception as e:
            return {"success": False, "error": str(e), "contacts": []}

    @staticmethod
    def _parse_contacts_from_ui_tree(xml: str, limit: int) -> List[Dict[str, Any]]:
        """从 UI 树 XML 解析文本条目作为联系人占位"""
        contacts = []
        if not xml:
            return contacts
        skip = {"通讯录", "搜索", "添加朋友", "新的朋友", "群聊", "标签", "公众号", "微信", "我"}
        for i, m in enumerate(re.finditer(r'\btext="([^"]{1,100})"', xml)):
            if i >= limit:
                break
            text = m.group(1).strip()
            if text and len(text) >= 1 and text not in skip:
                contacts.append({"user_id": f"wx_contact_{i}", "nickname": text, "remark": ""})
        return contacts
    
    async def add_friend(self, user_id: str, message: str = "") -> Dict[str, Any]:
        """添加好友"""
        try:
            self.launch()
            self.sleep(2)
            
            # 点击+
            self.click_text("+") or self.click_text("添加")
            self.sleep(0.5)
            
            # 添加朋友
            self.click_text("添加朋友")
            self.sleep(0.5)
            
            # 输入微信号
            self.input_text(user_id)
            self.sleep(1)
            
            # 搜索
            self.click_text("搜索")
            self.sleep(2)
            
            # 添加
            if self.click_text("添加到通讯录"):
                if message:
                    self.input_text(message)
                self.click_text("发送")
                return {"success": True}
            
            return {"success": False, "error": "未找到用户"}
        
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    async def accept_friend(self, user_id: str) -> Dict[str, Any]:
        """通过好友请求"""
        try:
            self.launch()
            self.sleep(2)
            
            # 点击通讯录
            self.click_text("通讯录")
            self.sleep(1)
            
            # 新的朋友
            self.click_text("新的朋友")
            self.sleep(1)
            
            # 找到并通过
            if self.click_text("接受"):
                return {"success": True}
            
            return {"success": False, "error": "未找到好友请求"}
        
        except Exception as e:
            return {"success": False, "error": str(e)}
