"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.archiveSpecRegistryEntry = archiveSpecRegistryEntry;
exports.buildArchivedRegistryDocument = buildArchivedRegistryDocument;
const traceability_1 = require("./traceability");
const document_io_1 = require("./document-io");
const ARCHIVED_SPEC_REGISTRY_STATUS = "archived";
function archiveSpecRegistryEntry(entry, archiveTimestamp) {
    // Archive writes are lifecycle-only: keep canonical traceability fields and metadata unchanged.
    const preservedFields = preserveArchiveTraceabilityFields(entry);
    return {
        ...preservedFields,
        status: ARCHIVED_SPEC_REGISTRY_STATUS,
        optional: {
            ...preservedFields.optional,
            updated_at: (0, traceability_1.parseRegistryTimestampField)(archiveTimestamp, "updated_at"),
            archived_at: archiveTimestamp
        }
    };
}
function buildArchivedRegistryDocument(currentDocument, targetIndex, archivedEntry) {
    return (0, document_io_1.applyNonDestructiveSpecIndexEntryUpdate)({
        currentDocument,
        targetIndex,
        nextEntry: archivedEntry
    });
}
function preserveArchiveTraceabilityFields(entry) {
    // Keep traceability fields in their canonical schema locations instead of archive-only shadows.
    return {
        id: entry.id,
        title: entry.title,
        depth: entry.depth,
        destination: entry.destination,
        spec_path: entry.spec_path,
        source: {
            ...entry.source,
            additionalMetadata: cloneNestedMetadata(entry.source.additionalMetadata)
        },
        optional: cloneNestedMetadata(entry.optional),
        additionalMetadata: cloneNestedMetadata(entry.additionalMetadata)
    };
}
function cloneNestedMetadata(value) {
    if (Array.isArray(value)) {
        return value.map((item) => cloneNestedMetadata(item));
    }
    if (typeof value !== "object" || value === null) {
        return value;
    }
    const clonedEntries = Object.entries(value).map(([key, nestedValue]) => [key, cloneNestedMetadata(nestedValue)]);
    return Object.fromEntries(clonedEntries);
}
