import { computed, type Ref } from 'vue';
import {
	describeComposerTarget,
	describePendingSendGuard,
	describeSelectionState,
} from '../store/subagent_projection';
import type { AgentInfo, AgentSession, SessionTreeEntry, SessionTreeSessionMeta } from '../types/index.d';

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

type ChatPageDisplayRefs = {
	currentAgent: Ref<AgentInfo | null | undefined>;
	entryById: Ref<Record<string, SessionTreeEntry>>;
	pendingLeafConfirmation: Ref<PendingLeafConfirmation>;
	selectedEntry: Ref<SessionTreeEntry | null>;
	selectedEntryId: Ref<string | null>;
	sessionId: Ref<string | null>;
	sessionMeta: Ref<SessionTreeSessionMeta | null>;
	sessions: Ref<AgentSession[]>;
	switchingLeafEntryId: Ref<string | null>;
};

export function useChatPageDisplay(refs: ChatPageDisplayRefs) {
	const sessionTitle = computed(() => {
		return refs.sessionMeta.value?.title?.trim()
			|| refs.sessions.value.find(item => item.sessionId === refs.sessionId.value)?.title
			|| '未命名会话';
	});

	const sessionProviderLabel = computed(() => {
		return refs.sessionMeta.value?.provider === 'mysql' ? 'MySQL' : 'File';
	});

	const sessionCwdLabel = computed(() => {
		const sessionCwd = refs.sessionMeta.value?.cwd?.trim();
		if (sessionCwd) return sessionCwd;
		const agentCwd = (refs.currentAgent.value?.config as any)?.session?.cwd?.trim();
		return agentCwd || '未设置';
	});

	const restoreLastSessionLabel = computed(() => {
		return (refs.currentAgent.value?.config as any)?.session?.restoreLastSession === false ? '关闭' : '开启';
	});

	const composerTargetSummary = computed(() => {
		return describeComposerTarget(refs.selectedEntry.value, refs.sessionMeta.value?.leafEntryId, refs.entryById.value);
	});

	const selectionStateSummary = computed(() => {
		return describeSelectionState(
			refs.selectedEntryId.value,
			refs.sessionMeta.value?.leafEntryId,
			refs.switchingLeafEntryId.value,
			refs.pendingLeafConfirmation.value,
		);
	});

	function pendingSendGuardMessage(targetTitle: string) {
		return describePendingSendGuard(targetTitle);
	}

	return {
		composerTargetSummary,
		pendingSendGuardMessage,
		restoreLastSessionLabel,
		selectionStateSummary,
		sessionCwdLabel,
		sessionProviderLabel,
		sessionTitle,
	};
}
