"""
工作手机SDK v3.0 - 抖音技能
"""

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

logger = logging.getLogger(__name__)


class DouyinSkill(BaseSkill):
    """抖音控制技能"""
    
    PACKAGE = "com.ss.android.ugc.aweme"
    NAME = "抖音"
    
    async def send_message(self, to_id: str, content: str, msg_type: str = "text") -> Dict[str, Any]:
        """
        发送抖音私信
        
        Args:
            to_id: 用户名/昵称
            content: 消息内容
            msg_type: 消息类型
        """
        try:
            self.launch()
            self.sleep(3)
            
            # 点击消息
            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.click_text("发私信") or self.click_text("私信")
            self.sleep(1)
            
            # 输入消息
            self.input_text(content)
            self.sleep(0.3)
            
            # 发送
            self.click_text("发送")
            
            logger.info(f"抖音私信发送成功: {to_id}")
            return {"success": True, "message_id": f"dy_{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 树解析文本节点，供列表展示占位；完整解析依赖设备端或官方 API）"""
        try:
            self.launch()
            self.sleep(3)
            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 树 XML 中解析出文本条目，作为私信列表占位（通用简单解析）"""
        messages = []
        if not xml:
            return messages
        # 匹配 text="..." 且非空、非纯空白
        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"dy_ui_{i}",
                    "content": text,
                    "from_id": "",
                    "to_id": "",
                    "timestamp": 0,
                    "is_self": False,
                })
        return messages
    
    async def reply_comment(self, video_id: str, comment_id: str, content: str) -> Dict[str, Any]:
        """回复评论（需设备端进入视频评论区后执行点击回复+输入；服务端仅做接口占位）"""
        try:
            # 完整流程：进入视频页 -> 打开评论区 -> 定位评论 -> 点击回复 -> 输入 content -> 发送
            return {"success": False, "error": "评论回复需在设备端 Skill 或 UI 自动化中实现"}
        except Exception as e:
            return {"success": False, "error": str(e)}
    
    async def follow(self, user_id: str) -> Dict[str, Any]:
        """关注用户"""
        try:
            self.launch()
            self.sleep(3)
            
            # 搜索用户
            self.click_text("搜索")
            self.sleep(0.5)
            self.input_text(user_id)
            self.sleep(1)
            
            # 点击用户
            self.click_text(user_id)
            self.sleep(1)
            
            # 关注
            if self.click_text("关注"):
                return {"success": True}
            
            if self.exists("已关注") or self.exists("互相关注"):
                return {"success": True, "message": "已关注"}
            
            return {"success": False, "error": "关注失败"}
        
        except Exception as e:
            return {"success": False, "error": str(e)}
