/**
 * Token 使用量汇总
 */
export interface TokenUsageSummary {
	supervisor: { input: number; output: number; thinking: number; total: number };
	selector: { input: number; output: number; total: number };
	skills: Record<string, { input: number; output: number; total: number; apiCalls: number }>;
	total: { input: number; output: number; total: number; apiCalls: number };
	/** Supervisor 最新一次 LLM 调用的 input_tokens，即当前上下文窗口占用量 */
	contextTokens: number;
	/** 是否包含估算值 */
	estimated: boolean;
}

/**
 * Agent 消息类型
 */
export interface ChatMessage {
	id?: number;
	sessionId?: string;
	role: 'user' | 'assistant' | 'tool' | 'system' | 'clarify' | 'compaction';
	content: string;
	/** LLM 思考内容（流式累积） */
	thinking?: string;
	skillName?: string;
	toolCalls?: any;
	metadata?: any;
	createTime?: string;
	// === 压缩气泡专用字段（role='compaction' 时使用） ===
	status?: 'running' | 'done' | 'error';
	reason?: 'manual' | 'auto';
	messageCount?: number;
	compactedCount?: number;
	keepRecentCount?: number;
	tokensBefore?: number;
	tokensAfter?: number;
	errorMessage?: string;
	summaryContent?: string;
}

export interface SubagentTaskDescriptor {
	goal?: string;
	context?: string;
	mode?: string;
	agentName?: string | null;
	agentId?: number | null;
	toolNames?: string[];
	[key: string]: any;
}

export interface SubagentRecord {
	id?: number;
	sortOrder?: number;
	name?: string | null;
	goal?: string | null;
	status?: 'running' | 'completed' | 'failed' | string;
	summary?: string | null;
	error?: string | null;
	[key: string]: any;
}

export interface SubagentBatch {
	batchId: string;
	sessionId: string;
	parentMessageId: number;
	mode: 'single' | 'parallel';
	tasks: SubagentTaskDescriptor[];
	status: 'running' | 'completed';
	results: SubagentRecord[];
}

export interface SessionTreeSubagentBatchContent {
	batchId: string;
	mode: 'single' | 'parallel';
	tasks: Record<string, unknown>[];
	status: 'running' | 'completed';
	parentEntryId?: string | null;
}

export interface SessionTreeSubagentResultContent {
	batchId: string;
	results: Record<string, unknown>[];
	status: 'running' | 'completed';
	parentEntryId?: string | null;
}

export interface SubagentBatchEventProjection {
	sequence?: number;
	timestamp?: string;
	event?: Record<string, unknown>;
	[key: string]: unknown;
}

export interface SubagentRuntimeEvent {
	timestamp: number;
	kind: 'started' | 'event' | 'completed';
	sequence?: number;
	status?: 'in_flight' | 'completed' | 'failed';
	payload: Record<string, unknown>;
}

export interface SubagentRuntimeState {
	batchId: string;
	status: 'running' | 'completed';
	mode?: 'single' | 'parallel';
	tasks: Record<string, unknown>[];
	results: Record<string, unknown>[];
	events: SubagentRuntimeEvent[];
}

/**
 * Agent 会话
 */
export interface AgentSession {
	id?: number;
	sessionId: string;
	agentId?: number | null;
	title: string;
	status: number;
	metadata?: any;
	hasCompactedView?: boolean;
	todoSummary?: TodoSummary | null;
	lastMessage?: string;
	isRunning?: boolean;
	createTime?: string;
	updateTime?: string;
}

export type SessionTreeEntryType =
	| 'message'
	| 'thinking_level_change'
	| 'model_change'
	| 'compaction'
	| 'branch_summary'
	| 'custom'
	| 'custom_message'
	| 'label'
	| 'session_info'
	| 'subagent_batch'
	| 'subagent_result';

