import { describeEntryDisplay } from '../store/subagent_projection';
import type { ChatMessage, SessionTreeEntry } from '../types/index.d';

export function stringifyContent(content: unknown) {
	if (typeof content === 'string') return content;
	if (content == null) return '';
	try {
		return JSON.stringify(content, null, 2);
	} catch {
		return String(content);
	}
}

export function entryKindLabel(entry: SessionTreeEntry) {
	if (entry.type === 'message') {
		switch (entry.message?.role) {
			case 'user':
				return '用户';
			case 'assistant':
				return '助手';
			case 'system':
				return '系统';
			case 'tool':
				return '工具';
			default:
				return '消息';
		}
	}

	switch (entry.type) {
		case 'branch_summary':
			return '分支';
		case 'compaction':
			return '压缩';
		case 'subagent_batch':
			return '批次';
		case 'subagent_result':
			return '结果';
		case 'custom_message':
			return '自定义';
		default:
			return entry.type;
	}
}

export function entryTitle(entry: SessionTreeEntry) {
	return describeEntryDisplay(entry);
}

export function truncateSingleLine(value: string | null | undefined, max = 80) {
	if (!value) return '';
	const normalized = value.replace(/\s+/g, ' ').trim();
	if (normalized.length <= max) return normalized;
	return `${normalized.slice(0, Math.max(0, max - 1))}…`;
}

export function formatTimestamp(timestamp?: string) {
	if (!timestamp) return '';
	const date = new Date(timestamp);
	if (Number.isNaN(date.getTime())) return timestamp;
	return date.toLocaleString('zh-CN', {
		month: '2-digit',
		day: '2-digit',
		hour: '2-digit',
		minute: '2-digit',
	});
}

export function formatDuration(startedAt?: string, finishedAt?: string) {
	if (!startedAt || !finishedAt) return '';
	const start = new Date(startedAt).getTime();
	const end = new Date(finishedAt).getTime();
	if (Number.isNaN(start) || Number.isNaN(end) || end < start) return '';
	const durationMs = end - start;
	if (durationMs < 1000) return `${durationMs}ms`;
	const seconds = durationMs / 1000;
	if (seconds < 60) return `${seconds.toFixed(seconds < 10 ? 1 : 0)}s`;
	const minutes = Math.floor(seconds / 60);
	const remainSeconds = Math.round(seconds % 60);
	return `${minutes}m ${remainSeconds}s`;
}

export function toChatMessage(entry: SessionTreeEntry): ChatMessage {
	const rawContent = stringifyContent(entry.message?.content);
	let thinking = entry.message?.thinking || '';
	let content = rawContent;

	if (!thinking && rawContent) {
		const match = rawContent.match(/<think>([\s\S]*?)<\/think>/i);
		if (match) {
			thinking = match[1]?.trim() || '';
			content = rawContent.replace(match[0], '').trim();
		}
	}

	return {
		role: (entry.message?.role as ChatMessage['role']) || 'assistant',
		content,
		thinking: thinking || undefined,
		createTime: formatTimestamp(entry.timestamp),
		metadata: entry.message?.metadata,
	};
}
