/**
 * 工作手机SDK v3.0 - TypeScript客户端
 * 
 * 存客宝前端/Node.js后端使用此SDK调用工作手机服务
 * 
 * @author 卡若
 * @version 3.0.0
 * 
 * @example
 * // 初始化
 * const sdk = new WorkPhoneSDK({
 *   baseUrl: 'https://workphone.example.com',
 *   apiKey: 'your-api-key'
 * });
 * 
 * // 发送微信消息
 * const result = await sdk.sendMessage({
 *   deviceId: 'device-001',
 *   platform: 'wechat',
 *   toId: '张三',
 *   content: '你好！'
 * });
 */

// ============================================================================
// 类型定义
// ============================================================================

/** 支持的平台 */
export type Platform = 'wechat' | 'douyin' | 'xhs' | 'xianyu' | 'soul';

/** 消息类型 */
export type MessageType = 'text' | 'image' | 'video' | 'voice' | 'file' | 'link' | 'mini_program';

/** 执行通道 */
export type Channel =
  | 'hook'
  | 'frida'
  | 'websocket/frida'
  | 'websocket/hook'
  | 'websocket/u2'
  | 'official_api'
  | 'sdk_control'
  | 'ai_agent'
  | 'adb'
  | 'u2';

/** SDK配置 */
export interface WorkPhoneConfig {
  /** SDK服务器地址 */
  baseUrl: string;
  /** API密钥 */
  apiKey: string;
  /** 超时时间(毫秒)，默认30000 */
  timeout?: number;
}

/** 通用响应 */
export interface ApiResponse<T = any> {
  code: number;
  message?: string;
  data: T;
  channel_used?: Channel;
}

/** 设备信息 */
export interface DeviceInfo {
  device_id: string;
  name?: string;
  model?: string;
  status: 'online' | 'offline';
  android_version?: string;
  agent_version?: string;
  capabilities?: string[];
  apps?: string[];
  last_heartbeat?: string;
  project_id?: string;
}

/** 消息 */
export interface Message {
  message_id: string;
  from_id: string;
  to_id: string;
  content: string;
  msg_type: MessageType;
  timestamp: number;
  is_self: boolean;
}

/** 联系人 */
export interface Contact {
  id: string;
  name: string;
  remark?: string;
  avatar?: string;
  tags?: string[];
}

/** 群聊 */
export interface Group {
  id: string;
  name: string;
  member_count: number;
  owner_id?: string;
  notice?: string;
}

/** 朋友圈动态 */
export interface Moment {
  id: string;
  user_id: string;
  content: string;
  images?: string[];
  video_url?: string;
  location?: string;
  timestamp: number;
  like_count: number;
  comment_count: number;
}

// ============================================================================
// 请求参数类型
// ============================================================================

/** 发送消息参数 */
export interface SendMessageParams {
  deviceId: string;
  platform: Platform;
  toId: string;
  content: string;
  msgType?: MessageType;
  mediaUrl?: string;
  atList?: string[];
  /** 强制通道；微信默认建议 hook */
  channel?: Channel;
  /** Hook 扩展配置 */
  hookConfig?: Record<string, unknown>;
  /** 本次请求超时(秒) */
  timeoutSeconds?: number;
}

/** 获取消息参数 */
export interface GetMessagesParams {
  deviceId: string;
  platform: Platform;
  conversationId?: string;
  limit?: number;
  sinceTime?: number;
}

/** 添加好友参数 */
export interface AddFriendParams {
  deviceId: string;
  platform: Platform;
  userId: string;
  message?: string;
  source?: string;
}

/** 创建群聊参数 */
export interface CreateGroupParams {
  deviceId: string;
  platform: Platform;
  groupName: string;
  memberIds: string[];
}

/** 邀请入群参数 */
export interface InviteToGroupParams {
  deviceId: string;
  platform: Platform;
  groupId: string;
  memberIds: string[];
}

/** 群发消息参数 */
export interface GroupMessageParams {
  deviceId: string;
  platform: Platform;
  groupId: string;
  content: string;
  msgType?: MessageType;
  mediaUrl?: string;
  atAll?: boolean;
  atList?: string[];
}