export interface SessionTreeMessagePayload {
	role: 'system' | 'user' | 'assistant' | 'tool';
	content: any;
	thinking?: string;
	model?: string;
	usage?: Record<string, unknown>;
	metadata?: Record<string, unknown>;
	toolCalls?: unknown;
	toolCallId?: string;
	[key: string]: any;
}

export interface SessionTreeEntry {
	id: string;
	parentId: string | null;
	timestamp: string;
	type: SessionTreeEntryType;
	message?: SessionTreeMessagePayload;
	thinkingLevel?: string;
	provider?: string;
	modelId?: string;
	summary?: string;
	fromId?: string;
	firstKeptEntryId?: string;
	tokensBefore?: number;
	customType?: string;
	content?: any;
	data?: Record<string, unknown>;
	display?: boolean;
	targetId?: string;
	label?: string;
	name?: string;
	metadata?: SessionTreeEntryMetadata;
}

export interface SubagentEvidenceSummary {
	kind: 'file-count' | 'tool-preview';
	title: string;
	summary: string;
	files?: string[];
	count?: number;
	previews?: string[];
}

export interface SubagentProcessEvent {
	type: string;
	runId?: string;
	timestamp?: string;
	name?: string;
	label?: string;
	toolCallId?: string;
	error?: string;
	result?: unknown;
	args?: unknown;
	text?: string;
	[key: string]: unknown;
}

export interface SubagentTaskPanel {
	key: string;
	title: string;
	status?: string;
	sortOrder?: number;
	runId?: string;
	summary?: string;
	error?: string;
	evidenceSummaries: SubagentEvidenceSummary[];
	processEvents: SubagentProcessEvent[];
	toolExecutions: SubagentToolExecution[];
	toolExecutionsTruncated?: boolean;
	result?: Record<string, unknown>;
}

export interface SubagentProjectionDiagnostics {
	selectedSource: 'subagent_result' | 'tool_message' | 'message_metadata' | 'entry_metadata';
	inputSources: Array<'subagent_result' | 'tool_message' | 'message_metadata' | 'entry_metadata'>;
	ignoredSources: Array<'subagent_result' | 'tool_message' | 'message_metadata' | 'entry_metadata'>;
	rawResultCount: number;
	dedupedResultCount: number;
	projectedTaskCount: number;
	skippedResultCount: number;
	fallbackUsed: boolean;
	projectionPath?: 'canonical-backend-projection' | 'metadata-only-fallback' | 'legacy-payload-fallback';
}

export interface SessionTreeSubagentBatchMetadata extends Record<string, unknown> {
	latestEvent?: SubagentBatchEventProjection;
	events?: SubagentBatchEventProjection[];
	processEvents?: SubagentProcessEvent[];
	finalResults?: Record<string, unknown>[];
	evidenceSummaries?: SubagentEvidenceSummary[];
	toolRuntimeRoutes?: ToolRuntimeRouteProjection[];
}

export interface SessionTreeSubagentResultMetadata extends Record<string, unknown> {
	finalResults?: Record<string, unknown>[];
	processEvents?: SubagentProcessEvent[];
	evidenceSummaries?: SubagentEvidenceSummary[];
}

export interface SubagentEntryProjection {
	version: 1;
	source: 'backend-projection';
	replay: {
		limits: {
			evidenceSummaries: number;
			processEvents: number;
			taskProcessEvents: number;
			toolExecutions: number;
		};
		truncated: {
			evidenceSummaries: boolean;
			processEvents: boolean;
			taskPanels: boolean;
			toolExecutions: boolean;
		};
	};
	evidenceSummaries: SubagentEvidenceSummary[];
	processEvents: SubagentProcessEvent[];
	taskPanels: SubagentTaskPanel[];
	diagnostics: SubagentProjectionDiagnostics;
}

export interface SessionTreeEntryMetadata extends Record<string, unknown> {
	subagentProjection?: SubagentEntryProjection;
	latestEvent?: SubagentBatchEventProjection;
	events?: SubagentBatchEventProjection[];
	processEvents?: SubagentProcessEvent[];
	finalResults?: Record<string, unknown>[];
	evidenceSummaries?: SubagentEvidenceSummary[];
	toolRuntimeRoutes?: ToolRuntimeRouteProjection[];
	skillExecutions?: unknown[];
}

