"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cloneCharacter = cloneCharacter;
const uuid_1 = require("uuid");
const serializer_js_1 = require("./serializer.js");
const prompt_builder_js_1 = require("./prompt-builder.js");
const index_js_1 = require("../data-store/index.js");
/**
 * Clone an existing character with optional overrides.
 * Deep clones DNA, assigns new UUID v4, applies selective field changes,
 * rebuilds master prompt, copies conversation profile, and saves to data store.
 */
async function cloneCharacter(sourceId, overrides, options) {
    const sourceDNA = await index_js_1.dataStore.getCharacter(sourceId);
    if (!sourceDNA) {
        throw new Error(`Source character not found: ${sourceId}`);
    }
    // Deep clone the source DNA
    const newDNA = (0, serializer_js_1.cloneDNA)(sourceDNA);
    // Apply selective field overrides before setting managed fields
    if (overrides) {
        applyOverrides(newDNA, overrides);
    }
    // Assign new unique ID and timestamps (always override, even if in overrides)
    const newId = (0, uuid_1.v4)();
    const now = new Date().toISOString();
    newDNA.id = newId;
    newDNA.createdAt = now;
    newDNA.updatedAt = now;
    newDNA.status = 'creating';
    // Save the new character DNA
    await index_js_1.dataStore.saveCharacter(newDNA);
    // Rebuild and save master prompt from the new DNA
    const masterPrompt = (0, prompt_builder_js_1.buildMasterPrompt)(newDNA);
    await index_js_1.dataStore.saveMasterPrompt(masterPrompt);
    // Deep clone and save conversation profile with updated characterId
    const sourceProfile = await index_js_1.dataStore.getConversationProfile(sourceId);
    if (sourceProfile) {
        const newProfile = JSON.parse(JSON.stringify(sourceProfile));
        newProfile.characterId = newId;
        await index_js_1.dataStore.saveConversationProfile(newProfile);
    }
    return newDNA;
}
/**
 * Applies partial overrides to a CharacterDNA object.
 * Merges nested objects shallowly per top-level section.
 * Skips id, createdAt, updatedAt as those are managed by clone logic.
 */
function applyOverrides(dna, overrides) {
    for (const key of Object.keys(overrides)) {
        if (key === 'id' || key === 'createdAt' || key === 'updatedAt')
            continue;
        const value = overrides[key];
        if (value !== undefined && typeof value === 'object' && value !== null && !Array.isArray(value)) {
            dna[key] = { ...dna[key], ...value };
        }
        else if (value !== undefined) {
            dna[key] = value;
        }
    }
}
//# sourceMappingURL=clone.js.map