/**
 * 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; state: 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 }>;
  delete: (sessionId: string) => Promise<{ success: boolean }>;
  getMessages: (sessionId: string) => Promise<Array<{
    id: string;
    role: string;
    content: string;
    reasoningContent?: string;
    toolCalls?: unknown[];
    attachments?: Array<{ id: string; name: string; type: string; size: number; preview?: string; textContent?: string }>;
    timestamp: number;
  }>>;
  pin: (sessionId: string, pinned: boolean) => Promise<{ success: boolean }>;
  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 }>;
  removeServer: (name: string) => Promise<{ success: boolean }>;
  toggleServer: (name: string, enabled: boolean) => Promise<{ success: boolean }>;
}

// ===== 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[]>;
}

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

interface MetonaConfigAPI {
  get: (key: string) => Promise<string | null>;
  set: (key: string, value: unknown) => Promise<{ success: boolean }>;
}

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

interface MetonaAppAPI {
  getVersion: () => Promise<string>;
  getAppDataPath: () => Promise<string>;
  openExternal: (url: string) => Promise<void>;
  showItemInFolder: (path: string) => void;
  selectFolder: (defaultPath?: string) => Promise<{ canceled: boolean; path: 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;
}

interface MetonaToolsAPI {
  list: () => Promise<MetonaToolInfo[]>;
  toggle: (toolName: string, enabled: boolean) => Promise<{ success: boolean }>;
}

// ===== 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 }>;
}

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

export interface MetonaBridge {
  agent: MetonaAgentAPI;
  sessions: MetonaSessionsAPI;
  mcp: MetonaMCPAPI;
  memory: MetonaMemoryAPI;
  config: MetonaConfigAPI;
  app: MetonaAppAPI;
  toast: MetonaToastAPI;
  tools: MetonaToolsAPI;
  data: MetonaDataAPI;
}

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