"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLicenseStatusCommand = createLicenseStatusCommand;
const errors_1 = require("../../../lib/errors");
const output_1 = require("../../../lib/output");
const runtime_contract_1 = require("../../../lib/runtime/runtime-contract");
const license_resolution_1 = require("../../../lib/license/license-resolution");
const license_status_1 = require("../../../lib/license/license-status");
const reminder_state_1 = require("../../../lib/license/reminder-state");
const license_guidance_1 = require("../../../lib/license/license-guidance");
const global_format_1 = require("../global-format");
async function createLicenseStatusCommand() {
    const { Command } = await import('commander');
    const command = new Command('status');
    command
        .description('Report license and reminder-policy diagnostics without writing state.')
        .option('--license-file <path>', 'Use a license file for this status run without writing config.')
        .addHelpText('after', [
        '',
        'Commercial guidance:',
        ...(0, license_guidance_1.renderLicenseWebsiteGuidanceLines)().map((line) => `  ${line}`),
        '  Automation hosts may use DAY_SHIFT_HOST_LABEL for a stable customer-managed label; status reports diagnostics only.',
    ].join('\n'))
        .action((_, commandInstance) => {
        const requestedFormat = commandInstance.optsWithGlobals?.().format ?? (0, global_format_1.getGlobalFormat)(commandInstance);
        const format = (0, output_1.resolveOutputFormat)(requestedFormat);
        if (format === null) {
            throw (0, errors_1.createUnsupportedOutputFormatError)({
                received: requestedFormat,
                commandBoundary: 'license status command output format',
            });
        }
        const commandOptions = commandInstance.opts();
        const repositoryDetection = (0, runtime_contract_1.detectRepositoryRoot)();
        const repositoryContext = (0, runtime_contract_1.createRepositoryContext)(repositoryDetection, false);
        const licenseStatus = (0, license_resolution_1.resolveLicenseStatus)({
            repositoryContext,
            licenseFile: commandOptions.licenseFile,
        });
        const licenseSources = (0, license_resolution_1.discoverLicenseSources)({
            licenseFile: commandOptions.licenseFile,
        });
        const reminderDiagnostics = (0, reminder_state_1.createReminderStatusDiagnostics)({
            repositoryRoot: repositoryContext.root,
            licenseStatus,
            commandCompletedAt: new Date().toISOString(),
        });
        const exitCode = (0, license_status_1.getLicenseStatusExitCode)(licenseStatus);
        const data = createLicenseStatusCommandData(licenseStatus, reminderDiagnostics, exitCode);
        (0, output_1.emitSuccess)({
            command: 'license status',
            format,
            text: renderLicenseStatusText(data, licenseSources.hostLicensePath),
            data,
        });
        getRootCommand(commandInstance ?? command).runtimeExitCode = exitCode === 0 ? errors_1.RuntimeExitCode.SUCCESS : exitCode;
    });
    return command;
}
function createLicenseStatusCommandData(status, reminderDiagnostics, exitCode) {
    return {
        effective_status: status.effective_status,
        reason_code: status.reason_code,
        license_path: status.license_path,
        fallback_mode: status.fallback_mode,
        suppresses_reminders: status.suppresses_reminders,
        current_cli_version: status.current_cli_version,
        entitlement_kind: status.entitlement_kind,
        covered_release_line: status.covered_release_line,
        current_version_coverage_state: status.current_version_coverage_state,
        temporary_expiration_state: status.temporary_expiration_state,
        effective_coverage_path: status.effective_coverage_path,
        discounted_upgrade_provenance: status.discounted_upgrade_provenance,
        selected_source: { ...status.selected_source },
        configured_source: { ...status.configured_source },
        configured_license_diagnostic: status.configured_license_diagnostic === null ? null : { ...status.configured_license_diagnostic },
        diagnostics: { ...status.diagnostics },
        reminder_diagnostics: reminderDiagnostics,
        read_only: true,
        exit_code: exitCode,
    };
}
function renderLicenseStatusText(data, hostLicensePath) {
    const configuredDiagnostic = data.configured_license_diagnostic;
    const reminder = data.reminder_diagnostics;
    const warning = reminder.warning_throttle;
    return [
        (0, output_1.renderTerminalSection)({
            heading: 'License status',
            headingStyle: 'title',
            fields: [
                { label: 'Effective status', value: data.effective_status },
                { label: 'Reason code', value: data.reason_code },
                { label: 'Suppresses reminders', value: data.suppresses_reminders },
                { label: 'Fallback mode', value: data.fallback_mode },
                { label: 'License path', value: data.license_path },
                { label: 'Coverage path', value: data.effective_coverage_path },
                { label: 'Current CLI version', value: data.current_cli_version },
                { label: 'Entitlement kind', value: data.entitlement_kind },
                { label: 'Covered release line', value: data.covered_release_line },
                { label: 'Version coverage state', value: data.current_version_coverage_state },
                { label: 'Temporary expiration state', value: data.temporary_expiration_state },
                { label: 'Upgrade provenance', value: data.discounted_upgrade_provenance },
                { label: 'Exit code', value: data.exit_code },
            ],
        }),
        (0, output_1.renderTerminalSection)({
            heading: 'Selected source',
            headingStyle: 'section',
            fields: [
                { label: 'Source', value: data.selected_source.source },
                { label: 'Label', value: data.selected_source.label },
                { label: 'Configured', value: data.selected_source.configured },
                { label: 'Found', value: data.selected_source.found },
                { label: 'Readable', value: data.selected_source.readable },
                { label: 'License path', value: data.selected_source.license_path },
            ],
        }),
        (0, output_1.renderTerminalSection)({
            heading: 'Configured source',
            headingStyle: 'section',
            fields: [
                { label: 'Configured', value: data.configured_source.configured },
                { label: 'Source', value: data.configured_source.source },
                { label: 'Label', value: data.configured_source.label },
                { label: 'Found', value: data.configured_source.found },
                { label: 'Readable', value: data.configured_source.readable },
                { label: 'License path', value: data.configured_source.license_path },
                { label: 'Failure kind', value: configuredDiagnostic?.failure_kind ?? null },
                {
                    label: 'Configured diagnostic exit code',
                    value: configuredDiagnostic?.planned_license_status_exit_code ?? null,
                },
            ],
        }),
        (0, output_1.renderTerminalSection)({
            heading: 'Reminder diagnostics',
            headingStyle: 'section',
            fields: [
                { label: 'Read status', value: reminder.read_status },
                { label: 'Recovery reason', value: reminder.recovery_reason },
                { label: 'Grace period state', value: reminder.grace_period_state },
                { label: 'Eligible command count', value: reminder.eligible_command_count },
                { label: 'First eligible command at', value: reminder.first_eligible_command_at },
                { label: 'Last reminder at', value: reminder.last_reminder_at },
                { label: 'Eligible commands since last reminder', value: reminder.eligible_commands_since_last_reminder },
                { label: 'Last invalid-license warning at', value: reminder.last_invalid_license_warning_at },
                { label: 'Next reminder window', value: reminder.next_reminder_window.kind },
                {
                    label: 'Next window eligible command ordinal',
                    value: reminder.next_reminder_window.eligible_command_ordinal_since_last_reminder,
                },
                { label: 'Random show threshold', value: reminder.next_reminder_window.random_show_threshold },
            ],
        }),
        (0, output_1.renderTerminalSection)({
            heading: 'Warning throttle',
            headingStyle: 'section',
            fields: [
                { label: 'Warning eligible', value: warning.warning_eligible },
                { label: 'Would show on human-readable command', value: warning.warning_visible },
                { label: 'Warning suppressed', value: warning.warning_suppressed },
                { label: 'Decision reason', value: warning.decision_reason },
                { label: 'Last invalid-license warning at', value: warning.last_invalid_license_warning_at },
            ],
        }),
        (0, output_1.renderTerminalSection)({
            heading: 'Commercial guidance',
            headingStyle: 'section',
            lines: [...(0, license_guidance_1.renderLicenseWebsiteGuidanceLines)(), (0, license_guidance_1.renderAutomationHostGuidanceLine)(hostLicensePath)],
        }),
        (0, output_1.renderTerminalBoundary)({ kind: 'read-only' }),
    ].join('\n\n');
}
function getRootCommand(commandInstance) {
    let current = commandInstance;
    while (current.parent !== undefined && current.parent !== null) {
        current = current.parent;
    }
    return current;
}
