"use strict";
/**
 * Copyright: (c) Myia SAS 2026.
 * This file and its contents are licensed under the AGPLv3 License.
 * Please see the LICENSE file at the root of this repository
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.rewriteScreenshots = exports.loadTrace = void 0;
// Reads one heal-traces.ndjson and projects it into the viewer model
// the SPA consumes via /api/trace/:id. The on-disk schema is one
// `HealTraceRecord` per non-empty line, in this order: header,
// statements, optional test-result. Missing terminator is treated as
// a partial trace, not an error — the worker may have crashed.
const promises_1 = require("node:fs/promises");
const parseLine = (line, lineNumber) => {
    try {
        return JSON.parse(line);
    }
    catch (err) {
        console.warn(`[heal-tracer] malformed JSON at line ${String(lineNumber)}:`, err);
        return null;
    }
};
const loadTrace = async (ndjsonPath) => {
    const content = await (0, promises_1.readFile)(ndjsonPath, 'utf-8');
    const lines = content.split('\n');
    let header = null;
    const statements = [];
    let result;
    let attachments = [];
    for (let i = 0; i < lines.length; i += 1) {
        const trimmed = lines[i].trim();
        if (!trimmed) {
            continue;
        }
        const record = parseLine(trimmed, i + 1);
        if (!record) {
            continue;
        }
        switch (record.kind) {
            case 'test-header':
                header = record.test;
                break;
            case 'statement':
                statements.push(record.statement);
                break;
            case 'test-result':
                result = record;
                break;
            case 'test-attachments':
                attachments = record.attachments;
                break;
            default:
                // Forward-compatible: unknown kinds are dropped silently.
                break;
        }
    }
    if (!header) {
        throw new Error(`No test-header record found in ${ndjsonPath}`);
    }
    return { header, statements, attachments, ...(result ? { result } : {}) };
};
exports.loadTrace = loadTrace;
/**
 * Rewrite each statement's `screenshot` from a bare filename
 * (`stmt-0007.png`) to a server-relative URL the SPA can fetch.
 * Walks the statement tree depth-first; pure (does not mutate input).
 */
const rewriteScreenshots = (statements, toUrl) => statements.map((stmt) => ({
    ...stmt,
    screenshot: stmt.screenshot ? toUrl(stmt.screenshot) : undefined,
    children: (0, exports.rewriteScreenshots)(stmt.children, toUrl),
}));
exports.rewriteScreenshots = rewriteScreenshots;
