import { mergeContext } from '../../engine/context-merger.js';
import { readJson, writeJson, projectDataDir } from '../base-store.js';
import { addMetricsToState } from '../../engine/calibrator.js';
import { getKnowledge, knowledgeFile } from './knowledge.js';
// --- File paths ---
function constitutionFile(projectId) {
    return `${projectDataDir(projectId)}/constitution.json`;
}
function clarificationsFile(projectId) {
    return `${projectDataDir(projectId)}/clarifications.json`;
}
function nliContextFile(projectId) {
    return `${projectDataDir(projectId)}/nli-context.json`;
}
function calibrationFile(projectId) {
    return `${projectDataDir(projectId)}/calibration.json`;
}
function feedbackFile(projectId) {
    return `${projectDataDir(projectId)}/feedback.json`;
}
// --- Constitution ---
export async function getConstitution(projectId) {
    return readJson(constitutionFile(projectId), null);
}
export async function saveConstitution(projectId, constitution) {
    await writeJson(constitutionFile(projectId), constitution);
}
export async function updateConstitution(projectId, updates) {
    const existing = await getConstitution(projectId);
    if (!existing) {
        throw new Error(`No constitution found for project "${projectId}". Use saveConstitution first.`);
    }
    const updated = {
        ...existing,
        ...updates,
        projectId,
        version: existing.version + 1,
        updatedAt: new Date().toISOString(),
    };
    await writeJson(constitutionFile(projectId), updated);
    return updated;
}
// --- Clarification Sessions ---
export async function listClarifications(projectId) {
    return readJson(clarificationsFile(projectId), []);
}
export async function getClarification(projectId, sessionId) {
    const sessions = await listClarifications(projectId);
    return sessions.find((s) => s.id === sessionId) ?? null;
}
export async function addClarification(projectId, session) {
    const sessions = await listClarifications(projectId);
    sessions.push(session);
    await writeJson(clarificationsFile(projectId), sessions);
    return session;
}
export async function updateClarification(projectId, sessionId, updates) {
    const sessions = await listClarifications(projectId);
    const idx = sessions.findIndex((s) => s.id === sessionId);
    if (idx === -1) {
        throw new Error(`Clarification session "${sessionId}" not found in project "${projectId}"`);
    }
    const existing = sessions[idx];
    if (!existing) {
        throw new Error(`Clarification session "${sessionId}" not found in project "${projectId}"`);
    }
    const updated = {
        ...existing,
        ...updates,
        id: sessionId,
        projectId,
    };
    sessions[idx] = updated;
    await writeJson(clarificationsFile(projectId), sessions);
    return updated;
}
export async function deleteClarification(projectId, sessionId) {
    const sessions = await listClarifications(projectId);
    const idx = sessions.findIndex((s) => s.id === sessionId);
    if (idx === -1) {
        return false;
    }
    sessions.splice(idx, 1);
    await writeJson(clarificationsFile(projectId), sessions);
    return true;
}
// --- NLI Context ---
export async function getNLIContext(projectId) {
    return readJson(nliContextFile(projectId), {
        currentProject: projectId,
        lastSpecs: [],
        lastTools: [],
        conversationMemory: [],
        userPatterns: [],
    });
}
export async function saveNLIContext(projectId, context) {
    await writeJson(nliContextFile(projectId), context);
}
export async function addUserPattern(projectId, pattern) {
    const context = await getNLIContext(projectId);
    const existing = context.userPatterns.find((p) => p.phrase === pattern.phrase && p.mappedTool === pattern.mappedTool);
    if (existing) {
        existing.frequency += pattern.frequency;
    }
    else {
        context.userPatterns.push(pattern);
    }
    await saveNLIContext(projectId, context);
    return context;
}
export async function appendConversationMemory(projectId, entries, maxEntries = 50) {
    const context = await getNLIContext(projectId);
    context.conversationMemory.push(...entries);
    if (context.conversationMemory.length > maxEntries) {
        context.conversationMemory = context.conversationMemory.slice(-maxEntries);
    }
    await saveNLIContext(projectId, context);
    return context;
}
export async function clearNLIContext(projectId) {
    await saveNLIContext(projectId, {
        currentProject: projectId,
        lastSpecs: [],
        lastTools: [],
        conversationMemory: [],
        userPatterns: [],
    });
}
// --- Calibration (SPEC-011) ---
export async function saveCalibrationMetrics(projectId, metrics) {
    const existing = await loadCalibrationState(projectId);
    const updated = addMetricsToState(existing, metrics);
    await writeJson(calibrationFile(projectId), updated);
    return updated;
}
export async function loadCalibrationState(projectId) {
    return readJson(calibrationFile(projectId), null);
}
export async function saveFeedbackEvent(projectId, event) {
    const history = await loadFeedbackHistory(projectId);
    history.push(event);
    const trimmed = history.length > 200 ? history.slice(-200) : history;
    await writeJson(feedbackFile(projectId), trimmed);
}
export async function loadFeedbackHistory(projectId, type) {
    const all = await readJson(feedbackFile(projectId), []);
    if (!type) {
        return all;
    }
    return all.filter((e) => e.type === type);
}
// --- Context Ingestion (SPEC-036) ---
export async function mergeContributedContext(projectId, context, source) {
    const existing = await getKnowledge(projectId);
    if (!existing) {
        throw new Error(`Project "${projectId}" not found. Run init_project first before contributing context.`);
    }
    const { merged, conflicts } = mergeContext(existing, context);
    const sources = [...(existing.contributedSources ?? []), source];
    await writeJson(knowledgeFile(projectId), {
        ...existing,
        contributedSources: sources,
        lastAnalyzed: new Date().toISOString(),
    });
    return { merged, conflicts, sourcesCount: sources.length };
}
//# sourceMappingURL=sessions.js.map