// tools/manage-context/crud-handlers.ts — save, load, list, delete action handlers
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { ti } from '../../i18n/index.js';
import { contextDir, sanitizeKey, readMeta, writeMeta, deleteNote, listNoteKeys, isExpired, preview, } from './store.js';
export async function handleSave(projectId, key, content, ttlDays, tags = [], specId) {
    const safeKey = sanitizeKey(key);
    const dir = contextDir(projectId);
    await mkdir(dir, { recursive: true });
    const now = new Date().toISOString();
    const meta = { key, createdAt: now, tags, specId };
    if (ttlDays && ttlDays > 0) {
        const expires = new Date();
        expires.setDate(expires.getDate() + ttlDays);
        meta.expiresAt = expires.toISOString();
    }
    const mdPath = join(dir, `${safeKey}.md`);
    await writeFile(mdPath, content, 'utf-8');
    await writeMeta(projectId, safeKey, meta);
    const result = {
        action: 'save',
        key,
        message: ti('tools.manage_context.success', { action: 'save', key }),
    };
    return {
        content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
    };
}
export async function handleLoad(projectId, key) {
    const safeKey = sanitizeKey(key);
    const dir = contextDir(projectId);
    const mdPath = join(dir, `${safeKey}.md`);
    let content;
    try {
        content = await readFile(mdPath, 'utf-8');
    }
    catch {
        return {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify({ action: 'load', key, error: `Context note '${key}' not found` }, null, 2),
                },
            ],
            isError: true,
        };
    }
    const meta = await readMeta(projectId, safeKey);
    // Check expiration
    if (meta && isExpired(meta)) {
        await deleteNote(projectId, safeKey);
        return {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify({ action: 'load', key, error: `Context note '${key}' has expired and was deleted` }, null, 2),
                },
            ],
            isError: true,
        };
    }
    const result = {
        action: 'load',
        key,
        content,
        message: ti('tools.manage_context.success', { action: 'load', key }),
    };
    return {
        content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
    };
}
export async function handleList(projectId, filterByTag, filterBySpecId) {
    const keys = await listNoteKeys(projectId);
    const dir = contextDir(projectId);
    const notes = [];
    for (const safeKey of keys) {
        const meta = await readMeta(projectId, safeKey);
        // Skip expired notes (but don't delete them here — cleanup does that)
        if (meta && isExpired(meta)) {
            continue;
        }
        // Tag filter: only include notes that have the requested tag
        if (filterByTag && !meta?.tags?.includes(filterByTag)) {
            continue;
        }
        // SpecId filter: only include notes linked to the requested spec
        if (filterBySpecId && meta?.specId !== filterBySpecId) {
            continue;
        }
        let contentPreview;
        try {
            const content = await readFile(join(dir, `${safeKey}.md`), 'utf-8');
            contentPreview = preview(content);
        }
        catch {
            contentPreview = '(unable to read)';
        }
        notes.push({
            key: meta?.key ?? safeKey,
            createdAt: meta?.createdAt ?? 'unknown',
            expiresAt: meta?.expiresAt,
            preview: contentPreview,
            tags: meta?.tags ?? [],
            specId: meta?.specId,
        });
    }
    // Sort by creation date, newest first
    notes.sort((a, b) => {
        if (a.createdAt === 'unknown') {
            return 1;
        }
        if (b.createdAt === 'unknown') {
            return -1;
        }
        return b.createdAt.localeCompare(a.createdAt);
    });
    const result = {
        action: 'list',
        notes,
        message: `Found ${notes.length} context note(s)`,
    };
    return {
        content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
    };
}
export async function handleDelete(projectId, key) {
    const safeKey = sanitizeKey(key);
    const meta = await readMeta(projectId, safeKey);
    if (!meta) {
        return {
            content: [
                {
                    type: 'text',
                    text: JSON.stringify({ action: 'delete', key, error: `Context note '${key}' not found` }, null, 2),
                },
            ],
            isError: true,
        };
    }
    await deleteNote(projectId, safeKey);
    const result = {
        action: 'delete',
        key,
        message: ti('tools.manage_context.success', { action: 'delete', key }),
    };
    return {
        content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
    };
}
//# sourceMappingURL=crud-handlers.js.map