import { V266_LEASE_DOCUMENT_HTML } from './v266-lease-document.js';
import { TRIAL_AGREEMENT_DOCUMENT_HTML } from './trial-agreement-document.js';
import { TRIAL_AGREEMENT_18T_DOCUMENT_HTML } from './trial-agreement-18t-document.js';
import { mergeMonolithicHtml } from './contract-template-section-html.js';
import { buildInitialWordTemplates } from './contract-template-seed.js';
import {
	ensureContractTemplateStore,
	getPublishedEnabledLeaseOptions,
	getPublishedContractTypeOptions,
	getTemplateDocumentById,
	getDefaultTemplateIdForContractType,
	subscribeContractTemplates,
	mapTemplateToLeaseOption,
	restoreContractTemplatesFromSession,
} from './contract-template-store.js';

export {
	getContractTypeLabel,
	normalizeContractType,
	resolveContractType,
} from './contract-template-types.js';

restoreContractTemplatesFromSession();
ensureContractTemplateStore(buildInitialWordTemplates);

export function getPublishedContractTemplateOptions(category) {
	return getPublishedEnabledLeaseOptions(category);
}

export function getPublishedContractTypeChoices(category) {
	return getPublishedContractTypeOptions(category);
}

export function subscribePublishedContractTemplateOptions(listener) {
	return subscribeContractTemplates(listener);
}

export function getContractTemplateOption(templateId) {
	var doc = getTemplateDocumentById(templateId);
	if (!doc || doc.status !== 'published' || doc.enabled === false) return null;
	return mapTemplateToLeaseOption(doc);
}

function getStaticTemplateBaseHtml(templateId) {
	switch (templateId) {
		case 'doc-4':
			return TRIAL_AGREEMENT_DOCUMENT_HTML || '';
		case 'doc-5':
			return TRIAL_AGREEMENT_18T_DOCUMENT_HTML || '';
		case 'doc-1':
		case 'doc-2':
		default:
			return V266_LEASE_DOCUMENT_HTML || '';
	}
}

/** 优先读取 store 中模板的 sectionContents，静态 HTML 仅作兜底 */
export function getContractTemplateBaseHtml(templateId) {
	var doc = getTemplateDocumentById(templateId);
	if (doc && doc.sectionContents) {
		var merged = mergeMonolithicHtml(doc.sectionContents);
		if (merged && String(merged).trim()) return merged;
	}
	return getStaticTemplateBaseHtml(templateId);
}

export function getDefaultContractTemplateId(contractType, category) {
	return getDefaultTemplateIdForContractType(contractType, category);
}

export function getContractTemplatePreviewBadge(templateId) {
	var option = getContractTemplateOption(templateId);
	if (!option) return '请先选择合同模板';
	return option.contractTypeLabel || option.title || option.kind || '—';
}
