/**
 * MetonaAI Desktop — 全局类型声明
 *
 * 为渲染进程暴露的 window.metona API 提供类型支持。
 * 使用具体类型替代 unknown，确保类型安全。
 */

// ===== Metona IR 类型（渲染进程侧子集） =====

/** MetonaMessage — IR 标准消息类型（渲染进程可构造的部分） */
interface MetonaMessageInput {
  role: 'user' | 'assistant' | 'system' | 'tool';
  content: string;
  reasoningContent?: string;
  toolCalls?: Array<{ id: string; name: string; args: Record<string, unknown> }>;
  timestamp: number;
  iteration?: number;
  images?: Array<{ url: string; detail?: 'low' | 'high' | 'auto' }>;
}

// ===== Agent API =====

interface MetonaStreamEventData {
  type: string;
  requestId?: string;
  sessionId?: string;
  iteration?: number;
  seq?: number;
  timestamp?: number;
  delta?: string;
  content?: string;
  toolCall?: {
    id: string;
    name: string;
    args: Record<string, unknown>;
  };
  toolResult?: {
    toolCallId: string;
    toolName: string;
    success: boolean;
    result?: unknown;
    error?: string;
    durationMs?: number;
  };
  usage?: {
    inputTokens?: number;
    outputTokens?: number;
    totalTokens?: number;
  };
  error?: {
    code: string;
    message: string;
    retryable?: boolean;
  };
  state?: string;
}

interface MetonaAgentAPI {
  /** 发送 MetonaMessage（IR 类型）+ sessionId 到主进程 */
  sendMessage: (message: MetonaMessageInput, sessionId: string) => Promise<{ success: boolean }>;
  onStreamEvent: (callback: (event: MetonaStreamEventData) => void) => () => void;
  onStateChange: (callback: (state: {
    sessionId: string | null;
    iteration: number;
    state: string;
    previous: string;
    current: string;
  }) => void) => () => void;
  abortSession: (sessionId: string) => Promise<{ success: boolean }>;
  onProviderSwitched: (callback: (data: { from?: string; to?: string; reason?: string }) => void) => () => void;
}

// ===== Sessions API =====

interface MetonaSessionInfo {
  id: string;
  title: string;
  createdAt: number;
  updatedAt: number;
  messageCount: number;
  pinned: boolean;
  archived: boolean;
}

interface MetonaSessionsAPI {
  list: () => Promise<MetonaSessionInfo[]>;
  create: (title?: string) => Promise<MetonaSessionInfo>;
  rename: (sessionId: string, title: string) => Promise<{ success: boolean; error?: string }>;
  delete: (sessionId: string) => Promise<{ success: boolean; error?: string }>;
  getMessages: (sessionId: string) => Promise<Array<{
    id: string;
    role: string;
    content: string;
    reasoningContent?: string;
    toolCalls?: unknown[];
    toolResult?: unknown;
    attachments?: Array<{ id: string; name: string; type: string; size: number; preview?: string; textContent?: string }>;
    iteration?: number;
    timestamp: number;
  }>>;
  pin: (sessionId: string, pinned: boolean) => Promise<{ success: boolean; error?: string }>;
  archive: (sessionId: string, archived: boolean) => Promise<{ success: boolean; error?: string }>;
  deleteMessage: (messageId: string) => Promise<{ success: boolean }>;
  clearMessages: (sessionId: string) => Promise<{ success: boolean }>;
  saveTrace: (sessionId: string, data: { traceSteps: unknown[]; tokenUsage: unknown }) => Promise<{ success: boolean }>;
  getTrace: (sessionId: string) => Promise<{ traceSteps: unknown[]; tokenUsage: unknown } | null>;
}

// ===== MCP API =====

interface MetonaMCPServerConfig {
  name: string;
  transport: 'stdio' | 'sse';
  command?: string;
  args?: string[];
  url?: string;
  enabled: boolean;
}

interface MetonaMCPServerStatus {
  name: string;
  status: 'connecting' | 'connected' | 'disconnected' | 'error';
  toolCount: number;
  error?: string;
}

interface MetonaMCPAPI {
  listServers: () => Promise<MetonaMCPServerStatus[]>;
  addServer: (config: MetonaMCPServerConfig) => Promise<{ success: boolean; error?: string }>;
  removeServer: (name: string) => Promise<{ success: boolean; error?: string }>;
  toggleServer: (name: string, enabled: boolean) => Promise<{ success: boolean; error?: string }>;
}

// ===== Memory API =====

interface MetonaMemorySearchResult {
  id: string;
  type: 'episodic' | 'semantic' | 'working';
  content: string;
  summary?: string;
  importance: number;
  relevanceScore: number;
  createdAt: number;
}

