"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.applyPlanningCommandPersistedArtifactReminderWrites = applyPlanningCommandPersistedArtifactReminderWrites;
const artifact_reminder_1 = require("../../lib/license/artifact-reminder");
const command_write_summary_1 = require("../../lib/license/command-write-summary");
const license_resolution_1 = require("../../lib/license/license-resolution");
const reminder_state_1 = require("../../lib/license/reminder-state");
function applyPlanningCommandPersistedArtifactReminderWrites(options) {
    const commandWriteSummary = (0, command_write_summary_1.normalizeCommandWriteSummaryOutputMode)(options.commandWriteSummary, { format: options.format });
    const repositoryContext = {
        root: options.repositoryContext.root,
        detectionSource: options.repositoryContext.detectionSource,
        warnedAboutFallback: false
    };
    const commandCompletedAt = options.commandCompletedAt ?? new Date().toISOString();
    const licenseStatus = (0, license_resolution_1.resolveLicenseStatus)({
        repositoryContext
    });
    let cadenceReason;
    let cadenceError;
    let persistedReminderEligible = false;
    let stateWritten = false;
    try {
        const cadence = (0, reminder_state_1.applyReminderCadenceStateUpdate)({
            repositoryRoot: repositoryContext.root,
            commandCompletedAt,
            isEligibleCommand: false,
            suppressReminders: licenseStatus.suppresses_reminders,
            terminalReminderOutputEligible: (0, command_write_summary_1.shouldEmitHumanReadableCommandOutput)(commandWriteSummary),
            commandWriteSummary,
            pseudoRandomValue: options.pseudoRandomValue
        });
        cadenceReason = cadence.reason;
        persistedReminderEligible =
            cadence.persistedReminderEligible ||
                (cadence.terminalCadenceDecision?.postGraceCadenceEligible === true &&
                    commandWriteSummary.materialWrite &&
                    !commandWriteSummary.dryRun &&
                    commandWriteSummary.jsonOnly !== true &&
                    !licenseStatus.suppresses_reminders);
        stateWritten = cadence.stateWritten;
    }
    catch (error) {
        cadenceReason = "reminder-state-write-failed";
        cadenceError = error instanceof Error ? error.message : String(error);
    }
    const writes = (0, artifact_reminder_1.applyPersistedArtifactLicenseReminderWrites)({
        summary: commandWriteSummary,
        persistedReminderEligible,
        repositoryRoot: repositoryContext.root,
        currentDate: options.currentDate ?? commandCompletedAt,
        generatedAt: options.generatedAt ?? commandCompletedAt,
        random: options.random
    });
    return {
        cadenceReason,
        ...(cadenceError === undefined ? {} : { cadenceError }),
        persistedReminderEligible,
        stateWritten,
        commandWriteSummary,
        writes
    };
}
