// --- 客户端 → 服务端 ---

export interface ChatAttachment {
  id: string;
  type: 'image' | 'video' | 'pdf' | 'document' | 'other';
  url: string;
  name: string;
  size: number;
  mimeType: string;
  role?: 'start_frame' | 'end_frame';
}

export interface ClientChatMessage {
  type: 'chat';
  sessionId: string;
  content: string;
  agentName?: string;
  agentId?: number;
  leafEntryId?: string | null;
  attachments?: ChatAttachment[];
}

export interface ClientPingMessage {
  type: 'ping';
}

export interface ClientSetThinkingLevelMessage {
  type: 'set_thinking_level';
  sessionId: string;
  level: string;
}

export interface ClientClarifyResponseMessage {
  type: 'clarify_response';
  sessionId: string;
  requestId: string;
  answer: string;
}

export interface ClientToolConfirmationResponseMessage {
  type: 'tool_confirmation_response';
  sessionId: string;
  requestId: string;
  confirmed: boolean;
}

export interface ClientCompactMessage {
  type: 'compact';
  sessionId: string;
  instructions?: string;
}

export type ClientMessage = ClientChatMessage | ClientPingMessage | ClientSetThinkingLevelMessage | ClientClarifyResponseMessage | ClientToolConfirmationResponseMessage | ClientCompactMessage;

// --- 服务端 → 客户端 ---

export interface ServerTokenEvent {
  type: 'token';
  sessionId: string;
  content: string;
}

export interface ServerThinkingEvent {
  type: 'thinking';
  sessionId: string;
  content: string;
}

export interface ServerToolCallEvent {
  type: 'tool_call';
  sessionId: string;
  toolName: string;
  args: Record<string, unknown>;
  toolCallId?: string;
}

export interface ServerToolStructuredResult {
  type: 'text' | 'json' | 'image' | 'images';
  text?: string;
  data?: unknown;
  url?: string;
  mimeType?: string;
  width?: number;
  height?: number;
  bytes?: number;
  originalWidth?: number;
  originalHeight?: number;
  originalBytes?: number;
  resized?: boolean;
  images?: {
    url: string;
    mimeType?: string;
    width?: number;
    height?: number;
    seed?: number;
  }[];
}

export interface ServerToolResultEvent {
  type: 'tool_result';
  sessionId: string;
  toolName: string;
  result: string;
  rawResult?: ServerToolStructuredResult;
  toolCallId?: string;
}

export interface ServerDoneEvent {
  type: 'done';
  sessionId: string;
  usage?: { inputTokens: number; outputTokens: number };
  thinkingCapability?: {
    supported: boolean;
    adaptive: boolean;
    levels: string[];
    defaultLevel: string;
  };
}

export interface ServerErrorEvent {
  type: 'error';
  sessionId: string;
  message: string;
}

export interface ServerPongEvent {
  type: 'pong';
}

export interface ServerSkillStartEvent {
  type: 'skill_start';
  sessionId: string;
  name: string;
  label: string;
}

export interface ServerSkillEndEvent {
  type: 'skill_end';
  sessionId: string;
  name: string;
  status: string;
  result?: any;
  tokens?: any;
}

export interface ServerProgressEvent {
  type: 'progress';
  sessionId: string;
  name: string;
  step?: string;
  detail?: string;
  percent?: number;
}

export interface ServerTokenUpdateEvent {
  type: 'token_update';
  sessionId: string;
  data: {
    current: { inputTokens: number; outputTokens: number; totalTokens: number; apiCalls: number };
    context: { usedTokens: number; maxTokens: number; percent: number; thresholdPercent?: number; estimated?: boolean };
  };
}

export interface ServerThinkingDeltaEvent {
  type: 'thinking_delta';
  sessionId: string;
  data: { text: string };
}

export interface ServerThinkingDoneEvent {
  type: 'thinking_done';
  sessionId: string;
  data: Record<string, never>;
}

export interface ServerTodoUpdateEvent {
  type: 'todo_update';
  sessionId: string;
  data: { todos: any[]; summary: any };
}

export interface ServerClarifyRequestEvent {
  type: 'clarify_request';
  sessionId: string;
  data: { requestId: string; question: string; choices?: string[] };
}

export interface ServerToolConfirmationRequestEvent {
  type: 'tool_confirmation_request';
  sessionId: string;
  data: {
    requestId: string;
    toolName: string;
    toolLabel: string;
    args: Record<string, unknown>;
    riskReason: string;
  };
}

export interface ServerCompactionStartEvent {
  type: 'compaction_start';
  sessionId: string;
  data: {
    reason: 'manual' | 'auto';
    messageCount: number;
  };
}

export interface ServerCompactionDoneEvent {
  type: 'compaction_done';
  sessionId: string;
  data: {
    success: boolean;
    compactedCount: number;
    keepRecentCount: number;
    summaryMessageId: number;
    summaryContent: string;
    tokensBefore: number;
    tokensAfter: number;
    errorMessage?: string;
  };
}

export interface ServerCompactionErrorEvent {
  type: 'compaction_error';
  sessionId: string;
  data: {
    message: string;
    retryable: boolean;
  };
}

export interface ServerSubagentBatchStartEvent {
  type: 'subagent_run_started';
  sessionId: string;
  parentMessageId: number;
  data: {
    batchId: string;
    mode: 'single' | 'parallel';
    tasks: unknown[];
    toolRuntimeRoutes?: Array<{
      name: string;
      workerRoutingHint?: 'local' | 'main-process-proxy' | 'disabled';
      supportedInWorker?: boolean;
      executionMode?: string;
      runtimeRoute?: 'worker-local' | 'main-process-proxy' | 'disabled';
    }>;
  };
}

