import type { Ref } from 'vue';
import { describeSubagentProjectionDiagnostics } from '../store/subagent_projection';
import type {
	SessionTreeEntry,
	SubagentEvidenceSummary,
	SubagentProcessEvent,
	SubagentProjectionDiagnostics,
	SubagentRuntimeState,
	SubagentTaskPanel,
	ToolRuntimeRouteProjection,
} from '../types/index.d';
import { stringifyContent } from '../utils/chat-display';
import { runtimeRouteLabel, subagentBatchContent, subagentResultContent } from '../utils/chat-subagent-display';

type SubagentEntryDisplayRefs = {
	subagentRuntimeByBatchId: Ref<Record<string, SubagentRuntimeState>>;
	toolRuntimeRoutesByBatchId: Ref<Record<string, ToolRuntimeRouteProjection[]>>;
	subagentEvidenceSummariesByEntryId: Ref<Record<string, SubagentEvidenceSummary[]>>;
	subagentProcessEventsByEntryId: Ref<Record<string, SubagentProcessEvent[]>>;
	subagentTaskPanelsByEntryId: Ref<Record<string, SubagentTaskPanel[]>>;
	subagentProjectionDiagnosticsByEntryId: Ref<Record<string, SubagentProjectionDiagnostics>>;
};

export function useSubagentEntryDisplay(
	refs: SubagentEntryDisplayRefs,
	expansion: {
		isSubagentEvidenceExpanded: (entryId: string) => boolean;
		isSubagentProcessExpanded: (entryId: string) => boolean;
	}
) {
	function subagentStateForEntry(entry: SessionTreeEntry): SubagentRuntimeState | null {
		const batchId = entry.type === 'subagent_batch'
			? subagentBatchContent(entry).batchId
			: entry.type === 'subagent_result'
				? subagentResultContent(entry).batchId
				: '';
		return batchId ? refs.subagentRuntimeByBatchId.value[batchId] || null : null;
	}

	function subagentTaskPanels(entry: SessionTreeEntry): SubagentTaskPanel[] {
		return refs.subagentTaskPanelsByEntryId.value[entry.id] || [];
	}

	function isDelegatedToolResultEntry(entry: SessionTreeEntry) {
		return entry.type === 'message'
			&& Boolean(entry.message)
			&& (refs.subagentTaskPanelsByEntryId.value[entry.id]?.length || 0) > 0;
	}

	function subagentTaskCount(entry: SessionTreeEntry) {
		return subagentStateForEntry(entry)?.tasks.length || subagentBatchContent(entry).tasks?.length || 0;
	}

	function subagentResultCount(entry: SessionTreeEntry) {
		if (isDelegatedToolResultEntry(entry)) {
			return subagentTaskPanels(entry).length;
		}
		return subagentStateForEntry(entry)?.results.length || subagentResultContent(entry).results?.length || 0;
	}

	function subagentResultHeadline(entry: SessionTreeEntry) {
		const count = subagentResultCount(entry);
		return count > 0 ? `${count} result${count > 1 ? 's' : ''}` : 'Result summary';
	}

	function subagentTaskPreview(entry: SessionTreeEntry) {
		const tasks = subagentStateForEntry(entry)?.tasks || subagentBatchContent(entry).tasks || [];
		return tasks.slice(0, 4).map(task => {
			const label = typeof task.goal === 'string' && task.goal.trim()
				? task.goal
				: typeof task.name === 'string' && task.name.trim()
					? task.name
					: typeof task.agentName === 'string' && task.agentName.trim()
						? task.agentName
						: stringifyContent(task);
			return label.length > 160 ? `${label.slice(0, 157)}...` : label;
		});
	}

	function subagentResultPreview(entry: SessionTreeEntry) {
		if (isDelegatedToolResultEntry(entry)) {
			return subagentTaskPanels(entry).slice(0, 4).map(panel => panel.summary || panel.error || panel.title);
		}
		const results = subagentStateForEntry(entry)?.results || subagentResultContent(entry).results || [];
		return results.slice(0, 4).map(result => {
			const label = typeof result.summary === 'string' && result.summary.trim()
				? result.summary
				: typeof result.goal === 'string' && result.goal.trim()
					? result.goal
					: typeof result.error === 'string' && result.error.trim()
						? result.error
						: stringifyContent(result);
			return label.length > 160 ? `${label.slice(0, 157)}...` : label;
		});
	}

	function subagentProjectionDiagnostics(entry: SessionTreeEntry): SubagentProjectionDiagnostics | null {
		return refs.subagentProjectionDiagnosticsByEntryId.value[entry.id] || null;
	}

	function subagentProjectionDiagnosticsSummary(entry: SessionTreeEntry) {
		return describeSubagentProjectionDiagnostics(subagentProjectionDiagnostics(entry)).summary;
	}

	function subagentProjectionDiagnosticsDisplay(entry: SessionTreeEntry) {
		return describeSubagentProjectionDiagnostics(subagentProjectionDiagnostics(entry));
	}

	function subagentEvidenceSummaries(entry: SessionTreeEntry): SubagentEvidenceSummary[] {
		const summaries = refs.subagentEvidenceSummariesByEntryId.value[entry.id] || [];
		return expansion.isSubagentEvidenceExpanded(entry.id) ? summaries : summaries.slice(0, 4);
	}

	function subagentProcessEvents(entry: SessionTreeEntry): SubagentProcessEvent[] {
		return refs.subagentProcessEventsByEntryId.value[entry.id] || [];
	}

	function visibleSubagentProcessEvents(entry: SessionTreeEntry): SubagentProcessEvent[] {
		const events = subagentProcessEvents(entry);
		return expansion.isSubagentProcessExpanded(entry.id) ? events : events.slice(0, 6);
	}

	function hasMoreEvidenceSummaries(entry: SessionTreeEntry) {
		return (refs.subagentEvidenceSummariesByEntryId.value[entry.id] || []).length > 4;
	}

	function hasMoreProcessEvents(entry: SessionTreeEntry) {
		return subagentProcessEvents(entry).length > 6;
	}

	function subagentRuntimeRoutes(entry: SessionTreeEntry): ToolRuntimeRouteProjection[] {
		const batchId = entry.type === 'subagent_batch'
			? subagentBatchContent(entry).batchId
			: entry.type === 'subagent_result'
				? subagentResultContent(entry).batchId
				: '';
		return batchId ? refs.toolRuntimeRoutesByBatchId.value[batchId] || [] : [];
	}

	function subagentRuntimeRouteSummary(entry: SessionTreeEntry) {
		const routes = subagentRuntimeRoutesForRequestedTools(entry);
		if (routes.length === 0) return '';
		const counts = routes.reduce<Record<string, number>>((acc, item) => {
			const key = item.runtimeRoute || 'disabled';
			acc[key] = (acc[key] || 0) + 1;
			return acc;
		}, {});
		return Object.entries(counts)
			.map(([key, count]) => `${runtimeRouteLabel(key as ToolRuntimeRouteProjection['runtimeRoute'])} ${count}`)
			.join(' / ');
	}

	function subagentRuntimeRoutesForRequestedTools(entry: SessionTreeEntry): ToolRuntimeRouteProjection[] {
		const routes = subagentRuntimeRoutes(entry);
		if (routes.length === 0) return [];

		const tasks = subagentStateForEntry(entry)?.tasks || subagentBatchContent(entry).tasks || [];
		const requestedNames = new Set<string>();
		for (const task of tasks) {
			const toolNames = Array.isArray((task as any)?.toolNames) ? (task as any).toolNames : [];
			for (const name of toolNames) {
				if (typeof name === 'string' && name.trim()) {
					requestedNames.add(name.trim());
				}
			}
		}

		if (requestedNames.size === 0) {
			return routes;
		}

		return routes.filter(route => requestedNames.has(route.name));
	}

	return {
		hasMoreEvidenceSummaries,
		hasMoreProcessEvents,
		isDelegatedToolResultEntry,
		subagentEvidenceSummaries,
		subagentProcessEvents,
		subagentProjectionDiagnostics,
		subagentProjectionDiagnosticsDisplay,
		subagentProjectionDiagnosticsSummary,
		subagentResultCount,
		subagentResultHeadline,
		subagentResultPreview,
		subagentRuntimeRouteSummary,
		subagentRuntimeRoutes,
		subagentRuntimeRoutesForRequestedTools,
		subagentStateForEntry,
		subagentTaskCount,
		subagentTaskPanels,
		subagentTaskPreview,
		visibleSubagentProcessEvents,
	};
}