export interface SubagentToolExecution {
	key: string;
	toolCallId?: string;
	name?: string;
	label?: string;
	kind: 'tool_call' | 'proxy_tool_call';
	status: 'running' | 'completed';
	args?: unknown;
	result?: unknown;
	error?: string;
	runId?: string;
	startedAt?: string;
	finishedAt?: string;
}

export interface SessionTreeLabelState {
	label: string;
	timestamp: string;
	entryId: string;
}

export interface SessionTreeSessionMeta {
	sessionId: string;
	provider: 'file' | 'mysql';
	rootEntryId: string | null;
	leafEntryId: string | null;
	cwd?: string;
	sessionFile?: string;
	parentSessionId?: string;
	agentId?: number | string | null;
	userId?: number | string | null;
	title?: string;
	status?: string;
	metadata?: Record<string, unknown>;
	createdAt?: string;
	updatedAt?: string;
}

export interface SessionTreeRuntimeMessage {
	role: 'system' | 'user' | 'assistant' | 'tool' | 'custom' | 'branchSummary' | 'compactionSummary';
	content?: any;
	summary?: string;
	customType?: string;
	timestamp?: number;
	[key: string]: any;
}

export interface SessionTreeSnapshot {
	session: SessionTreeSessionMeta;
	entries: SessionTreeEntry[];
	activePath: SessionTreeEntry[];
	childrenByParentId: Record<string, string[]>;
	labelsByEntryId: Record<string, SessionTreeLabelState>;
	runtimeContext: {
		messages: SessionTreeRuntimeMessage[];
		thinkingLevel: string;
		model: { provider: string; modelId: string } | null;
	};
	session?: {
		backend?: 'file' | 'mysql';
		cwd?: string;
		file?: {
			rootDir?: string;
		};
	};
	memory?: {
		enabled?: boolean;
		backend?: 'mysql' | 'sqlite';
		sqlitePath?: string;
		prefetchLimit?: number;
	};
	session?: {
		backend?: 'file' | 'mysql';
		cwd?: string;
		restoreLastSession?: boolean;
		file?: {
			rootDir?: string;
		};
	};
	memory?: {
		enabled?: boolean;
		backend?: 'mysql' | 'sqlite';
		sqlitePath?: string;
		prefetchLimit?: number;
	};
}

export interface StreamingToolProjection {
	toolCallId: string;
	assistantEntryId?: string;
	toolName: string;
	label?: string;
	args?: Record<string, unknown>;
	result?: string;
	runtimeRoute?: 'worker-local' | 'main-process-proxy' | 'disabled';
	workerRoutingHint?: 'local' | 'main-process-proxy' | 'disabled';
	blockedReason?: string | null;
	policySources?: string[];
	latestProcessEvent?: RuntimeProcessEventProjection;
	processEvents?: RuntimeProcessEventProjection[];
	processLogRef?: RuntimeProcessLogRef;
	rawResult?: {
		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;
			label?: string;
			purpose?: string;
			reason?: string;
			damageId?: string;
			timestamp?: number;
			width?: number;
			height?: number;
			seed?: number;
		}[];
	};
	status: 'running' | 'done' | 'error';
}

export interface RuntimeProcessLogRef {
	kind: 'runtime_process_log';
	sessionId: string;
	operationId: string;
	toolCallId?: string;
}

