import type { Ref } from 'vue';
import {
	describeTreeNodeBadges,
	extractTreeNodeContextMeta,
	summarizeBranchEntry,
	summarizeCompactionEntry,
} from '../store/subagent_projection';
import type { SessionTreeEntry, SessionTreeSessionMeta } from '../types/index.d';

type PendingLeafConfirmation = { entryId: string; previousLeafEntryId: string | null } | null;
const MAX_TREE_DISPLAY_DEPTH = 5;

type SessionTreeDisplayRefs = {
	activePathIds: Ref<string[]>;
	childrenByParentId: Ref<Record<string, string[]>>;
	entryById: Ref<Record<string, SessionTreeEntry>>;
	pendingLeafConfirmation: Ref<PendingLeafConfirmation>;
	selectedEntryId: Ref<string | null>;
	sessionId: Ref<string | null>;
	sessionMeta: Ref<SessionTreeSessionMeta | null>;
};

export function useSessionTreeDisplay(refs: SessionTreeDisplayRefs) {
	function flattenTree(rootId: string, depth = 0): Array<{ id: string; depth: number; type: string; node: SessionTreeEntry }> {
		const node = refs.entryById.value[rootId];
		if (!node) return [];
		const children = refs.childrenByParentId.value[rootId] || [];
		return [
			{ id: node.id, depth: Math.min(depth, MAX_TREE_DISPLAY_DEPTH), type: node.type, node },
			...children.flatMap(childId => flattenTree(childId, depth + 1)),
		];
	}

	function isLeafEntry(entry: SessionTreeEntry) {
		return refs.sessionMeta.value?.leafEntryId === entry.id;
	}

	function canContinueFromEntry(entry: SessionTreeEntry) {
		return Boolean(refs.sessionId.value) && !isLeafEntry(entry);
	}

	function continueActionLabel(entry: SessionTreeEntry) {
		return entry.type === 'message' && entry.message?.role === 'user' ? '从这里分支' : '从这里继续';
	}

	function treeNodeBadges(entry: SessionTreeEntry): Array<{ label: string; tone: 'leaf' | 'path' | 'branch' | 'selected' | 'pending' }> {
		return describeTreeNodeBadges(entry, {
			selectedEntryId: refs.selectedEntryId.value,
			leafEntryId: refs.sessionMeta.value?.leafEntryId,
			activePathIds: refs.activePathIds.value,
			pendingLeafConfirmation: refs.pendingLeafConfirmation.value,
		});
	}

	function treeNodeContextMeta(entry: SessionTreeEntry) {
		return extractTreeNodeContextMeta(entry);
	}

	function branchSummaryText(entry: SessionTreeEntry) {
		return summarizeBranchEntry(entry).summary;
	}

	function branchSourceLabel(entry: SessionTreeEntry) {
		return summarizeBranchEntry(entry).sourceLabel;
	}

	function compactionSummaryText(entry: SessionTreeEntry) {
		return summarizeCompactionEntry(entry).summary;
	}

	function compactionTokenLabel(entry: SessionTreeEntry) {
		return summarizeCompactionEntry(entry).tokenLabel;
	}

	function compactionBoundaryLabel(entry: SessionTreeEntry) {
		return summarizeCompactionEntry(entry).boundaryLabel;
	}

	return {
		branchSourceLabel,
		branchSummaryText,
		canContinueFromEntry,
		compactionBoundaryLabel,
		compactionSummaryText,
		compactionTokenLabel,
		continueActionLabel,
		flattenTree,
		isLeafEntry,
		treeNodeBadges,
		treeNodeContextMeta,
	};
}
