/**
 * emitFileContents() — reads a file from disk and hands its contents to
 * the writer's `emit()`. Shim for the legacy `captureFile(path)` pattern
 * now that the port takes in-memory payloads.
 *
 * Covers the ~13 producer sites that write a file for user-facing output
 * (e.g. promptfoo writes YAML configs and JSON results) and then need to
 * also capture them as artifacts. Reading at emit-time is uniform, keeps
 * the port narrow, and costs nothing at the sizes in play (all descriptors
 * cap ≤10 MB; most are ≤256 KB).
 *
 * Failures are non-blocking per P5 — a missing file or unparseable JSON
 * returns null + warns rather than throwing, so the pipeline keeps moving
 * even if the user-facing file wasn't produced.
 *
 * See `tasks/plan.md § Q2` for the design rationale.
 */
import { promises as fs } from "node:fs";
import { ARTIFACT_REGISTRY, } from "../_vendor/ailf-core/index.js";
/**
 * Read a file from disk, parse it per the descriptor's mime, and emit it.
 *
 * - JSON mime: file contents are `JSON.parse`d into an object before `emit()`.
 * - Markdown / YAML mime: file contents are passed to `emit()` as a string.
 * - NDJSON: not supported by `emit()` — use `appendNdjson()` directly instead.
 *
 * Returns null (with a warn) on any error. Never throws.
 */
export async function emitFileContents(writer, type, association, filePath) {
    const descriptor = ARTIFACT_REGISTRY[type];
    if (descriptor.mime === "application/x-ndjson") {
        console.warn(`  ⚠️  emitFileContents("${type}", ${filePath}): NDJSON types require appendNdjson(), not emit() — skipping`);
        return null;
    }
    let contents;
    try {
        contents = await fs.readFile(filePath, "utf-8");
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        console.warn(`  ⚠️  emitFileContents read failed (non-blocking): ${filePath} — ${message}`);
        return null;
    }
    let payload = contents;
    if (descriptor.mime === "application/json") {
        try {
            payload = JSON.parse(contents);
        }
        catch (err) {
            const message = err instanceof Error ? err.message : String(err);
            console.warn(`  ⚠️  emitFileContents parse failed (non-blocking): ${filePath} — ${message}`);
            return null;
        }
    }
    return writer.emit(type, association, payload);
}
