/**
 * Copyright (c) 2025 TWork Team. All rights reserved.
 * This source code is licensed under the TWork License.
 */

/**
 * TWork 浏览器桥接 — 协议类型定义
 *
 * 桥接架构：浏览器扩展（MV3）经 native messaging 拉起本地 host，host 监听
 * 本机命名管道；TWork 主进程作为管道客户端连接 host，调用浏览器工具。
 * 无 HTTP、无端口：管道仅本机可达 + 一次性 token 握手。
 *
 * wire 协议（换行分隔 JSON，与 host/src/pipe-server.js 保持一致）：
 * - 握手：客户端首条消息必须是 { method: "hello", token }，
 *   应答 { ok: true, result: { version, pid } }，token 不符立即断开。
 * - 请求：{ id, method, params }，应答 { id, ok, result | error }。
 * - 推送：无 id 帧 { method, params }（双向均可），用于聊天事件等单向流。
 */

/** host 启动后写入的信息文件内容（bridge-info.json），客户端据此发现管道与令牌 */
export interface BridgeInfo {
  version: string;
  pipe: string;
  token: string;
  pid: number;
  startedAt: string;
}

/** host 暴露的工具元数据（list_tools 返回项） */
export interface BridgeToolMeta {
  name: string;
  description?: string;
  inputSchema?: Record<string, unknown>;
}

/** 管道请求帧 */
export interface BridgeRequest {
  id: number;
  method: string;
  params?: Record<string, unknown>;
}

/** 管道应答帧 */
export interface BridgeResponse {
  id: number | null;
  ok: boolean;
  result?: unknown;
  error?: string;
}

/** call_tool 返回的内容块（与 MCP content 块同构） */
export interface BridgeContentBlock {
  type: 'text' | 'image';
  text?: string;
  mimeType?: string;
  data?: string;
}

/** bridge_status 应答 */
export interface BridgeStatus {
  version: string;
  pid: number;
  browserCore?: Record<string, unknown>;
}

// ---------------------------------------------------------------------------
// 聊天协议（扩展侧栏 ↔ TWork Agent，经 host 透传）
// ---------------------------------------------------------------------------

/** 管道推送帧（无 id，单向） */
export interface BridgeNotify {
  method: string;
  params?: Record<string, unknown>;
}

/** 扩展 → TWork：发送一条聊天消息（method="chat_send"） */
export interface BridgeChatSendParams {
  /** 缺省时由 TWork 创建/复用扩展专用会话，并在 accepted 事件中回传 */
  conversationId?: string;
  text: string;
  /** 页面上下文（background 自动附带当前活动 tab） */
  pageUrl?: string;
  pageTitle?: string;
  /** 右键菜单选中文本 */
  selection?: string;
  /** 会话级模型（等价桌面版手动切换模型；缺省沿用会话既有模型） */
  modelConfigId?: string;
  /** 目标工作区；与当前专用会话不一致时 TWork 新建会话并回传新 conversationId */
  workspaceId?: string;
}

/** 模型配置选项（chat_config 下行，与桌面版 MODEL_CONFIG_LIST 同源精简字段） */
export interface BridgeModelOption {
  id: string;
  name: string;
  provider?: string;
  model?: string;
  enabled?: boolean;
}

/** 工作区选项（chat_config 下行，与 database.getWorkspaces 同源） */
export interface BridgeWorkspaceOption {
  id: string;
  name: string;
  path?: string;
}

/** TWork → 扩展：聊天配置（method="chat_config"，响应 chat_config_request） */
export interface BridgeChatConfig {
  /** 与请求帧对应的 requestId，便于面板对答 */
  requestId?: string;
  models: BridgeModelOption[];
  workspaces: BridgeWorkspaceOption[];
  current?: {
    modelConfigId?: string;
    workspaceId?: string;
    conversationId?: string;
  };
  error?: string;
}

/** 桌面版 → 扩展：打开侧栏并定位会话（method="sidepanel_open"） */
export interface BridgeSidepanelOpenParams {
  conversationId?: string;
  workspaceId?: string;
}

/** 扩展 → TWork：拉取会话历史（method="chat_history_request"，双向互通的会话记录同步） */
export interface BridgeChatHistoryRequestParams {
  requestId?: string;
  conversationId: string;
}

/** 历史消息条目（角色已归一为展示层三态） */
export interface BridgeChatHistoryItem {
  id: string;
  role: 'user' | 'assistant' | 'system';
  content: string;
  at?: number;
  /** 工具调用摘要（历史消息里均已完成；侧栏渲染为折叠卡片） */
  toolCalls?: Array<{ name: string; status: 'start' | 'end' }>;
  /** 思考过程（截断后；侧栏渲染为折叠区） */
  thinking?: string;
}

/** TWork → 扩展：会话历史（method="chat_history"，响应 chat_history_request） */
export interface BridgeChatHistory {
  requestId?: string;
  conversationId: string;
  messages: BridgeChatHistoryItem[];
  /** 历史被截断（只回最近 N 条） */
  truncated?: boolean;
  /** 该会话当前有进行中的回合（侧栏重开后据此恢复 busy/回复中状态） */
  active?: boolean;
  error?: string;
}

/** TWork → 扩展：聊天流事件（method="chat_event"） */
export type BridgeChatEventType = 'accepted' | 'delta' | 'thinking' | 'tool' | 'complete' | 'error';

export interface BridgeChatEvent {
  type: BridgeChatEventType;
  conversationId: string;
  turnId?: string;
  /** delta：流式文本增量（已合批） */
  delta?: string;
  /** thinking：思考过程全量快照（节流+截尾，替换语义；完整版终态后重拉历史对齐） */
  thinking?: string;
  /** tool：工具调用摘要 */
  toolName?: string;
  toolStatus?: 'start' | 'end';
  /** complete：最终完整回复 */
  text?: string;
  /** error：错误文案 */
  error?: string;
  at?: number;
}