/** 设置群欢迎语参数 */
export interface SetGroupWelcomeParams {
  deviceId: string;
  platform: Platform;
  groupId: string;
  welcomeText: string;
  welcomeImage?: string;
}

/** 添加标签参数 */
export interface AddTagParams {
  deviceId: string;
  platform: Platform;
  userId: string;
  tags: string[];
}

/** 发布朋友圈参数 */
export interface PostMomentsParams {
  deviceId: string;
  platform: Platform;
  content: string;
  images?: string[];
  videoUrl?: string;
  location?: string;
  visibleList?: string[];
  invisibleList?: string[];
}

/** 点赞朋友圈参数 */
export interface LikeMomentsParams {
  deviceId: string;
  platform: Platform;
  userId: string;
  postIndex?: number;
}

/** 评论朋友圈参数 */
export interface CommentMomentsParams {
  deviceId: string;
  platform: Platform;
  userId: string;
  postIndex?: number;
  comment: string;
  replyTo?: string;
}

/** AI任务参数 */
export interface ExecuteTaskParams {
  deviceId: string;
  task: string;
  llmProvider?: 'deepseek' | 'openai' | 'ollama';
  maxSteps?: number;
}

/** 批量发送消息参数 */
export interface BatchSendMessageParams {
  deviceId: string;
  platform: Platform;
  toIds: string[];
  content: string;
  msgType?: MessageType;
  mediaUrl?: string;
  /** 批量间隔(秒)，防风控默认 65s */
  interval?: number;
}

/** 批量添加好友参数 */
export interface BatchAddFriendParams {
  deviceId: string;
  platform: Platform;
  userIds: string[];
  message?: string;
  /** 批量间隔(秒)，防风控默认 180s */
  interval?: number;
}

// ============================================================================
// SDK主类
// ============================================================================

export class WorkPhoneSDK {
  private baseUrl: string;
  private apiKey: string;
  private timeout: number;

  constructor(config: WorkPhoneConfig) {
    this.baseUrl = config.baseUrl.replace(/\/$/, '');
    this.apiKey = config.apiKey;
    this.timeout = config.timeout || 30000;
  }

  // ==========================================================================
  // HTTP请求方法
  // ==========================================================================

