/**
 * HTML export of session traces after each query.
 *
 * Exports the main session JSONL and any subagent JSONLs to HTML after
 * each agent_end event. The /trace command opens them in the browser.
 */
import { existsSync, readdirSync, readFileSync, statSync } from 'fs';
import { basename, dirname, join } from 'path';
import { resolveForkTraceDir } from '../../app/session/fork-trace-paths.js';
import { exportFromFile } from '../export-html/index.js';
import { exportSessionToHtml } from '../export-html/session-export.js';
/** List fork-trace JSONL files for a session, sorted by modification time. */
function listForkTraceJsonls(sessionDir, sessionFile) {
    const traceDir = resolveForkTraceDir(sessionDir, sessionFile);
    if (!existsSync(traceDir))
        return [];
    try {
        return readdirSync(traceDir)
            .filter((file) => file.endsWith('.jsonl'))
            .map((file) => join(traceDir, file))
            .sort((a, b) => statSync(a).mtimeMs - statSync(b).mtimeMs);
    }
    catch {
        return [];
    }
}
/** Pick a human-readable title for a fork-trace HTML, falling back to a numeric label. */
function inferForkTraceTitle(jsonlPath, index) {
    try {
        const firstLine = readFileSync(jsonlPath, 'utf-8').split('\n')[0];
        const header = JSON.parse(firstLine);
        if (typeof header.id === 'string') {
            const match = /^fork-(.*)-\d+$/.exec(header.id);
            if (match?.[1])
                return `Fork: ${match[1]}`;
        }
    }
    catch { }
    return `Fork ${index}`;
}
/**
 * Export root + subagent traces and return structured artifact metadata.
 */
export async function exportTraceArtifacts(session) {
    const mainFile = session.sessionManager.getSessionFile();
    if (!mainFile)
        return [];
    const outputDir = dirname(mainFile);
    const artifacts = [];
    try {
        const mainBase = basename(mainFile, '.jsonl');
        const mainHtml = join(outputDir, `${mainBase}.html`);
        await exportSessionToHtml(session, mainHtml);
        artifacts.push({
            fileName: basename(mainHtml),
            htmlPath: mainHtml,
            jsonlPath: mainFile,
            isRoot: true
        });
    }
    catch {
        // Silently skip — export may fail if session is empty
    }
    const entries = session.sessionManager.getEntries();
    let subIndex = 0;
    for (const entry of entries) {
        if (entry.type !== 'message')
            continue;
        const msg = entry.message;
        if (msg?.role !== 'toolResult')
            continue;
        const subFile = msg?.details?.sessionFile;
        if (typeof subFile === 'string' && existsSync(subFile)) {
            try {
                subIndex++;
                const toolName = msg?.toolName;
                const title = toolName ? `Subagent: ${toolName}` : `Subagent ${subIndex}`;
                const subBase = basename(subFile, '.jsonl');
                const subHtml = join(outputDir, `${subBase}.html`);
                await exportFromFile(subFile, { outputPath: subHtml, title });
                artifacts.push({
                    fileName: basename(subHtml),
                    htmlPath: subHtml,
                    jsonlPath: subFile,
                    isRoot: false
                });
            }
            catch {
                // Skip failed subagent exports
            }
        }
    }
    let forkIndex = 0;
    for (const forkFile of listForkTraceJsonls(outputDir, mainFile)) {
        try {
            forkIndex++;
            const forkBase = basename(forkFile, '.jsonl');
            const forkHtml = join(outputDir, `${forkBase}.html`);
            await exportFromFile(forkFile, {
                outputPath: forkHtml,
                title: inferForkTraceTitle(forkFile, forkIndex)
            });
            artifacts.push({
                fileName: basename(forkHtml),
                htmlPath: forkHtml,
                jsonlPath: forkFile,
                isRoot: false
            });
        }
        catch {
            // Skip failed fork exports.
        }
    }
    return artifacts;
}
/**
 * Export main + subagent session JSONLs to HTML.
 * Returns all exported HTML paths, or empty array if nothing was exported.
 */
export async function exportDevTraces(session) {
    const artifacts = await exportTraceArtifacts(session);
    return artifacts.map((artifact) => artifact.htmlPath);
}
//# sourceMappingURL=trace-export.js.map