// packages/frontend/src/modules/agent/types/protocol.ts
// 前端与后端 WebSocket 通信协议类型定义，需与后端保持同步

/** 客户端 -> 服务端：聊天消息 */
export interface ClientChatMessage {
  type: 'chat';
  sessionId: string;
  content: string;
  agentName?: string;
  agentId?: number;
}

/** 客户端 -> 服务端：心跳 */
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 ClientCompactMessage {
  type: 'compact';
  sessionId: string;
  instructions?: string;
}

/** 客户端消息联合类型 */
export type ClientMessage =
  | ClientChatMessage
  | ClientPingMessage
  | ClientSetThinkingLevelMessage
  | ClientClarifyResponseMessage
  | ClientCompactMessage;

// 服务端 token_update 事件（含压缩阈值）
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 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 };
}

/** 压缩状态（store 中维护） */
export interface CompactionState {
  inFlight: boolean;
  lastResult?: ServerCompactionDoneEvent['data'];
  lastError?: string;
}
