import { writeFile } from "node:fs/promises";
import { stat } from "node:fs/promises";
import { assertUUID, readMeta, findDataFile, attachmentDir, } from "../lib/attachments.js";
import { memoryIngestExtract } from "./memory-ingest-extract.js";
import { resolve } from "node:path";
// ---------------------------------------------------------------------------
// memory-edit-attachment — edit a stored text/markdown attachment in place.
//
// VALIDATE MIME --> WRITE NEW CONTENT --> UPDATE META --> RE-EXTRACT
//      │                   │                   │               │
//      v                   v                   v               v
//  [non-text?]        [disk write]       [timestamp]     [cache populated
//   → reject           failure?           updated         for memory-ingest]
//                       → throw
//
// After editing, the extract cache is populated so the agent can call
// memory-ingest with updated summaries. The agent must still provide
// summaries — this tool handles extract + cache, not the full pipeline.
// ---------------------------------------------------------------------------
const EDITABLE_MIME_TYPES = new Set(["text/plain", "text/markdown"]);
export async function memoryEditAttachment(params) {
    const { accountId, attachmentId, content } = params;
    assertUUID(attachmentId, "attachmentId");
    const t0 = Date.now();
    const tag = attachmentId.slice(0, 8);
    const log = (stage, detail) => console.error(`[memory-edit-attachment] [${tag}] ${stage}${detail ? ` — ${detail}` : ""} (${Date.now() - t0}ms)`);
    log("start");
    const meta = await readMeta(accountId, attachmentId);
    if (!meta) {
        throw new Error(`Attachment "${attachmentId}" not found. ` +
            `No metadata file exists for this attachment in this account.`);
    }
    if (!EDITABLE_MIME_TYPES.has(meta.mimeType)) {
        throw new Error(`Cannot edit "${meta.filename}" — only text/plain and text/markdown files are editable. ` +
            `This file has MIME type "${meta.mimeType}".`);
    }
    const dataFile = await findDataFile(accountId, attachmentId);
    if (!dataFile) {
        throw new Error(`Attachment "${attachmentId}" metadata exists but the data file is missing.`);
    }
    const oldStat = await stat(dataFile);
    const oldSizeBytes = oldStat.size;
    // Write the updated content to disk
    log("writing", `${content.length} chars`);
    await writeFile(dataFile, content, "utf-8");
    const newStat = await stat(dataFile);
    const newSizeBytes = newStat.size;
    // Update meta.json timestamp and size
    const updatedMeta = {
        ...meta,
        sizeBytes: newSizeBytes,
        storedAt: new Date().toISOString(),
    };
    const metaPath = resolve(attachmentDir(accountId, attachmentId), `${attachmentId}.meta.json`);
    await writeFile(metaPath, JSON.stringify(updatedMeta, null, 2));
    log("meta-updated", `${oldSizeBytes} → ${newSizeBytes} bytes`);
    // Re-extract to populate the cache for memory-ingest
    let cachePopulated = false;
    let extractSections;
    let extractChunks;
    try {
        const extractResult = await memoryIngestExtract({
            storagePath: dataFile,
            filename: meta.filename,
            mimeType: meta.mimeType,
            attachmentId,
        });
        cachePopulated = true;
        extractSections = extractResult.sections.length;
        extractChunks = extractResult.sections.reduce((n, s) => n + s.chunkCount, 0);
        log("cache-populated", `${extractSections} sections, ${extractChunks} chunks`);
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        log("cache-failed", msg);
        console.error(`[memory-edit-attachment] [${tag}] WARNING: file was updated on disk ` +
            `but extract cache could not be populated. The agent will need to call ` +
            `memory-ingest-extract manually before memory-ingest. Error: ${msg}`);
    }
    log("complete", `${meta.filename} — ${oldSizeBytes} → ${newSizeBytes} bytes — cache ${cachePopulated ? "populated" : "FAILED"}`);
    return {
        attachmentId,
        filename: meta.filename,
        mimeType: meta.mimeType,
        oldSizeBytes,
        newSizeBytes,
        cachePopulated,
        extractSections,
        extractChunks,
    };
}
//# sourceMappingURL=memory-edit-attachment.js.map