import { readFile } from "node:fs/promises";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { assertUUID, readMeta, findDataFile, } from "../lib/attachments.js";
// ---------------------------------------------------------------------------
// memory-read-attachment — read a stored attachment's content from disk.
//
// META.JSON --> MIME CHECK --> READ/EXTRACT --> RETURN
//                  │               │
//                  v               v
//             [image?]        [text → raw]
//             → metadata      [pdf → pdftotext]
//               + URL
// ---------------------------------------------------------------------------
const execFileAsync = promisify(execFile);
export async function memoryReadAttachment(accountId, attachmentId) {
    assertUUID(attachmentId, "attachmentId");
    const t0 = Date.now();
    const tag = attachmentId.slice(0, 8);
    const log = (stage, detail) => console.error(`[memory-read-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.`);
    }
    const dataFile = await findDataFile(accountId, attachmentId);
    if (!dataFile) {
        throw new Error(`Attachment "${attachmentId}" metadata exists but the data file is missing.`);
    }
    const { filename, mimeType, sizeBytes, storedAt } = meta;
    // Images: return metadata + URL only (binary content not useful in text response)
    if (mimeType.startsWith("image/")) {
        log("image", `${filename} — metadata only`);
        return {
            attachmentId,
            filename,
            mimeType,
            sizeBytes,
            storedAt,
            contentNote: "Image files are returned as metadata only. " +
                "Use the HTTP URL to view the image in the chat UI.",
            httpUrl: `/api/admin/attachment/${attachmentId}`,
        };
    }
    // Text/markdown: return full content
    if (mimeType === "text/plain" || mimeType === "text/markdown") {
        const content = await readFile(dataFile, "utf-8");
        log("text", `${filename} — ${content.length} chars`);
        return {
            attachmentId,
            filename,
            mimeType,
            sizeBytes,
            storedAt,
            content,
        };
    }
    // PDF: extract text via pdftotext
    if (mimeType === "application/pdf") {
        log("pdf-extract", filename);
        try {
            const { stdout } = await execFileAsync("pdftotext", [dataFile, "-"], {
                maxBuffer: 10 * 1024 * 1024,
            });
            const content = stdout.trim();
            log("pdf-extracted", `${content.length} chars`);
            return {
                attachmentId,
                filename,
                mimeType,
                sizeBytes,
                storedAt,
                content,
                contentNote: "This is extracted text from a PDF. " +
                    "The original layout and formatting are not preserved.",
            };
        }
        catch (err) {
            const msg = err instanceof Error ? err.message : String(err);
            if (msg.includes("ENOENT") || msg.includes("not found")) {
                throw new Error("pdftotext not found. Install poppler-utils: sudo apt-get install -y poppler-utils");
            }
            throw new Error(`PDF text extraction failed: ${msg}`);
        }
    }
    // CSV and other types: return metadata only with explanation
    log("unsupported-content", `${filename} (${mimeType}) — metadata only`);
    return {
        attachmentId,
        filename,
        mimeType,
        sizeBytes,
        storedAt,
        contentNote: `Content reading is not supported for MIME type "${mimeType}". ` +
            `Supported for reading: text/plain, text/markdown, application/pdf. ` +
            `Images return metadata and HTTP URL.`,
    };
}
//# sourceMappingURL=memory-read-attachment.js.map