import { isObjectLike as isRecord } from '../utils/records' import { getBioTemplateInfo, } from './catalog' import { getBioTemplatePackInfo, } from './packs' import { getBioTemplatePresetInfo, } from './presets' import { extractTemplateCollection, } from './templateEnvelopes' import type { BioTemplateEnvelope, TemplateId, TemplatePresetId, } from './types' import type { BioTemplateControlTarget, } from './controlSchemaTypes' export type ControlSchemaResolvedTarget = | { kind: 'template'; name: TemplateId } | { kind: 'pack'; templates: TemplateId[] } | { kind: 'preset'; name: TemplatePresetId } | { kind: 'collection'; templates: TemplateId[] } export function resolveControlSchemaTarget( target: BioTemplateControlTarget ): ControlSchemaResolvedTarget | undefined { if (typeof target === 'string') { const preset = getBioTemplatePresetInfo(target) if (preset) return { kind: 'preset', name: preset.name } const pack = getBioTemplatePackInfo(target) if (pack) return { kind: 'pack', templates: [...pack.templates] } const template = getBioTemplateInfo(target) if (template) return { kind: 'template', name: template.template_id } return undefined } if (isTemplateEnvelope(target)) { const template = getBioTemplateInfo(target.template_id) return template ? { kind: 'template', name: template.template_id } : undefined } const presetName = collectionPresetName(target) if (presetName) { const preset = getBioTemplatePresetInfo(presetName) if (preset) return { kind: 'preset', name: preset.name } } const packName = collectionPackName(target) if (packName) { const pack = getBioTemplatePackInfo(packName) if (pack) return { kind: 'pack', templates: [...pack.templates] } } const collection = extractTemplateCollection(target) const templateIds = Object.keys(collection) .map(id => getBioTemplateInfo(id)?.template_id) .filter((id): id is TemplateId => id !== undefined) return templateIds.length > 0 ? { kind: 'collection', templates: templateIds } : undefined } export function describeControlTarget(target: BioTemplateControlTarget): string { if (typeof target === 'string') return target if (isTemplateEnvelope(target)) return target.template_id return collectionPresetName(target) ?? collectionPackName(target) ?? 'template collection' } function isTemplateEnvelope(value: unknown): value is BioTemplateEnvelope { return isRecord(value) && typeof value.template_id === 'string' && 'data' in value } function collectionPresetName(value: unknown): string | undefined { if (!isRecord(value) || !isRecord(value.metadata)) return undefined return typeof value.metadata.preset === 'string' ? value.metadata.preset : undefined } function collectionPackName(value: unknown): string | undefined { if (!isRecord(value) || !isRecord(value.metadata)) return undefined return typeof value.metadata.pack === 'string' ? value.metadata.pack : undefined }