import { readJson, writeJson, projectDataDir } from './base-store.js';
// --- internal helpers ---
function specsFile(projectId) {
    return `${projectDataDir(projectId)}/specs.json`;
}
/** Normalize legacy specs: map huPath→specPath, fichaTecnicaPath→technicalPath */
function normalizeSpec(raw) {
    const spec = raw;
    // Lazy migration: legacy field names → modern field names
    if (!spec.specPath && spec.huPath) {
        spec.specPath = spec.huPath;
    }
    if (!spec.technicalPath && spec.fichaTecnicaPath) {
        spec.technicalPath = spec.fichaTecnicaPath;
    }
    return spec;
}
async function loadAll(projectId) {
    const raw = await readJson(specsFile(projectId), []);
    return raw.map(normalizeSpec);
}
async function saveAll(projectId, specs) {
    await writeJson(specsFile(projectId), specs);
}
// --- public API ---
/**
 * List every spec for a project.
 */
export async function listSpecs(projectId) {
    return loadAll(projectId);
}
/**
 * Get a single spec by ID. Returns `null` when not found.
 */
export async function getSpec(projectId, specId) {
    const specs = await loadAll(projectId);
    return specs.find((s) => s.id === specId) ?? null;
}
/**
 * Create a new spec. Throws if a spec with the same ID already exists.
 */
export async function createSpec(projectId, spec) {
    const specs = await loadAll(projectId);
    if (specs.some((s) => s.id === spec.id)) {
        throw new Error(`Spec "${spec.id}" already exists in project "${projectId}"`);
    }
    specs.push(spec);
    await saveAll(projectId, specs);
    return spec;
}
/**
 * Replace an existing spec entirely. Throws if the spec does not exist.
 */
export async function updateSpec(projectId, specId, updates) {
    const specs = await loadAll(projectId);
    const idx = specs.findIndex((s) => s.id === specId);
    if (idx === -1) {
        throw new Error(`Spec "${specId}" not found in project "${projectId}"`);
    }
    const existing = specs[idx];
    if (!existing) {
        throw new Error(`Spec "${specId}" not found in project "${projectId}"`);
    }
    const updated = {
        ...existing,
        ...updates,
        id: specId, // never allow id override
        updatedAt: new Date().toISOString(),
    };
    specs[idx] = updated;
    await saveAll(projectId, specs);
    return updated;
}
/**
 * Update only the status field of a spec.
 */
export async function updateSpecStatus(projectId, specId, status) {
    return updateSpec(projectId, specId, { status });
}
/**
 * Delete a spec by ID. Returns `true` if removed, `false` if not found.
 */
export async function deleteSpec(projectId, specId) {
    const specs = await loadAll(projectId);
    const idx = specs.findIndex((s) => s.id === specId);
    if (idx === -1) {
        return false;
    }
    specs.splice(idx, 1);
    await saveAll(projectId, specs);
    return true;
}
/**
 * Find specs matching a predicate.
 */
export async function findSpecs(projectId, predicate) {
    const specs = await loadAll(projectId);
    return specs.filter(predicate);
}
/**
 * Count specs for a project, optionally filtered by status.
 */
export async function countSpecs(projectId, status) {
    const specs = await loadAll(projectId);
    if (status) {
        return specs.filter((s) => s.status === status).length;
    }
    return specs.length;
}
// --- DoR/DoD persistence ---
function dorFile(projectId, specId) {
    return `${projectDataDir(projectId)}/specs/${specId}/dor.json`;
}
function dodFile(projectId, specId) {
    return `${projectDataDir(projectId)}/specs/${specId}/dod.json`;
}
/**
 * Persist a DoR checklist for a spec.
 */
export async function saveDor(projectId, specId, dor) {
    await writeJson(dorFile(projectId, specId), dor);
}
/**
 * Load the persisted DoR checklist for a spec. Returns null if not found.
 */
export async function loadDor(projectId, specId) {
    return readJson(dorFile(projectId, specId), null);
}
/**
 * Persist a DoD checklist for a spec.
 */
export async function saveDoD(projectId, specId, dod) {
    await writeJson(dodFile(projectId, specId), dod);
}
/**
 * Load the persisted DoD checklist for a spec. Returns null if not found.
 */
export async function loadDoD(projectId, specId) {
    return readJson(dodFile(projectId, specId), null);
}
// --- Version persistence ---
function versionsFile(projectId, specId) {
    return `${projectDataDir(projectId)}/specs/${specId}/versions.json`;
}
/**
 * Append a new SpecVersion to the version history for a spec.
 */
export async function saveVersion(projectId, specId, version) {
    const existing = await loadVersions(projectId, specId);
    existing.push(version);
    await writeJson(versionsFile(projectId, specId), existing);
}
/**
 * Load all persisted versions for a spec. Returns empty array if none exist.
 */
export async function loadVersions(projectId, specId) {
    return readJson(versionsFile(projectId, specId), []);
}
/**
 * Get the latest version number for a spec (0 if no versions exist).
 */
export async function getLatestVersion(projectId, specId) {
    const versions = await loadVersions(projectId, specId);
    if (versions.length === 0) {
        return 0;
    }
    return Math.max(...versions.map((v) => v.version));
}
// --- Summary persistence ---
function summaryFile(projectId, specId) {
    return `${projectDataDir(projectId)}/specs/${specId}/summary.json`;
}
/**
 * Persist a SpecSummary for a spec. Used by summarize_spec to cache results.
 */
export async function saveSummary(projectId, specId, summary) {
    await writeJson(summaryFile(projectId, specId), summary);
}
/**
 * Load the persisted SpecSummary for a spec. Returns null if not found.
 */
export async function loadSummary(projectId, specId) {
    return readJson(summaryFile(projectId, specId), null);
}
//# sourceMappingURL=spec-store.js.map