/**
 * Guidance pack export + import dry-run helpers (CAEUX-P2-05 / T100090).
 */
import { createHash } from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { stableStringifyForCaeDigest } from "./cae-registry-load.js";
export function sha256FileIfReadable(absPath) {
    try {
        if (!fs.existsSync(absPath))
            return null;
        const st = fs.statSync(absPath);
        if (!st.isFile())
            return null;
        return createHash("sha256").update(fs.readFileSync(absPath)).digest("hex");
    }
    catch {
        return null;
    }
}
function artifactRowFingerprint(row) {
    return stableStringifyForCaeDigest({
        artifactId: row.artifact_id,
        artifactType: row.artifact_type,
        path: row.path,
        title: row.title,
        description: row.description,
        metadata_json: row.metadata_json
    });
}
function activationRowFingerprint(row) {
    return stableStringifyForCaeDigest({
        activationId: row.activation_id,
        family: row.family,
        priority: row.priority,
        lifecycle_state: row.lifecycle_state,
        scope_json: row.scope_json,
        artifact_refs_json: row.artifact_refs_json,
        acknowledgement_json: row.acknowledgement_json,
        metadata_json: row.metadata_json
    });
}
export function buildGuidancePackExport(input) {
    const hashes = {};
    const root = path.resolve(input.workspaceRoot);
    for (const r of input.artifactRows) {
        const aid = String(r.artifact_id ?? "");
        const p = String(r.path ?? "").trim();
        if (!aid.length || !p.length)
            continue;
        hashes[aid] = sha256FileIfReadable(path.resolve(root, p));
    }
    return {
        schemaVersion: 1,
        exportedAt: new Date().toISOString(),
        sourceVersionId: input.versionId,
        artifacts: input.artifactRows,
        activations: input.activationRows,
        artifactFileHashes: hashes
    };
}
export function dryRunGuidancePackImport(input) {
    const activeArtById = new Map();
    for (const r of input.activeArtifactRows) {
        const id = String(r.artifact_id ?? "");
        if (id.length)
            activeArtById.set(id, r);
    }
    const activeActById = new Map();
    for (const r of input.activeActivationRows) {
        const id = String(r.activation_id ?? "");
        if (id.length)
            activeActById.set(id, r);
    }
    const artifactConflicts = [];
    const artifactsWouldAdd = [];
    for (const r of input.pack.artifacts) {
        const id = String(r.artifact_id ?? "");
        if (!id.length)
            continue;
        const cur = activeArtById.get(id);
        if (!cur) {
            artifactsWouldAdd.push(id);
            continue;
        }
        if (artifactRowFingerprint(cur) !== artifactRowFingerprint(r)) {
            artifactConflicts.push({
                artifactId: id,
                reason: "Active registry row fingerprint differs from pack row for the same artifact_id"
            });
        }
    }
    const activationConflicts = [];
    const activationsWouldAdd = [];
    for (const r of input.pack.activations) {
        const id = String(r.activation_id ?? "");
        if (!id.length)
            continue;
        const cur = activeActById.get(id);
        if (!cur) {
            activationsWouldAdd.push(id);
            continue;
        }
        if (activationRowFingerprint(cur) !== activationRowFingerprint(r)) {
            activationConflicts.push({
                activationId: id,
                reason: "Active registry row fingerprint differs from pack row for the same activation_id"
            });
        }
    }
    return {
        schemaVersion: 1,
        artifactConflicts,
        activationConflicts,
        artifactsWouldAdd: artifactsWouldAdd.sort((a, b) => a.localeCompare(b)),
        activationsWouldAdd: activationsWouldAdd.sort((a, b) => a.localeCompare(b))
    };
}
