import { readJson, writeJson, projectDataDir } from '../base-store.js';
import { withFileLock } from '../file-mutex.js';
import { discoverProjectDataFile } from '../data-dir-discovery.js';
import { migrateLegacyDataDir } from '../migrations/cwd-to-absolute.js';
function knowledgeFile(projectId) {
    return `${projectDataDir(projectId)}/knowledge.json`;
}
/**
 * Get project knowledge. Returns `null` when no knowledge has been stored yet.
 *
 * Read fallback (cwd-tolerance): when the cwd-relative file does not exist,
 * walk up from cwd and consult the registered projectPath before giving up.
 * This unblocks users whose MCP server runs from a different cwd than the one
 * used during init_project.
 */
export async function getKnowledge(projectId) {
    // SPEC-1007: migrate legacy <cwd>/data/projects/{id} to absolute home once.
    await migrateLegacyDataDir(projectId);
    const direct = await readJson(knowledgeFile(projectId), null);
    if (direct !== null) {
        return direct;
    }
    const discovered = await discoverProjectDataFile(projectId, 'knowledge.json');
    if (discovered === null) {
        return null;
    }
    return readJson(discovered, null);
}
/**
 * Save or overwrite the full project knowledge object.
 */
export async function saveKnowledge(projectId, knowledge) {
    // SPEC-1007: migrate legacy tree before first save so writes land in absolute path.
    await migrateLegacyDataDir(projectId);
    await withFileLock(knowledgeFile(projectId), async () => {
        await writeJson(knowledgeFile(projectId), knowledge);
    });
}
/**
 * Partially update project knowledge, merging with the existing object.
 */
export async function updateKnowledge(projectId, updates) {
    return withFileLock(knowledgeFile(projectId), async () => {
        const existing = await readJson(knowledgeFile(projectId), null);
        if (!existing) {
            throw new Error(`No knowledge found for project "${projectId}". Use saveKnowledge first.`);
        }
        const updated = {
            ...existing,
            ...updates,
            projectId, // never allow override
            lastAnalyzed: new Date().toISOString(),
        };
        await writeJson(knowledgeFile(projectId), updated);
        return updated;
    });
}
/**
 * Delete all knowledge for a project. Returns `true` if it existed.
 */
export async function deleteKnowledge(projectId) {
    return withFileLock(knowledgeFile(projectId), async () => {
        const existing = await readJson(knowledgeFile(projectId), null);
        if (!existing) {
            return false;
        }
        // Overwrite with null sentinel so readJson returns null on next read
        await writeJson(knowledgeFile(projectId), null);
        return true;
    });
}
export { knowledgeFile };
//# sourceMappingURL=knowledge.js.map