export interface RuntimeProcessEventProjection {
	version: 1;
	operationId: string;
	parentOperationId?: string;
	targetType: 'tool' | 'skill' | 'subagent' | 'task' | 'runtime';
	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 interface ToolRuntimeRouteProjection {
	name: string;
	kind?: 'builtin' | 'memory' | 'skill' | 'delegation' | 'admin' | 'custom';
	executionMode?: 'parallel' | 'sequential';
	workerRoutingHint?: 'local' | 'main-process-proxy' | 'disabled';
	supportedInWorker?: boolean;
	runtimeRoute?: 'worker-local' | 'main-process-proxy' | 'disabled';
	blockedReason?: string | null;
	policySources?: string[];
	policyDerived?: boolean;
}

/**
 * Skill 元数据
 */
export interface SkillMeta {
	name: string;
	label: string;
	description: string;
	category: string;
	/** Skill类型: compute=纯计算 llm=需要LLM multimodal=需要多模态LLM */
	skillType?: 'compute' | 'llm' | 'multimodal';
	/** Skill分类: compute-entry=计算入口 compute-toolkit=计算工具集 prompt=提示词技能 */
	classification?: 'compute-entry' | 'compute-toolkit' | 'prompt';
	icon?: string;
	version: string;
	inputSchema: any;
	outputSchema: any;
	status?: number;
	/** 标签（如 ['并发']） */
	tags?: string[];
}

/**
 * Agent 高级配置
 */
export interface AgentConfig {
	/** 欢迎语 */
	welcomeMessage?: string;
	/** Middleware 配置 */
	middleware?: {
		/** Tool 重试最大次数，默认 2 */
		toolRetryMaxRetries?: number;
		/** Tool 调用总次数限制，默认 20 */
		maxToolCalls?: number;
		/** 模型重试最大次数，默认 2 */
		modelRetryMaxRetries?: number;
	};
}

export interface AgentToolConfig {
	inheritCoreTools?: boolean;
	enabled?: string[];
	disabled?: string[];
	perTool?: Record<string, {
		enabled?: boolean;
		promptHint?: string;
		allowInSubagent?: boolean;
		workerRoutingStrategy?: 'auto' | 'force-local' | 'force-main-process-proxy' | 'force-disabled';
	}>;
}

export interface AgentSubagentConfig {
	enabled?: boolean;
	maxConcurrent?: number;
	allowedPresetAgentIds?: number[];
	allowedToolNames?: string[];
}

/**
 * Agent 信息
 */
export interface AgentInfo {
	id?: number;
	name: string;
	label: string;
	description?: string;
	icon?: string;
	systemPrompt?: string;
	skills?: string[];
	toolsets?: string[];
	tools?: AgentToolConfig;
	subagentConfig?: AgentSubagentConfig;
	modelConfig?: { apiKey?: string; apiUrl?: string; modelId?: string; contextWindow?: number };
	config?: AgentConfig;
	status: number;
	createTime?: string;
	updateTime?: string;
}

export interface AgentChannelInfo {
	id?: number;
	name: string;
	type: 'weixin' | 'weixin-db';
	agentId?: number | null;
	agentName?: string | null;
	description?: string;
	config?: Record<string, any>;
	credential?: Record<string, any> | null;
	runtime?: Record<string, any>;
	loginStatus?: 'pending' | 'connected' | 'disconnected' | 'error' | 'unsupported_platform';
	lastError?: string | null;
	lastConnectedAt?: string | null;
	status?: 0 | 1;
	createTime?: string;
	updateTime?: string;
	/** Plan C 新增 */
	groupTotal?: number;
	groupEnabled?: number;
	/** weixin-db 渠道专用字段 */
	wechatVersion?: string | null;
	wxid?: string | null;
}

export interface AgentGroupItem {
	id: number;
	channelId: number;
	roomId: string;
	roomName: string | null;
	status: 0 | 1;
	triggerMode: 'at_mention' | 'all';
	triggerPrefix: string | null;
	/** 每群独立绑定的 agentId；null 表示历史数据未配置 */
	boundAgentId: number | null;
	/** 每群独立的回复身份；null 表示历史数据未配置 */
	replyIdentityOverride: 'silent' | 'ai_prefix' | null;
	firstSeenAt: string | null;
	lastSeenAt: string | null;
	lastActiveAt: string | null;
}

/**
 * SSE 事件
 */
export interface SSEEvent {
	type: 'token' | 'thinking' | 'skill_start' | 'skill_end' | 'progress' | 'token_update' | 'error' | 'done' | 'snapshot';
	data: any;
}

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

/**
 * WebSocket 客户端消息
 */
export interface WSClientMessage {
	type: 'chat' | 'ping' | 'clarify_response';
	sessionId?: string;
	content?: string;
	agentId?: number;
	leafEntryId?: string | null;
	requestId?: string;
	answer?: string;
	attachments?: ChatAttachment[];
}

/**
 * WebSocket 服务端事件
 */
export interface WSServerEvent {
	type: 'token' | 'thinking' | 'tool_call' | 'tool_result' | 'tool_process_event' | 'tool_call_started' | 'tool_call_completed' | 'tool_result_streamed' | 'skill_start' | 'skill_end' | 'progress' | 'token_update' | 'done' | 'error' | 'pong' | 'todo_update' | 'thinking_delta' | 'thinking_done' | 'clarify_request' | 'compaction_start' | 'compaction_done' | 'compaction_error' | 'subagent_run_started' | 'subagent_event' | 'subagent_run_completed' | 'session_entry_added' | 'session_entry_updated' | 'session_leaf_changed' | 'assistant_stream_start' | 'assistant_stream_delta' | 'assistant_stream_end';
	sessionId?: string;
	toolLabel?: string;
	[key: string]: any;
}

/**
 * 重连快照数据
 */
export interface ReconnectSnapshot {
	content: string;
	thinking: string;
	skillProgress: SkillProgress[];
	tokenUsage: any;
}

/**
 * 执行状态查询结果
 */
export interface ExecutionStatus {
	status: 'idle' | 'running' | 'done' | 'error';
	partialContent?: string;
	skillProgress?: SkillProgress[];
}

/**
 * Skill 执行状态
 */
export interface SkillProgress {
	name: string;
	label?: string;
	status: 'running' | 'done' | 'error';
	/** 来源类型：skill=Skill技能, tool=普通工具调用 */
	source?: 'skill' | 'tool';
	input?: any;
	result?: any;
	/** 当前步骤描述 */
	step?: string;
	/** 进度百分比 (0-100) */
	percent?: number;
	/** 详细信息 */
	detail?: string;
	/** 当前处理序号 */
	current?: number;
	/** 总数 */
	total?: number;
	/** workspace taskId */
	taskId?: string;
	/** 图片相对路径列表 */
	images?: string[];
	/** Skill 消耗的 token */
	tokens?: { input: number; output: number; total: number; apiCalls?: number };
}

/**
 * 语音对话消息
 */
export interface VoiceMessage {
	id: string;
	role: 'user' | 'assistant';
	text: string;
	/** ASR 中间结果（非最终） */
	isPartial?: boolean;
	timestamp: number;
}

// === Todo 系统类型 ===
export interface TodoItem {
	id: string;
	content: string;
	status: 'pending' | 'in_progress' | 'completed' | 'cancelled';
}

export interface TodoSummary {
	total: number;
	pending: number;
	in_progress: number;
	completed: number;
	cancelled: number;
}

// === 思考级别类型 ===
export type ThinkLevel = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'adaptive';

export interface ModelThinkingCapability {
	supported: boolean;
	adaptive: boolean;
	levels: ThinkLevel[];
	defaultLevel: ThinkLevel;
}

// === Token 统计类型 ===
export interface TokenUpdateEvent {
	current: {
		inputTokens: number;
		outputTokens: number;
		totalTokens: number;
		apiCalls: number;
	};
	context: {
		usedTokens: number;
		maxTokens: number;
		percent: number;
		thresholdPercent?: number;
		estimated?: boolean;
	};
}

// === Clarify 工具类型 ===
export interface ClarifyRequestData {
	requestId: string;
	question: string;
	choices?: string[];
}

export interface ClarifyMessageMeta {
	requestId: string;
	choices?: string[];
	status: 'pending' | 'answered';
	answer?: string;
}
