import { normalizeBrandVoice } from './brand-voice.js';
import { applyParsedDocumentToProfile, parseBrandVoiceDocument, serializeBrandVoiceDocument, } from './brand-voice-document.js';
import { parseStructuredProfile } from './brand-voice-structured.js';
function metaFromProfile(profile) {
    return {
        version: profile.version ?? 1,
        status: profile.status ?? 'draft',
        generatedFrom: profile.generatedFrom ?? [],
        lastUpdated: new Date().toISOString().slice(0, 10),
    };
}
function fromParsed(enabled, parsed) {
    return normalizeBrandVoice(applyParsedDocumentToProfile({ enabled }, parsed));
}
/**
 * Normalize a brand voice payload for persistence. Quick-edit fields and the
 * markdown document stay in sync — whichever surface the editor used last wins.
 */
export function prepareBrandVoiceForSave(input) {
    const enabled = Boolean(input.enabled);
    const fields = {
        name: input.name ?? '',
        tone: input.tone ?? '',
        audience: input.audience ?? '',
        guidelines: input.guidelines ?? '',
        sampleText: input.sampleText ?? '',
    };
    if (input.preferDocument && input.document?.trim()) {
        const parsed = parseBrandVoiceDocument(input.document);
        if (!parsed.ok)
            throw new Error(parsed.error);
        return fromParsed(enabled, parsed.value);
    }
    const meta = metaFromProfile(input);
    const structured = input.document?.trim() ? parseStructuredProfile(input.document) : undefined;
    const document = serializeBrandVoiceDocument({
        fields,
        meta: { ...meta, version: (input.version ?? 1) + 1 },
        existingDocument: input.document,
        structured,
    });
    return normalizeBrandVoice({
        enabled,
        ...fields,
        document,
        version: (input.version ?? 1) + 1,
        status: meta.status,
        generatedFrom: meta.generatedFrom.length ? meta.generatedFrom : undefined,
    });
}
//# sourceMappingURL=brand-voice-save.js.map