// storage/technology-selection-store.ts — SPEC-1021 project-local technology contract
import { mkdir, readFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { writeJsonSafe } from '../engine/safety/atomic-writer.js';
import { safeJsonParse } from './base-store.js';
import { withFileLock } from './file-mutex.js';
export const TECHNOLOGY_SELECTION_RELATIVE_PATH = '.planu/technology-selection.json';
function contractPath(projectPath) {
    return join(projectPath, TECHNOLOGY_SELECTION_RELATIVE_PATH);
}
function isStringArray(value) {
    return Array.isArray(value) && value.every((item) => typeof item === 'string');
}
function isTechnologySelectionContract(value) {
    if (value === null || typeof value !== 'object') {
        return false;
    }
    const rec = value;
    return ((rec.mode === 'existing_project' || rec.mode === 'new_project') &&
        typeof rec.projectPath === 'string' &&
        (rec.source === 'detected' ||
            rec.source === 'user-confirmed' ||
            rec.source === 'suggested-confirmed') &&
        isStringArray(rec.evidence) &&
        Array.isArray(rec.officialDocs));
}
export async function readTechnologySelectionContract(projectPath) {
    try {
        const raw = await readFile(contractPath(projectPath), 'utf-8');
        const parsed = safeJsonParse(raw, null);
        return isTechnologySelectionContract(parsed) ? parsed : null;
    }
    catch {
        return null;
    }
}
export async function writeTechnologySelectionContract(projectPath, contract) {
    const filePath = contractPath(projectPath);
    await mkdir(dirname(filePath), { recursive: true });
    await withFileLock(filePath, () => writeJsonSafe(filePath, contract));
}
//# sourceMappingURL=technology-selection-store.js.map