  private async request<T>(
    method: 'GET' | 'POST' | 'PUT' | 'DELETE',
    path: string,
    data?: any
  ): Promise<ApiResponse<T>> {
    const url = `${this.baseUrl}${path}`;
    
    const options: RequestInit = {
      method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.apiKey}`,
      },
    };

    if (data && method !== 'GET') {
      options.body = JSON.stringify(data);
    }

    // 添加超时控制
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), this.timeout);
    options.signal = controller.signal;

    try {
      const response = await fetch(url, options);
      clearTimeout(timeoutId);
      
      const result = await response.json();
      
      if (!response.ok) {
        throw new Error(result.message || `HTTP ${response.status}`);
      }
      
      return result;
    } catch (error: any) {
      clearTimeout(timeoutId);
      if (error.name === 'AbortError') {
        throw new Error('请求超时');
      }
      throw error;
    }
  }

  private async get<T>(path: string, params?: Record<string, any>): Promise<ApiResponse<T>> {
    let url = path;
    if (params) {
      const searchParams = new URLSearchParams();
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          searchParams.append(key, String(value));
        }
      });
      const queryString = searchParams.toString();
      if (queryString) {
        url += `?${queryString}`;
      }
    }
    return this.request<T>('GET', url);
  }

  private async post<T>(path: string, data?: any): Promise<ApiResponse<T>> {
    return this.request<T>('POST', path, data);
  }

  // ==========================================================================
  // 一、消息管理
  // ==========================================================================

  /**
   * 发送消息（统一接口，自动选择最优通道）
   */
  async sendMessage(params: SendMessageParams): Promise<ApiResponse<{
    success: boolean;
    message_id?: string;
    error?: string;
    error_code?: 'contact_not_found' | 'timeout';
    timeout_seconds?: number;
  }>> {
    const body: Record<string, unknown> = {
      device_id: params.deviceId,
      platform: params.platform,
      to_id: params.toId,
      content: params.content,
      msg_type: params.msgType || 'text',
      media_url: params.mediaUrl,
      at_list: params.atList,
      channel: params.channel || 'hook',
      hook_config: params.hookConfig,
    };
    if (params.timeoutSeconds != null) body.timeout_seconds = params.timeoutSeconds;
    return this.post('/api/v3/message/send', body);
  }

  /**
   * 获取消息列表
   */
  async getMessages(params: GetMessagesParams): Promise<ApiResponse<{
    messages: Message[];
  }>> {
    return this.post('/api/v3/message/list', {
      device_id: params.deviceId,
      platform: params.platform,
      conversation_id: params.conversationId,
      limit: params.limit || 20,
      since_time: params.sinceTime,
    });
  }

  /**
   * 批量发送消息（与 unified 契约一致：data.sent / data.failed / data.total）
   */
  async batchSendMessage(params: BatchSendMessageParams): Promise<ApiResponse<{
    sent: Array<{ to_id: string; message_id?: string }>;
    failed: Array<{ to_id: string; error?: string }>;
    total: number;
  }>> {
    return this.post('/api/v3/message/batch-send', {
      device_id: params.deviceId,
      platform: params.platform,
      to_ids: params.toIds,
      content: params.content,
      msg_type: params.msgType || 'text',
      media_url: params.mediaUrl,
      interval: params.interval ?? 65,
    });
  }

  /**
   * 回复评论（抖音/小红书等）
   */
  async replyComment(params: {
    deviceId: string;
    platform: Platform;
    commentId: string;
    content: string;
    videoId?: string;
  }): Promise<ApiResponse<{ success: boolean; error?: string }>> {
    return this.post('/api/v3/comment/reply', {
      device_id: params.deviceId,
      platform: params.platform,
      comment_id: params.commentId,
      content: params.content,
      video_id: params.videoId,
    });
  }

  // ==========================================================================
  // 二、好友管理
  // ==========================================================================

  /**
   * 添加好友
   */
  async addFriend(params: AddFriendParams): Promise<ApiResponse<{
    success: boolean;
    error?: string;
  }>> {
    return this.post('/api/v3/friend/add', {
      device_id: params.deviceId,
      platform: params.platform,
      user_id: params.userId,
      message: params.message || '',
      source: params.source,
    });
  }

  /**
   * 通过好友请求
   */
  async acceptFriend(params: {
    deviceId: string;
    platform: Platform;
    userId: string;
  }): Promise<ApiResponse<{ success: boolean }>> {
    return this.post('/api/v3/friend/accept', {
      device_id: params.deviceId,
      platform: params.platform,
      user_id: params.userId,
    });
  }

  /**
   * 设置好友备注
   */
  async setFriendRemark(params: {
    deviceId: string;
    platform: Platform;
    userId: string;
    remark: string;
  }): Promise<ApiResponse<{ success: boolean }>> {
    return this.post('/api/v3/friend/set-remark', {
      device_id: params.deviceId,
      platform: params.platform,
      user_id: params.userId,
      remark: params.remark,
    });
  }

  /**
   * 删除好友
   */
  async deleteFriend(params: {
    deviceId: string;
    platform: Platform;
    userId: string;
  }): Promise<ApiResponse<{ success: boolean }>> {
    return this.post('/api/v3/friend/delete', {
      device_id: params.deviceId,
      platform: params.platform,
      user_id: params.userId,
    });
  }

  /**
   * 获取联系人列表
   */
  async getContacts(params: {
    deviceId: string;
    platform: Platform;
    limit?: number;
  }): Promise<ApiResponse<{ contacts: Contact[] }>> {
    return this.get('/api/v3/contacts', {
      device_id: params.deviceId,
      platform: params.platform,
      limit: params.limit || 100,
    });
  }

  /**
   * 批量添加好友
   */
  async batchAddFriend(params: BatchAddFriendParams): Promise<ApiResponse<{
    success_count?: number;
    failed_count?: number;
    results?: Array<{ user_id: string; success: boolean; error?: string }>;
  }>> {
    return this.post('/api/v3/friend/batch-add', {
      device_id: params.deviceId,
      platform: params.platform,
      user_ids: params.userIds,
      message: params.message || '',
      interval: params.interval ?? 180,
    });
  }

  // ==========================================================================
  // 三、群聊管理
  // ==========================================================================

  /**
   * 创建群聊
   */
  async createGroup(params: CreateGroupParams): Promise<ApiResponse<{
    success: boolean;
    group_id?: string;
  }>> {
    return this.post('/api/v3/group/create', {
      device_id: params.deviceId,
      platform: params.platform,
      group_name: params.groupName,
      member_ids: params.memberIds,
    });
  }

  /**
   * 邀请入群
   */
  async inviteToGroup(params: InviteToGroupParams): Promise<ApiResponse<{
    success: boolean;
    invited_count?: number;
  }>> {
    return this.post('/api/v3/group/invite', {
      device_id: params.deviceId,
      platform: params.platform,
      group_id: params.groupId,
      member_ids: params.memberIds,
    });
  }

  /**
   * 移出群聊
   */
  async removeFromGroup(params: {
    deviceId: string;
    platform: Platform;
    groupId: string;
    memberIds: string[];
  }): Promise<ApiResponse<{ success: boolean }>> {
    return this.post('/api/v3/group/remove', {
      device_id: params.deviceId,
      platform: params.platform,
      group_id: params.groupId,
      member_ids: params.memberIds,
    });
  }

  /**
   * 设置群公告
   */
  async setGroupNotice(params: {
    deviceId: string;
    platform: Platform;
    groupId: string;
    notice: string;
  }): Promise<ApiResponse<{ success: boolean }>> {
    return this.post('/api/v3/group/set-notice', {
      device_id: params.deviceId,
      platform: params.platform,
      group_id: params.groupId,
      notice: params.notice,
    });
  }

  /**
   * 设置群名
   */
  async setGroupName(params: {
    deviceId: string;
    platform: Platform;
    groupId: string;
    groupName: string;
  }): Promise<ApiResponse<{ success: boolean }>> {
    return this.post('/api/v3/group/set-name', {
      device_id: params.deviceId,
      platform: params.platform,
      group_id: params.groupId,
      group_name: params.groupName,
    });
  }

  /**
   * 发送群消息
   */
  async sendGroupMessage(params: GroupMessageParams): Promise<ApiResponse<{
    success: boolean;
    message_id?: string;
  }>> {
    return this.post('/api/v3/group/send-message', {
      device_id: params.deviceId,
      platform: params.platform,
      group_id: params.groupId,
      content: params.content,
      msg_type: params.msgType || 'text',
      media_url: params.mediaUrl,
      at_all: params.atAll || false,
      at_list: params.atList,
    });
  }

  /**
   * 设置群欢迎语
   */
  async setGroupWelcome(params: SetGroupWelcomeParams): Promise<ApiResponse<{
    success: boolean;
  }>> {
    return this.post('/api/v3/group/set-welcome', {
      device_id: params.deviceId,
      platform: params.platform,
      group_id: params.groupId,
      welcome_text: params.welcomeText,
      welcome_image: params.welcomeImage,
    });
  }

  /**
   * 获取群聊列表
   */
  async getGroups(params: {
    deviceId: string;
    platform: Platform;
    limit?: number;
  }): Promise<ApiResponse<{ groups: Group[] }>> {
    return this.get('/api/v3/group/list', {
      device_id: params.deviceId,
      platform: params.platform,
      limit: params.limit || 100,
    });
  }

  /**
   * 获取群成员列表
   */
  async getGroupMembers(params: {
    deviceId: string;
    platform: Platform;
    groupId: string;
  }): Promise<ApiResponse<{ members: Contact[] }>> {
    return this.get('/api/v3/group/members', {
      device_id: params.deviceId,
      platform: params.platform,
      group_id: params.groupId,
    });
  }

  // ==========================================================================
  // 四、标签管理
  // ==========================================================================

  /**
   * 给好友添加标签
   */
  async addTag(params: AddTagParams): Promise<ApiResponse<{ success: boolean }>> {
    return this.post('/api/v3/tag/add', {
      device_id: params.deviceId,
      platform: params.platform,
      user_id: params.userId,
      tags: params.tags,
    });
  }

  /**
   * 移除好友标签
   */
  async removeTag(params: AddTagParams): Promise<ApiResponse<{ success: boolean }>> {
    return this.post('/api/v3/tag/remove', {
      device_id: params.deviceId,
      platform: params.platform,
      user_id: params.userId,
      tags: params.tags,
    });
  }

  /**
   * 创建标签
   */
  async createTag(params: {
    deviceId: string;
    platform: Platform;
    tagName: string;
  }): Promise<ApiResponse<{ success: boolean }>> {
    return this.post('/api/v3/tag/create', {
      device_id: params.deviceId,
      platform: params.platform,
      tag_name: params.tagName,
    });
  }

  /**
   * 删除标签
   */
  async deleteTag(params: {
    deviceId: string;
    platform: Platform;
    tagName: string;
  }): Promise<ApiResponse<{ success: boolean }>> {
    return this.post('/api/v3/tag/delete', {
      device_id: params.deviceId,
      platform: params.platform,
      tag_name: params.tagName,
    });
  }

  /**
   * 获取标签列表
   */
  async getTags(params: {
    deviceId: string;
    platform: Platform;
  }): Promise<ApiResponse<{ tags: string[] }>> {
    return this.get('/api/v3/tag/list', {
      device_id: params.deviceId,
      platform: params.platform,
    });
  }

  /**
   * 根据标签获取好友列表
   */
  async getUsersByTag(params: {
    deviceId: string;
    platform: Platform;
    tagName: string;
    limit?: number;
  }): Promise<ApiResponse<{ users: Contact[] }>> {
    return this.post('/api/v3/tag/users', {
      device_id: params.deviceId,
      platform: params.platform,
      tag_name: params.tagName,
      limit: params.limit || 100,
    });
  }

  // ==========================================================================
  // 五、朋友圈管理
  // ==========================================================================

  /**
   * 发布朋友圈
   */
  async postMoments(params: PostMomentsParams): Promise<ApiResponse<{
    success: boolean;
    post_id?: string;
  }>> {
    return this.post('/api/v3/moments/post', {
      device_id: params.deviceId,
      platform: params.platform,
      content: params.content,
      images: params.images,
      video_url: params.videoUrl,
      location: params.location,
      visible_list: params.visibleList,
      invisible_list: params.invisibleList,
    });
  }

  /**
   * 点赞朋友圈
   */
  async likeMoments(params: LikeMomentsParams): Promise<ApiResponse<{
    success: boolean;
  }>> {
    return this.post('/api/v3/moments/like', {
      device_id: params.deviceId,
      platform: params.platform,
      user_id: params.userId,
      post_index: params.postIndex || 0,
    });
  }

  /**
   * 评论朋友圈
   */
  async commentMoments(params: CommentMomentsParams): Promise<ApiResponse<{
    success: boolean;
  }>> {
    return this.post('/api/v3/moments/comment', {
      device_id: params.deviceId,
      platform: params.platform,
      user_id: params.userId,
      post_index: params.postIndex || 0,
      comment: params.comment,
      reply_to: params.replyTo,
    });
  }

  /**
   * 获取朋友圈列表
   */
  async getMoments(params: {
    deviceId: string;
    platform: Platform;
    userId?: string;
    limit?: number;
  }): Promise<ApiResponse<{ moments: Moment[] }>> {
    return this.post('/api/v3/moments/list', {
      device_id: params.deviceId,
      platform: params.platform,
      user_id: params.userId,
      limit: params.limit || 10,
    });
  }

  // ==========================================================================
  // 六、设备管理
  // ==========================================================================

  /**
   * 获取设备列表
   */
  async getDevices(): Promise<ApiResponse<DeviceInfo[]>> {
    return this.get('/api/v3/devices');
  }

  /**
   * 获取设备详情
   */
  async getDevice(deviceId: string): Promise<ApiResponse<DeviceInfo>> {
    return this.get(`/api/v3/devices/${deviceId}`);
  }

  /**
   * 设备截图
   */
  async screenshot(deviceId: string): Promise<ApiResponse<{
    image_url?: string;
    base64?: string;
    width: number;
    height: number;
  }>> {
    return this.post(`/api/v3/devices/${deviceId}/screenshot`);
  }

  /**
   * 获取UI树
   */
  async getUiTree(deviceId: string): Promise<ApiResponse<{
    ui_tree: string;
  }>> {
    return this.get(`/api/v3/devices/${deviceId}/ui-tree`);
  }

  /**
   * 检查设备是否在线
   */
  async isOnline(deviceId: string): Promise<boolean> {
    try {
      const result = await this.getDevice(deviceId);
      return result.code === 200 && result.data?.status === 'online';
    } catch {
      return false;
    }
  }

  /**
   * 获取在线设备列表
   */
  async getOnlineDevices(): Promise<DeviceInfo[]> {
    try {
      const result = await this.getDevices();
      if (result.code === 200 && Array.isArray(result.data)) {
        return result.data.filter(d => d.status === 'online');
      }
      return [];
    } catch {
      return [];
    }
  }

  // ==========================================================================
  // 七、AI Agent
  // ==========================================================================

  /**
   * 执行自然语言任务（AI Agent模式）
   */
  async executeTask(params: ExecuteTaskParams): Promise<ApiResponse<{
    success: boolean;
    steps?: string[];
    duration_ms?: number;
    error?: string;
  }>> {
    return this.post('/api/v3/agent/execute', {
      device_id: params.deviceId,
      task: params.task,
      llm_provider: params.llmProvider || 'deepseek',
      max_steps: params.maxSteps || 30,
    });
  }

  /**
   * 获取Agent状态
   */
  async getAgentStatus(deviceId: string): Promise<ApiResponse<{
    status: 'idle' | 'running' | 'error';
    current_task?: string;
    current_step?: number;
  }>> {
    return this.get(`/api/v3/agent/status/${deviceId}`);
  }

  /**
   * 停止Agent任务
   */
  async stopAgent(deviceId: string): Promise<ApiResponse<{ success: boolean }>> {
    return this.post(`/api/v3/agent/stop/${deviceId}`);
  }

  /**
   * 获取设备 AI Brain 状态
   */
  async getAIBrainStatus(deviceId: string): Promise<ApiResponse<Record<string, unknown>>> {
    return this.get(`/api/v3/devices/${deviceId}/ai/status`);
  }

  /**
   * 推送 AI 任务（排队，心跳周期执行）
   */
  async pushAITask(deviceId: string, instruction: string, priority = 5): Promise<ApiResponse<{
    device_id: string;
    instruction: string;
    priority: number;
    status: string;
  }>> {
    return this.post(`/api/v3/devices/${deviceId}/ai/task`, { instruction, priority });
  }

  /**
   * 推送 AI 常驻指令
   */
  async pushAIStandingOrder(deviceId: string, order: string): Promise<ApiResponse<{
    device_id: string;
    order: string;
    status: string;
  }>> {
    return this.post(`/api/v3/devices/${deviceId}/ai/standing-order`, { order });
  }

  /**
   * 同步执行 AI 自然语言任务
   */
  async executeAITask(deviceId: string, task: string, timeout = 60): Promise<ApiResponse<Record<string, unknown>>> {
    return this.post(`/api/v3/devices/${deviceId}/ai/execute?${new URLSearchParams({ task, timeout: String(timeout) })}`);
  }

  /**
   * 中台大脑能力树（Skill Registry）
   * 需求 §3.7 #6 — 工作台展示可用能力（211 action / 150 平台）
   */
  async getSkillRegistry(): Promise<ApiResponse<{ skills: unknown; summary: Record<string, number> }>> {
    return this.get('/api/v3/ai/brain/skill-registry');
  }

  /**
   * 多平台精确 action（execute-script）
   * 需求 §3.7 #7 — 抖音/小红书/闲鱼/Soul 控机
   * @param script 平台脚本：wechat/douyin/xhs/xianyu/soul
   */
  async executeScript(
    deviceId: string,
    script: string,
    action: string,
    params: Record<string, unknown> = {},
  ): Promise<ApiResponse<Record<string, unknown>>> {
    return this.post('/api/v3/ai/brain/execute-script', { device_id: deviceId, script, action, params });
  }

  /**
   * 多设备批量 action（batch-execute）
   * 需求 §3.7 #8 — 多设备运营
   */
  async batchExecuteScript(
    deviceIds: string[],
    script: string,
    action: string,
    params: Record<string, unknown> = {},
  ): Promise<ApiResponse<Record<string, unknown>>> {
    return this.post('/api/v3/ai/brain/batch-execute', { device_ids: deviceIds, script, action, params });
  }

  // ==========================================================================
  // 八、底层控制（高级用法）
  // ==========================================================================

  /**
   * 点击坐标
   */
  async click(deviceId: string, x: number, y: number): Promise<ApiResponse<{ success: boolean }>> {
    return this.post(`/api/v3/devices/${deviceId}/click`, { x, y });
  }

  /**
   * 点击文字
   */
  async clickText(deviceId: string, text: string, timeout: number = 10): Promise<ApiResponse<{
    success: boolean;
  }>> {
    return this.post(`/api/v3/devices/${deviceId}/click-text`, { text, timeout });
  }

  /**
   * 输入文字
   */
  async input(deviceId: string, text: string, clear: boolean = true): Promise<ApiResponse<{
    success: boolean;
  }>> {
    return this.post(`/api/v3/devices/${deviceId}/input`, { text, clear });
  }

  /**
   * 滑动
   */
  async swipe(deviceId: string, direction: 'up' | 'down' | 'left' | 'right', scale: number = 0.8): Promise<ApiResponse<{
    success: boolean;
  }>> {
    return this.post(`/api/v3/devices/${deviceId}/swipe`, { direction, scale });
  }

  /**
   * 执行脚本（底层接口）
   */
  async execute(
    deviceId: string,
    script: string,
    action: string,
    params: Record<string, any> = {},
    timeout: number = 30
  ): Promise<ApiResponse<any>> {
    return this.post(`/api/v3/devices/${deviceId}/execute`, {
      script,
      action,
      params,
      timeout,
    });
  }

  // ==========================================================================
  // 九、快捷方法
  // ==========================================================================

  /**
   * 发送微信消息
   */
  async wechatSend(deviceId: string, toId: string, content: string) {
    return this.sendMessage({
      deviceId,
      platform: 'wechat',
      toId,
      content,
    });
  }

  /**
   * 发送抖音私信
   */
  async douyinSend(deviceId: string, toId: string, content: string) {
    return this.sendMessage({
      deviceId,
      platform: 'douyin',
      toId,
      content,
    });
  }

  /**
   * 发送小红书私信
   */
  async xhsSend(deviceId: string, toId: string, content: string) {
    return this.sendMessage({
      deviceId,
      platform: 'xhs',
      toId,
      content,
    });
  }

  /**
   * 发送闲鱼消息
   */
  async xianyuSend(deviceId: string, toId: string, content: string) {
    return this.sendMessage({
      deviceId,
      platform: 'xianyu',
      toId,
      content,
    });
  }

  /**
   * 发送 Soul 消息
   */
  async soulSend(deviceId: string, toId: string, content: string) {
    return this.sendMessage({
      deviceId,
      platform: 'soul',
      toId,
      content,
    });
  }

  /**
   * 健康检查
   */
  async healthCheck(): Promise<{
    status: string;
    version: string;
    devices_online: number;
  }> {
    const result = await this.get<{
      status: string;
      version: string;
      devices_online: number;
    }>('/health');
    return result.data || result as any;
  }
}

// 默认导出
export default WorkPhoneSDK;
