import { toolBlockedReasonLabel, toolRuntimeRouteLabel, toolWorkerRoutingHintLabel } from '../tools/runtime-policy';
import type {
	SessionTreeEntry,
	SessionTreeSubagentBatchContent,
	SessionTreeSubagentResultContent,
	SubagentProcessEvent,
	SubagentTaskPanel,
	SubagentToolExecution,
	ToolRuntimeRouteProjection,
} from '../types/index.d';
import { formatDuration, formatTimestamp, stringifyContent } from './chat-display';

export function subagentBatchContent(entry: SessionTreeEntry): SessionTreeSubagentBatchContent {
	return (entry.content || {}) as SessionTreeSubagentBatchContent;
}

export function subagentResultContent(entry: SessionTreeEntry): SessionTreeSubagentResultContent {
	return (entry.content || {}) as SessionTreeSubagentResultContent;
}

export function subagentBatchHeadline(entry: SessionTreeEntry) {
	const content = subagentBatchContent(entry);
	return `${content.mode === 'parallel' ? 'Parallel' : 'Single'} run`;
}

export function subagentResultBatchLabel(entry: SessionTreeEntry) {
	if (entry.type !== 'subagent_result') return '';
	const batchId = subagentResultContent(entry).batchId;
	return typeof batchId === 'string' && batchId.trim() ? batchId.slice(0, 8) : '';
}

export function taskPanelScopeKey(entryId: string, panel: SubagentTaskPanel) {
	return `${entryId}:${panel.key}`;
}

export function hasMoreTaskEvidenceSummaries(panel: SubagentTaskPanel) {
	return panel.evidenceSummaries.length > 4;
}

export function hasMoreTaskProcessEvents(panel: SubagentTaskPanel) {
	return panel.processEvents.length > 6;
}

export function subagentToolExecutionLabel(execution: SubagentToolExecution) {
	return execution.label || execution.name || '工具';
}

export function subagentToolExecutionCountLabel(panel: SubagentTaskPanel) {
	const count = `${panel.toolExecutions.length} 次`;
	return panel.toolExecutionsTruncated ? `前 ${count}` : count;
}

export function subagentToolExecutionMeta(execution: SubagentToolExecution) {
	const items: string[] = [];
	const duration = formatDuration(execution.startedAt, execution.finishedAt);
	if (duration) {
		items.push(duration);
	}
	if (execution.finishedAt) {
		items.push(`结束 ${formatTimestamp(execution.finishedAt)}`);
	} else if (execution.startedAt) {
		items.push(`开始 ${formatTimestamp(execution.startedAt)}`);
	}
	if (execution.toolCallId) {
		items.push(execution.toolCallId);
	}
	return items;
}

export function getToolExecutionBlockText(execution: SubagentToolExecution, kind: 'args' | 'result' | 'error') {
	if (kind === 'error') {
		return typeof execution.error === 'string' ? execution.error.trim() : '';
	}
	const payload = kind === 'args' ? execution.args : execution.result;
	if (payload == null) return '';
	return typeof payload === 'string' ? payload.trim() : stringifyContent(payload).trim();
}

export function hasLongToolExecutionBlock(execution: SubagentToolExecution, kind: 'args' | 'result' | 'error') {
	return getToolExecutionBlockText(execution, kind).length > 280;
}

export function hasProcessEventLongPayload(event: SubagentProcessEvent) {
	return processEventPayloadPreview(event).length > 280;
}

export function evidenceKindLabel(kind?: string) {
	if (kind === 'file-count') return '文件统计';
	if (kind === 'tool-preview') return '工具证据';
	return '证据摘要';
}

export function processEventLabel(event: SubagentProcessEvent) {
	switch (event.type) {
		case 'run_start':
			return '启动';
		case 'tool_call':
			return `调用 ${event.label || event.name || '工具'}`;
		case 'tool_result':
			return `结果 ${event.label || event.name || '工具'}`;
		case 'proxy_tool_call':
			return `代理调用 ${event.label || event.name || '工具'}`;
		case 'run_end':
			return '完成';
		case 'run_error':
			return '失败';
		case 'thinking':
			return '思考';
		case 'token':
			return '输出';
		default:
			return event.type || '事件';
	}
}

export function processEventDetail(event: SubagentProcessEvent) {
	if (typeof event.error === 'string' && event.error.trim()) return event.error;
	if (typeof event.text === 'string' && event.text.trim()) return event.text.slice(0, 180);
	if (typeof event.result === 'string' && event.result.trim()) return event.result.replace(/\s+/g, ' ').slice(0, 180);
	if (typeof event.toolCallId === 'string' && event.toolCallId.trim()) return event.toolCallId;
	if (typeof event.timestamp === 'string' && event.timestamp.trim()) return formatTimestamp(event.timestamp);
	return stringifyContent(event).replace(/\s+/g, ' ').slice(0, 180);
}

export function processEventPayloadPreview(event: SubagentProcessEvent) {
	const payload = event.type === 'tool_call' || event.type === 'proxy_tool_call'
		? event.args
		: event.type === 'tool_result'
			? event.result
			: event.type === 'run_error'
				? { error: event.error }
				: null;
	if (payload == null) return '';
	const text = typeof payload === 'string' ? payload : stringifyContent(payload);
	return text.trim();
}

export function subagentStatusLabel(status?: string) {
	return status === 'completed' ? '已完成' : '运行中';
}

export function subagentEventLabel(kind: 'started' | 'event' | 'completed') {
	switch (kind) {
		case 'started':
			return '已启动';
		case 'completed':
			return '已完成';
		default:
			return '事件';
	}
}

export function runtimeRouteLabel(route?: ToolRuntimeRouteProjection['runtimeRoute']) {
	return toolRuntimeRouteLabel(route);
}

export function workerRoutingHintLabel(hint?: ToolRuntimeRouteProjection['workerRoutingHint']) {
	return toolWorkerRoutingHintLabel(hint);
}

export function blockedReasonLabel(reason?: string | null) {
	return toolBlockedReasonLabel(reason);
}
