"use strict";
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2024-2026 Gracker (Chris)
// This file is part of SmartPerfetto. See LICENSE for details.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.commitTurnOutputs = commitTurnOutputs;
/**
 * Per-turn persistence helper shared by `analyze` and `resume`.
 *
 * Both commands end a turn with the same fan-out: write conclusion +
 * per-turn markdown + HTML report + config + transcript + index entry,
 * then render the conclusion block and the completion summary. This
 * helper owns those eight steps so the call sites stay short and
 * uniform — any future addition (e.g. a `--no-report` flag) only
 * touches one place.
 */
const path = __importStar(require("path"));
const sessionStore_1 = require("../io/sessionStore");
const indexJson_1 = require("../io/indexJson");
const transcriptWriter_1 = require("../io/transcriptWriter");
function commitTurnOutputs(input) {
    const { paths, sp, renderer, sessionId, turn, query, result, config, turnMarkdown, reportAppendix, indexEntry } = input;
    const conclusion = result.result.conclusion || '';
    (0, sessionStore_1.writeConclusion)(sp, conclusion);
    (0, sessionStore_1.writeTurnMarkdown)(sp, turn, reportAppendix?.markdown ? `${turnMarkdown}\n\n${reportAppendix.markdown}` : turnMarkdown);
    writeAnalysisQualitySidecars(sp, turn, result);
    let turnReportPath;
    const reportHtml = result.reportHtml && reportAppendix?.html
        ? appendHtmlToBody(result.reportHtml, reportAppendix.html)
        : result.reportHtml;
    const reportPathForUser = result.reportHtml
        ? (turnReportPath = (0, sessionStore_1.writeTurnReportHtml)(sp, turn, reportHtml || ''), (0, sessionStore_1.writeReportHtml)(sp, reportHtml || ''), sp.report)
        : `(report generation failed${result.reportError ? `: ${result.reportError}` : ''})`;
    (0, sessionStore_1.writeConfig)(sp, config);
    (0, transcriptWriter_1.appendTranscriptTurn)(sp.transcript, {
        turn,
        timestamp: config.lastTurnAt,
        question: query,
        conclusionMd: conclusion,
        confidence: result.result.confidence,
        rounds: result.result.rounds,
        durationMs: result.result.totalDurationMs,
        reportFile: turnReportPath,
        error: result.reportError,
    });
    (0, indexJson_1.upsertSession)(paths, indexEntry);
    renderer.printConclusion(conclusion, {
        confidence: result.result.confidence,
        rounds: result.result.rounds,
        durationMs: result.result.totalDurationMs,
        claimVerification: result.result.claimVerificationResult
            ? {
                status: result.result.claimVerificationResult.status,
                checkedClaimCount: result.result.claimVerificationResult.checkedClaimCount,
                unsupportedClaimCount: result.result.claimVerificationResult.unsupportedClaimCount,
                issueCount: result.result.claimVerificationResult.issues?.length || 0,
            }
            : undefined,
    });
    renderer.printCompletion({
        reportPath: reportPathForUser,
        turnReportPath,
        sessionDir: sp.dir,
        sessionId,
        success: result.result.success,
    });
}
function writeAnalysisQualitySidecars(sp, turn, result) {
    const turnPrefix = path.join(sp.turnsDir, String(turn).padStart(3, '0'));
    (0, sessionStore_1.writeJsonFile)(sp, sp.claimSupport, result.result.claimSupport || []);
    (0, sessionStore_1.writeJsonFile)(sp, `${turnPrefix}.claim-support.json`, result.result.claimSupport || []);
    (0, sessionStore_1.writeJsonFile)(sp, sp.claimVerification, result.result.claimVerificationResult || null);
    (0, sessionStore_1.writeJsonFile)(sp, `${turnPrefix}.claim-verification.json`, result.result.claimVerificationResult || null);
    (0, sessionStore_1.writeJsonFile)(sp, sp.identityResolutions, result.result.identityResolutions || []);
    (0, sessionStore_1.writeJsonFile)(sp, `${turnPrefix}.identity-resolutions.json`, result.result.identityResolutions || []);
}
function appendHtmlToBody(html, appendixHtml) {
    const closeBody = /<\/body>\s*<\/html>\s*$/i;
    if (closeBody.test(html)) {
        return html.replace(closeBody, `${appendixHtml}\n</body>\n</html>`);
    }
    return `${html}\n${appendixHtml}`;
}
//# sourceMappingURL=turnPersistence.js.map