export interface ServerSubagentUpdateEvent {
  type: 'subagent_event';
  sessionId: string;
  parentMessageId: number;
  data: {
    batchId: string;
    sequence: number;
    timestamp: string;
    event: {
      kind: 'progress' | 'result' | 'status';
      status: 'in_flight' | 'completed' | 'failed';
      subagent: Record<string, unknown>;
    };
  };
}

export interface ServerSubagentDoneEvent {
  type: 'subagent_run_completed';
  sessionId: string;
  parentMessageId: number;
  data: {
    batchId: string;
    results: Record<string, unknown>[];
  };
}

export interface ServerSessionEntryAddedEvent {
  type: 'session_entry_added';
  sessionId: string;
  data: {
    entry: SessionTreeEntry;
    session?: SessionTreeSession;
  };
}

export interface ServerSessionEntryUpdatedEvent {
  type: 'session_entry_updated';
  sessionId: string;
  data: {
    entry: SessionTreeEntry;
    session?: SessionTreeSession;
  };
}

export interface ServerSessionLeafChangedEvent {
  type: 'session_leaf_changed';
  sessionId: string;
  data: {
    leafEntryId: string | null;
    session?: SessionTreeSession;
  };
}

export interface ServerAssistantStreamStartEvent {
  type: 'assistant_stream_start';
  sessionId: string;
  data: {
    assistantEntryId: string;
  };
}

export interface ServerAssistantStreamDeltaEvent {
  type: 'assistant_stream_delta';
  sessionId: string;
  data: {
    assistantEntryId?: string;
    text: string;
  };
}

export interface ServerAssistantStreamEndEvent {
  type: 'assistant_stream_end';
  sessionId: string;
  data: {
    assistantEntryId: string;
  };
}

export interface ServerToolCallStartedEvent {
  type: 'tool_call_started';
  sessionId: string;
  data: {
    toolCallId: string;
    assistantEntryId?: string;
    toolName: string;
    toolLabel?: string;
    args: Record<string, unknown>;
    status: 'running';
    runtimeRoute?: 'worker-local' | 'main-process-proxy' | 'disabled';
    workerRoutingHint?: 'local' | 'main-process-proxy' | 'disabled';
    blockedReason?: string | null;
    policySources?: string[];
  };
}

export interface ServerToolCallCompletedEvent {
  type: 'tool_call_completed';
  sessionId: string;
  data: {
    toolCallId: string;
      assistantEntryId?: string;
      toolName: string;
      toolLabel?: string;
      result: string;
      rawResult?: ServerToolStructuredResult;
      status: 'done' | 'error';
      runtimeRoute?: 'worker-local' | 'main-process-proxy' | 'disabled';
      workerRoutingHint?: 'local' | 'main-process-proxy' | 'disabled';
      blockedReason?: string | null;
      policySources?: string[];
    };
  }

export interface ServerToolResultStreamedEvent {
  type: 'tool_result_streamed';
  sessionId: string;
  data: {
    toolCallId: string;
      assistantEntryId?: string;
      toolName: string;
      toolLabel?: string;
      result: string;
      rawResult?: ServerToolStructuredResult;
      runtimeRoute?: 'worker-local' | 'main-process-proxy' | 'disabled';
      workerRoutingHint?: 'local' | 'main-process-proxy' | 'disabled';
      blockedReason?: string | null;
      policySources?: string[];
    };
  }

export interface ServerToolProcessEvent {
  type: 'tool_process_event';
  sessionId: string;
  data: {
    version: 1;
    operationId: string;
    parentOperationId?: string;
    targetType: 'tool' | 'skill' | 'subagent' | 'task' | 'runtime';
    toolCallId: string;
    assistantEntryId?: string;
    toolName: string;
    toolLabel?: string;
    source: 'skill' | 'tool' | 'subagent' | 'runtime';
    taskId?: string;
    stage?: string;
    status: 'queued' | 'started' | 'running' | 'completed' | 'failed' | 'cancelled' | 'skipped';
    level?: 'debug' | 'info' | 'warning' | 'error';
    message: string;
    detail?: string;
    current?: number;
    total?: number;
    percent?: number;
    payload?: Record<string, unknown>;
    timestamp: string;
    sequence: number;
  };
}

export type ServerEvent =
  | ServerTokenEvent
  | ServerThinkingEvent
  | ServerToolCallEvent
  | ServerToolResultEvent
  | ServerSkillStartEvent
  | ServerSkillEndEvent
  | ServerProgressEvent
  | ServerTokenUpdateEvent
  | ServerThinkingDeltaEvent
  | ServerThinkingDoneEvent
  | ServerTodoUpdateEvent
  | ServerClarifyRequestEvent
  | ServerToolConfirmationRequestEvent
  | ServerCompactionStartEvent
  | ServerCompactionDoneEvent
  | ServerCompactionErrorEvent
  | ServerSubagentBatchStartEvent
  | ServerSubagentUpdateEvent
  | ServerSubagentDoneEvent
  | ServerSessionEntryAddedEvent
  | ServerSessionEntryUpdatedEvent
  | ServerSessionLeafChangedEvent
  | ServerAssistantStreamStartEvent
  | ServerAssistantStreamDeltaEvent
  | ServerAssistantStreamEndEvent
  | ServerToolCallStartedEvent
  | ServerToolCallCompletedEvent
  | ServerToolResultStreamedEvent
  | ServerToolProcessEvent
  | ServerDoneEvent
  | ServerErrorEvent
  | ServerPongEvent;
import type { SessionTreeEntry, SessionTreeSession } from '../session-tree/types.js';