interface MetonaMemoryAPI {
  search: (query: string, options?: {
    topK?: number;
    type?: 'episodic' | 'semantic' | 'working';
    minImportance?: number;
  }) => Promise<MetonaMemorySearchResult[]>;
  listAll: (options?: { type?: string; limit?: number }) => Promise<{
    success: boolean;
    data?: { episodic?: unknown[]; semantic?: unknown[]; working?: unknown[] };
    error?: string;
  }>;
  delete: (type: string, id: string) => Promise<{ success: boolean; error?: string }>;
}

// ===== Config API =====

interface MetonaConfigAPI {
  get: (key: string) => Promise<unknown>;
  set: (key: string, value: unknown) => Promise<{ success: boolean; error?: string }>;
  // v0.3.9: 批量保存配置，避免串行保存中间态触发 reloadAdapter 失败
  setBatch: (entries: Array<{ key: string; value: unknown }>) => Promise<{ success: boolean; error?: string }>;
  // v0.3.17: 监听配置变更广播（后端 config:set/setBatch 后触发，用于前端 store 实时更新）
  onChanged: (callback: (data: { key: string; value: unknown }) => void) => () => void;
}

// ===== App API =====

interface MetonaAppAPI {
  getVersion: () => Promise<string>;
  getAppDataPath: () => Promise<string>;
  openExternal: (url: string) => Promise<{ success: boolean; error?: string }>;
  showItemInFolder: (path: string) => Promise<{ success: boolean; error?: string }>;
  selectFolder: (defaultPath?: string) => Promise<{ canceled: boolean; path: string }>;
  restart: () => Promise<{ success: boolean }>;
  reportError: (payload: unknown) => void;
}

// ===== Workspace API =====

interface MetonaWorkspaceCheckResult {
  valid: boolean;
  path?: string;
  exists?: boolean;
  missingFiles?: string[];
  isNewWorkspace?: boolean;
  /** 目标目录下 .metona/agent.db 是否存在（用于判断是否显示"继承数据库"选项） */
  dbExists?: boolean;
  reason?: string;
}

interface MetonaWorkspaceInheritResult {
  success: boolean;
  inherited?: string[];
  failed?: Array<{ file: string; error: string }>;
  error?: string;
}

interface MetonaWorkspaceFileInfo {
  name: string;
  path: string;
  exists: boolean;
  size: number;
  mtime: number;
  preview: string;
}

interface MetonaWorkspaceDirInfo {
  name: string;
  path: string;
  exists: boolean;
  fileCount: number;
}

interface MetonaWorkspaceInfo {
  path: string;
  files: MetonaWorkspaceFileInfo[];
  dirs: MetonaWorkspaceDirInfo[];
}

interface MetonaWorkspaceAPI {
  check: (targetPath: string) => Promise<MetonaWorkspaceCheckResult>;
  inheritFiles: (params: { targetPath: string; sourcePath: string; files: string[] }) =>
    Promise<MetonaWorkspaceInheritResult>;
  getInfo: () => Promise<MetonaWorkspaceInfo>;
  // #51 修复: 校验源数据库完整性（PRAGMA integrity_check）
  checkDatabaseIntegrity: (sourcePath: string) => Promise<{
    success: boolean;
    ok?: boolean;
    detail?: string;
    error?: string;
  }>;
}

// ===== Toast API =====

interface MetonaToastAPI {
  onShow: (callback: (data: {
    type: 'success' | 'error' | 'warning' | 'info';
    message: string;
    options?: Record<string, unknown>;
  }) => void) => () => void;
}

// ===== Tools API =====

interface MetonaToolInfo {
  name: string;
  description: string;
  category: string;
  riskLevel: string;
  requiresPermission: boolean;
  enabled: boolean;
}

interface MetonaToolsAPI {
  list: () => Promise<MetonaToolInfo[]>;
  toggle: (toolName: string, enabled: boolean) => Promise<{ success: boolean; error?: string }>;
  /** v0.3.18 修复: 监听工具就绪事件（MCP 初始化完成后触发） */
  onReady: (callback: (data: { toolCount: number }) => void) => () => void;
  /** v0.3.18 修复: 查询工具当前是否已就绪（解决事件竞态） */
  isReady: () => Promise<{ ready: boolean; toolCount: number }>;
}

// ===== SearXNG API =====

interface MetonaSearXNGTestResult {
  success: boolean;
  statusCode?: number;
  latencyMs?: number;
  error?: string;
}

interface MetonaSearXNGAPI {
  /** 测试 SearXNG 实例连接可达性与认证有效性 */
  testConnection: (url: string, authKey: string, authType: string) => Promise<MetonaSearXNGTestResult>;
}

// ===== Data API =====

interface MetonaDataAPI {
  exportData: (sessionId?: string) => Promise<{ success: boolean; data?: unknown; error?: string }>;
  clearSessions: () => Promise<{ success: boolean; error?: string }>;
  clearMemories: () => Promise<{ success: boolean; error?: string }>;
  clearAuditLogs: () => Promise<{ success: boolean; error?: string }>;
}

// ===== v0.2.0: Tasks API =====

interface MetonaTask {
  id: string;
  session_id: string;
  title: string;
  description: string;
  status: 'pending' | 'in_progress' | 'completed' | 'blocked' | 'cancelled';
  priority: 'low' | 'medium' | 'high' | 'critical';
  parent_id: string | null;
  assigned_to: string | null;
  order_idx: number;
  created_at: number;
  updated_at: number;
  completed_at: number | null;
}

interface MetonaTasksAPI {
  list: (sessionId?: string) => Promise<{ success: boolean; data: MetonaTask[] }>;
  create: (data: {
    sessionId: string;
    title: string;
    description?: string;
    priority?: string;
    parentId?: string;
  }) => Promise<{ success: boolean; id?: string; error?: string }>;
  update: (
    id: string,
    updates: {
      title?: string;
      description?: string;
      status?: string;
      priority?: string;
      assignedTo?: string;
    },
    sessionId: string,
  ) => Promise<{ success: boolean; error?: string }>;
  delete: (id: string, sessionId: string) => Promise<{ success: boolean; error?: string }>;
  // P2（v0.3.13）: 订阅任务变更事件
  onTaskChanged: (callback: (sessionId: string) => void) => () => void;
}

// ===== v0.2.0: Audit API =====

interface MetonaAuditVerifyResult {
  success: boolean;
  valid: boolean;
  totalRecords: number;
  verifiedRecords: number;
  tamperedId: number | null;
  error?: string;
}

interface MetonaAuditAPI {
  verifyChain: () => Promise<MetonaAuditVerifyResult>;
  query: (filters?: { sessionId?: string; eventType?: string; limit?: number }) =>
    Promise<{ success: boolean; data?: unknown[]; error?: string }>;
}

// ===== v0.2.0: Tool Confirmation API =====

interface MetonaConfirmationRequest {
  toolCallId: string;
  toolName: string;
  args: Record<string, unknown>;
  riskLevel: string;
  reason: string;
  /** v0.3.2: 过期时间戳（ms），由后端 ConfirmationHook 注入，用于倒计时 */
  expiresAt?: number;
}

interface MetonaToolAPI {
  onConfirmationRequest: (callback: (request: MetonaConfirmationRequest) => void) => () => void;
  sendConfirmationResponse: (response: {
    toolCallId: string;
    approved: boolean;
    remember: boolean;
    autoExecute?: boolean;
  }) => void;
  /** v0.3.2: 批量确认响应（并行工具一次性审批，支持同工具多次调用） */
  sendConfirmationResponseBatch: (response: {
    toolCallIds: string[];
    approved: boolean;
    remember: boolean;
    autoExecute?: boolean;
  }) => void;
  /**
   * v0.3.2: 拉取当前所有 pending 确认
   * 前端弹框打开时主动调用，防止并行 IPC 事件在前端 state 中互相覆盖导致丢失
   */
  getPendingConfirmations: () => Promise<{
    success: boolean;
    data: MetonaConfirmationRequest[];
  }>;
  /** 设置/取消工具的持久化自动执行（跨会话不再询问） */
  setAutoExecute: (toolName: string, enabled: boolean) => Promise<{ success: boolean; error?: string }>;
  /** 获取已设置为自动执行的工具列表 */
  getAutoExecuteList: () => Promise<{ success: boolean; data: string[] }>;
}

// ===== Bridge 接口 =====

interface MetonaBridge {
  agent: MetonaAgentAPI;
  sessions: MetonaSessionsAPI;
  mcp: MetonaMCPAPI;
  memory: MetonaMemoryAPI;
  config: MetonaConfigAPI;
  app: MetonaAppAPI;
  workspace: MetonaWorkspaceAPI;
  toast: MetonaToastAPI;
  tools: MetonaToolsAPI;
  data: MetonaDataAPI;
  searxng: MetonaSearXNGAPI;
  tasks: MetonaTasksAPI;
  audit: MetonaAuditAPI;
  tool: MetonaToolAPI;
}

// ===== 全局 Window 增强 =====

interface Window {
  metona: MetonaBridge;
  electron: unknown;
}
