"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.discoverLicenseSources = discoverLicenseSources;
exports.resolveLicenseInventoryProvenance = resolveLicenseInventoryProvenance;
exports.resolveLicenseStatus = resolveLicenseStatus;
const node_fs_1 = __importDefault(require("node:fs"));
const node_os_1 = __importDefault(require("node:os"));
const node_path_1 = __importDefault(require("node:path"));
const license_provenance_1 = require("./license-provenance");
const license_file_1 = require("./license-file");
const license_status_1 = require("./license-status");
const reminder_config_1 = require("./reminder-config");
function discoverLicenseSources(options = {}) {
    const env = options.env ?? process.env;
    const commandLicenseFile = normalizeOptionalInput(options.licenseFile);
    const environmentLicenseFile = normalizeOptionalInput(env.DAY_SHIFT_LICENSE_FILE);
    const hostLicensePath = options.hostLicensePath ?? getHostLicensePath(env, options.platform);
    const userLicenseDirectory = options.userLicenseDirectory ?? getUserLicenseDirectory(env, options.platform, options.homeDirectory);
    const candidates = [];
    if (commandLicenseFile !== undefined) {
        candidates.push({
            kind: 'single-file',
            source: 'command-input',
            label: '--license-file',
            configured: true,
            filePath: commandLicenseFile,
        });
    }
    else if (environmentLicenseFile !== undefined) {
        candidates.push({
            kind: 'single-file',
            source: 'environment',
            label: 'DAY_SHIFT_LICENSE_FILE',
            configured: true,
            filePath: environmentLicenseFile,
        });
    }
    else {
        candidates.push({
            kind: 'single-file',
            source: 'host-state',
            label: 'host-local automation path',
            configured: false,
            filePath: hostLicensePath,
        }, {
            kind: 'directory',
            source: 'user-local-state',
            label: 'user-local license directory',
            configured: false,
            directoryPath: userLicenseDirectory,
        });
    }
    candidates.push({
        kind: 'fallback',
        source: 'runtime-derived',
        label: 'unlicensed_fallback',
        configured: false,
    });
    return {
        commandLicenseFile,
        environmentLicenseFile,
        hostLicensePath,
        userLicenseDirectory,
        candidates,
    };
}
function resolveLicenseInventoryProvenance(options) {
    const resolved = resolveLicenseStatusCore(options);
    const hostLabelSource = normalizeOptionalInput(resolved.env.DAY_SHIFT_HOST_LABEL) === undefined ? 'hostname' : 'DAY_SHIFT_HOST_LABEL';
    return (0, license_provenance_1.createLicenseInventoryProvenance)({
        'license.resolution_order': summaryEntry(resolved.selectedAttempt.source, 'License resolution order: command input, DAY_SHIFT_LICENSE_FILE, host-local automation path, user-local license directory, unlicensed fallback.'),
        'license.effective_source': printedEntry(resolved.selectedAttempt.source, resolved.selectedAttempt.sourceDescription, resolved.selectedAttempt.label),
        'license.configured_path_source': summaryEntry(configuredPathSource(resolved.sourceDiscovery.commandLicenseFile, resolved.sourceDiscovery.environmentLicenseFile, resolved.selectedAttempt), configuredPathDescription(resolved.sourceDiscovery.commandLicenseFile, resolved.sourceDiscovery.environmentLicenseFile, resolved.selectedAttempt)),
        'license.user_directories': summaryEntry('user-local-state', `User-local license directory checked for installed *.json licenses; readable count=${resolved.readableInstalledLicenseCount}.`),
        'license.readable_installed_license_count': printedEntry('user-local-state', 'Count of readable installed user license files discovered while evaluating the user-local license directory.', resolved.readableInstalledLicenseCount),
        'license.selected_installed_license_id': redactedEntry('user-local-state', selectedInstalledLicenseDescription(resolved.statusResult.selected_installed_license_id)),
        'license.selected_suppressing_license_id': redactedEntry('user-local-state', selectedSuppressingLicenseDescription(resolved.statusResult.selected_suppressing_license_id)),
        'license.effective_status': printedEntry(resolved.statusResult.selected_source.source, resolved.selectedAttempt.sourceDescription, resolved.statusResult.effective_status),
        'license.reason_code': printedEntry(resolved.statusResult.selected_source.source, 'Machine-readable reason code from the canonical license status result.', resolved.statusResult.reason_code),
        'license.suppresses_reminders': printedEntry('runtime-derived', 'Reminder suppression decision from the canonical license status result.', resolved.statusResult.suppresses_reminders),
        'license.current_cli_version': printedEntry('runtime-derived', 'Current Day Shift CLI version used for license coverage checks.', resolved.statusResult.current_cli_version),
        'license.entitlement_kind': printedEntry(resolved.statusResult.selected_source.source, 'Safe license entitlement kind from parsed license payload metadata when available.', resolved.statusResult.entitlement_kind),
        'license.covered_release_line': availabilityEntry(resolved.statusResult.selected_source.source, 'Safe covered release line from parsed license entitlement when available.', resolved.statusResult.covered_release_line),
        'license.current_version_coverage_state': printedEntry(resolved.statusResult.selected_source.source, 'Current CLI version coverage state from safe entitlement metadata.', resolved.statusResult.current_version_coverage_state),
        'license.temporary_expiration_state': printedEntry(resolved.statusResult.selected_source.source, 'Temporary-license expiration state from safe expires_at metadata.', resolved.statusResult.temporary_expiration_state),
        'license.effective_coverage_path': printedEntry(resolved.statusResult.selected_source.source, 'Safe commercial coverage path from the canonical license status result.', resolved.statusResult.effective_coverage_path),
        'license.unlicensed_fallback': summaryEntry('runtime-derived', unlicensedFallbackDescription(resolved.selectedAttempt, resolved.statusResult)),
        'license.entitlement_summary': summaryEntry(resolved.selectedAttempt.source, 'Safe entitlement summary includes kind, release-line coverage, expiration state, and reminder suppression only.'),
        'license.previous_license_id_provenance': redactedEntry('user-local-state', resolved.statusResult.discounted_upgrade_provenance
            ? 'Discounted upgrade provenance is present and previous license IDs are redacted.'
            : 'No discounted upgrade provenance was available.'),
        'license.discounted_upgrade_provenance': summaryEntry('user-local-state', resolved.statusResult.discounted_upgrade_provenance
            ? 'Discounted upgrade provenance is present; previous license IDs remain redacted.'
            : 'No discounted upgrade provenance was available.'),
        'license.automation_host_paths': summaryEntry('host-state', 'Host-local automation license path checked without printing license payloads.'),
        'license.automation_host_label_source': summaryEntry(hostLabelSource === 'DAY_SHIFT_HOST_LABEL' ? 'environment' : 'host-state', `Automation host label source is ${hostLabelSource}; inventory does not print the host label value.`),
        'license.effective_automation_host_label': summaryEntry(hostLabelSource === 'DAY_SHIFT_HOST_LABEL' ? 'environment' : 'host-state', 'Effective automation host label is available only as a non-secret source summary.'),
        ...buildReminderInventoryEntries({
            env: resolved.env,
            suppressesReminders: resolved.statusResult.suppresses_reminders,
        }),
    }, resolved.statusResult);
}
function resolveLicenseStatus(options) {
    return resolveLicenseStatusCore(options).statusResult;
}
function resolveLicenseStatusCore(options) {
    const env = options.env ?? process.env;
    const sourceDiscovery = discoverLicenseSources({
        licenseFile: options.licenseFile,
        env,
        platform: options.platform,
        homeDirectory: options.homeDirectory,
        hostLicensePath: options.hostLicensePath,
        userLicenseDirectory: options.userLicenseDirectory,
    });
    let userDirectoryAttempt = null;
    let selectedAttempt = null;
    for (const candidate of sourceDiscovery.candidates) {
        if (candidate.kind === 'fallback') {
            selectedAttempt = createUnlicensedFallbackAttempt();
            break;
        }
        if (candidate.kind === 'single-file') {
            const attempt = readSingleLicenseFileAttempt({
                source: candidate.source,
                label: candidate.label,
                filePath: candidate.filePath,
                configured: candidate.configured,
            });
            if (attempt.configured || attempt.found) {
                selectedAttempt = attempt;
                break;
            }
            continue;
        }
        userDirectoryAttempt = readUserLicenseDirectoryAttempt(candidate.directoryPath, options.currentCliVersion);
        if (userDirectoryAttempt.found) {
            selectedAttempt = userDirectoryAttempt;
            break;
        }
    }
    selectedAttempt ??= createUnlicensedFallbackAttempt();
    const status = selectedAttempt.evaluatedStatus ??
        (0, license_status_1.evaluateSafeLicenseStatus)({
            payload: selectedAttempt.payload,
            signatureVerification: selectedAttempt.signatureVerification,
            configuredPathError: selectedAttempt.configured,
            malformed: selectedAttempt.malformed,
            currentCliVersion: options.currentCliVersion,
        });
    const statusResult = createLicenseStatusResultForAttempt(selectedAttempt, status);
    const readableInstalledLicenseCount = userDirectoryAttempt?.readableInstalledLicenseCount ??
        (selectedAttempt.source === 'user-local-state' ? selectedAttempt.readableInstalledLicenseCount : null) ??
        0;
    return {
        env,
        sourceDiscovery,
        selectedAttempt,
        userDirectoryAttempt,
        statusResult,
        readableInstalledLicenseCount,
    };
}
function buildReminderInventoryEntries(options) {
    const snapshot = readReminderStateSnapshot(options.env);
    const stateSourceDescription = reminderStateSourceDescription(snapshot);
    const runtimeSourceDescription = reminderRuntimeSourceDescription(snapshot);
    const stateDirectoryOverrideDescription = snapshot.stateDirectoryOverrideActive
        ? 'DAY_SHIFT_STATE_DIR is set for this invocation; reminder state identity uses the environment override without persisting it to config.'
        : 'No DAY_SHIFT_STATE_DIR override is active; reminder state identity uses the default user-local state directory.';
    return {
        'reminder.terminal_eligibility': summaryEntry('runtime-derived', options.suppressesReminders
            ? 'Terminal reminders are suppressed for this inventory run because the effective license suppresses reminders.'
            : 'Config inventory is read-only; terminal reminder eligibility is reported as policy provenance without advancing cadence.'),
        'reminder.grace_period_state': summaryEntry(snapshot.status === 'available' ? 'user-local-state' : 'product-policy', reminderGracePeriodDescription(snapshot)),
        'reminder.eligible_command_count': reminderPrintableCountEntry(snapshot, 'eligibleCommandCount', 'Eligible command count from local reminder state.'),
        'reminder.eligible_commands_since_last_reminder': reminderPrintableCountEntry(snapshot, 'eligibleCommandsSinceLastReminder', 'Eligible command count since the last terminal reminder from local reminder state.'),
        'reminder.last_reminder_at': summaryEntry(snapshot.status === 'available' ? 'user-local-state' : 'product-policy', reminderLastReminderDescription(snapshot)),
        'reminder.next_reminder_window': summaryEntry('runtime-derived', reminderNextWindowDescription(snapshot)),
        'reminder.state_location': summaryEntry(snapshot.stateDirectorySource === 'environment' ? 'environment' : 'user-local-state', stateSourceDescription),
        'reminder.state_directory_override_influence': summaryEntry(snapshot.stateDirectoryOverrideActive ? 'environment' : 'runtime-derived', stateDirectoryOverrideDescription),
        'reminder.cadence_state': summaryEntry(snapshot.status === 'available' ? 'user-local-state' : 'product-policy', runtimeSourceDescription),
        'reminder.invalid_license_banner_state': summaryEntry(snapshot.status === 'available' ? 'user-local-state' : 'product-policy', reminderInvalidLicenseBannerDescription(snapshot)),
        'reminder.fallback_license_reminder_placement': summaryEntry('product-policy', 'Fallback LICENSE-REMINDER.md placement is read-only policy provenance: create it only for an unlicensed material write with no eligible parent coordination artifact.'),
        'reminder.managed_region_ownership': summaryEntry('repository-state', 'Persisted artifact reminders are owned by stable managed reminder regions; config inventory reports ownership only and does not create or update regions.'),
        'reminder.stale_region_refresh_policy': printedEntry('product-policy', 'Stale managed reminder regions are refreshed in place only by eligible reminder-writing command behavior.', 'refresh managed regions older than thirty days'),
        'reminder.cadence_policy_constants': printedEntry('product-policy', 'Reminder cadence policy constants are product policy, not repository configuration.', 'grace: first 3 eligible commands or 30 minutes; after reminder: suppress 2, 40% chance on 3-4, force on 5'),
        'reminder.generated_fallback_files': summaryEntry('repository-state', 'Generated fallback LICENSE-REMINDER.md files are reminder artifacts owned by license/reminder behavior; inventory reports policy only and prints no generated body.'),
    };
}
function createLicenseStatusResultForAttempt(selectedAttempt, status) {
    return (0, license_status_1.createLicenseStatusResult)({
        evaluation: status,
        selectedSource: selectedSourceMetadata(selectedAttempt),
        configuredSource: configuredSourceState(selectedAttempt),
        fallbackMode: fallbackModeForAttempt(selectedAttempt, status),
        payload: selectedAttempt.payload,
    });
}
function selectedSourceMetadata(attempt) {
    return {
        source: attempt.source,
        label: attempt.label,
        configured: attempt.configured,
        found: attempt.found,
        readable: attempt.readable,
        license_path: attempt.licensePath,
    };
}
function configuredSourceState(attempt) {
    if (!attempt.configured) {
        return {
            configured: false,
            source: null,
            label: null,
            found: null,
            readable: null,
            license_path: null,
        };
    }
    return {
        configured: true,
        source: attempt.source,
        label: attempt.label,
        found: attempt.found,
        readable: attempt.readable,
        license_path: attempt.licensePath,
    };
}
function fallbackModeForAttempt(attempt, status) {
    if (status.suppressesReminders) {
        return 'not_needed';
    }
    if (attempt.configured) {
        return 'configured_source_no_fallback';
    }
    if (attempt.source === 'runtime-derived') {
        return 'unlicensed_fallback';
    }
    return 'non_suppressing_source';
}
function readReminderStateSnapshot(env) {
    const stateDir = getUserStateDirectory(env);
    const stateDirectoryOverrideActive = normalizeOptionalInput(env.DAY_SHIFT_STATE_DIR) !== undefined;
    const statePath = node_path_1.default.join(stateDir, reminder_config_1.REMINDER_STATE_FILE_NAME);
    const stateDirectorySource = stateDirectoryOverrideActive ? 'environment' : 'user-local-state';
    if (!node_fs_1.default.existsSync(statePath)) {
        return {
            status: 'missing',
            statePath,
            stateDirectoryOverrideActive,
            stateDirectorySource,
        };
    }
    try {
        const parsed = parseReminderStateFile(statePath);
        return {
            status: parsed === null ? 'malformed' : 'available',
            statePath,
            stateDirectoryOverrideActive,
            stateDirectorySource,
            ...(parsed === null ? {} : { state: parsed }),
        };
    }
    catch {
        return {
            status: 'unreadable',
            statePath,
            stateDirectoryOverrideActive,
            stateDirectorySource,
        };
    }
}
function parseReminderStateFile(statePath) {
    const parsed = JSON.parse(node_fs_1.default.readFileSync(statePath, 'utf8'));
    if (!isRecord(parsed) || parsed.reminder_state_schema_version !== reminder_config_1.REMINDER_STATE_SCHEMA_VERSION) {
        return null;
    }
    const firstEligibleCommandAt = stringValue(parsed.first_eligible_command_at);
    const eligibleCommandCount = nonNegativeIntegerValue(parsed.eligible_command_count);
    const lastReminderAt = nullableStringValue(parsed.last_reminder_at);
    const eligibleCommandsSinceLastReminder = nonNegativeIntegerValue(parsed.eligible_commands_since_last_reminder);
    const lastInvalidLicenseWarningAt = nullableStringValue(parsed.last_invalid_license_warning_at);
    if (firstEligibleCommandAt === undefined ||
        eligibleCommandCount === undefined ||
        lastReminderAt === undefined ||
        eligibleCommandsSinceLastReminder === undefined ||
        lastInvalidLicenseWarningAt === undefined) {
        return null;
    }
    return {
        firstEligibleCommandAt,
        eligibleCommandCount,
        lastReminderAt,
        eligibleCommandsSinceLastReminder,
        lastInvalidLicenseWarningAt,
    };
}
function reminderPrintableCountEntry(snapshot, field, availableDescription) {
    if (snapshot.status === 'available' && snapshot.state !== undefined) {
        return printedEntry('user-local-state', availableDescription, snapshot.state[field]);
    }
    if (snapshot.status === 'missing') {
        return printedEntry('product-policy', 'Reminder state is missing; inventory treats this as normal new-installation state with zero recorded eligible commands.', 0);
    }
    return {
        valueState: 'not-resolved',
        sourceKind: 'user-local-state',
        sourceDescription: reminderStateUnavailableDescription(snapshot),
        safeToPrintEffectiveValue: false,
    };
}
function reminderStateSourceDescription(snapshot) {
    const sourceLabel = snapshot.stateDirectoryOverrideActive
        ? 'DAY_SHIFT_STATE_DIR override'
        : 'default user-local state directory';
    if (snapshot.status === 'missing') {
        return `${sourceLabel} resolved ${reminder_config_1.REMINDER_STATE_FILE_NAME} lookup; state file is absent and treated as normal new-installation state.`;
    }
    if (snapshot.status === 'available') {
        return `${sourceLabel} resolved ${reminder_config_1.REMINDER_STATE_FILE_NAME} lookup; file was read for summary provenance without printing the path or raw payload.`;
    }
    return `${sourceLabel} resolved ${reminder_config_1.REMINDER_STATE_FILE_NAME} lookup; ${reminderStateUnavailableDescription(snapshot)}`;
}
function reminderRuntimeSourceDescription(snapshot) {
    if (snapshot.status === 'available' && snapshot.state !== undefined) {
        return `Reminder cadence summary: eligible count=${snapshot.state.eligibleCommandCount}, since last reminder=${snapshot.state.eligibleCommandsSinceLastReminder}, last reminder ${snapshot.state.lastReminderAt === null ? 'not recorded' : 'recorded'}.`;
    }
    if (snapshot.status === 'missing') {
        return 'Reminder cadence state is absent; inventory reports new-installation provenance without creating state.';
    }
    return reminderStateUnavailableDescription(snapshot);
}
function reminderGracePeriodDescription(snapshot) {
    if (snapshot.status === 'available' && snapshot.state !== undefined) {
        if (snapshot.state.eligibleCommandCount >= 3) {
            return `Grace period is complete by eligible-command count; first eligible command timestamp is present and not printed as raw state.`;
        }
        return `Grace period is active by eligible-command count (${snapshot.state.eligibleCommandCount}/3); thirty-minute first-command window also applies.`;
    }
    if (snapshot.status === 'missing') {
        return 'Reminder state is missing; inventory reports normal new-installation grace period without creating state.';
    }
    return reminderStateUnavailableDescription(snapshot);
}
function reminderLastReminderDescription(snapshot) {
    if (snapshot.status === 'available' && snapshot.state !== undefined) {
        return snapshot.state.lastReminderAt === null
            ? 'Reminder state is readable and no last reminder timestamp is recorded.'
            : 'Reminder state contains a last reminder timestamp; inventory reports timestamp presence without raw state payloads.';
    }
    if (snapshot.status === 'missing') {
        return 'Reminder state is missing; no last reminder timestamp is recorded yet.';
    }
    return reminderStateUnavailableDescription(snapshot);
}
function reminderNextWindowDescription(snapshot) {
    if (snapshot.status !== 'available' || snapshot.state === undefined) {
        return snapshot.status === 'missing'
            ? 'Next reminder window is in the new-installation grace period: after the third eligible command or thirty minutes after first eligible command.'
            : `Next reminder window is unavailable because ${reminderStateUnavailableDescription(snapshot)}`;
    }
    if (snapshot.state.eligibleCommandCount < 3) {
        return 'Next reminder window is still inside the new-installation grace period.';
    }
    if (snapshot.state.lastReminderAt === null) {
        return 'Next eligible unlicensed command after grace is the first reminder window.';
    }
    const nextEligibleAfterLastReminder = snapshot.state.eligibleCommandsSinceLastReminder + 1;
    if (nextEligibleAfterLastReminder <= 2) {
        return `Next eligible command remains suppressed by the two-command post-reminder window (${nextEligibleAfterLastReminder}/2).`;
    }
    if (nextEligibleAfterLastReminder <= 4) {
        return `Next eligible command is in the deterministic 40% reminder chance window (${nextEligibleAfterLastReminder}/4).`;
    }
    return 'Next eligible command is in the forced fifth-command reminder window.';
}
function reminderInvalidLicenseBannerDescription(snapshot) {
    if (snapshot.status === 'available' && snapshot.state !== undefined) {
        return snapshot.state.lastInvalidLicenseWarningAt === null
            ? 'Reminder state is readable and no invalid-license banner timestamp is recorded.'
            : 'Reminder state includes invalid-license banner timestamp presence without printing raw state.';
    }
    if (snapshot.status === 'missing') {
        return 'Reminder state is missing; no invalid-license banner state is recorded yet.';
    }
    return reminderStateUnavailableDescription(snapshot);
}
function reminderStateUnavailableDescription(snapshot) {
    if (snapshot.status === 'malformed') {
        return 'reminder state is readable but malformed; raw payload is omitted and inventory reports diagnostic provenance only.';
    }
    if (snapshot.status === 'unreadable') {
        return 'reminder state exists but could not be read; raw payload is omitted and inventory reports diagnostic provenance only.';
    }
    return 'reminder state is unavailable.';
}
function readSingleLicenseFileAttempt(options) {
    if (!node_fs_1.default.existsSync(options.filePath)) {
        return {
            source: options.source,
            label: options.label,
            configured: options.configured,
            found: false,
            readable: false,
            malformed: false,
            readableInstalledLicenseCount: null,
            payload: null,
            signatureVerification: null,
            licensePath: options.filePath,
            sourceDescription: `${options.label} did not resolve to an existing license file.`,
        };
    }
    try {
        const parsed = (0, license_file_1.parseLicenseFile)(options.filePath);
        const payload = parsed.ok ? parsed.parsed.safePayload : null;
        const signatureVerification = parsed.ok ? (0, license_file_1.verifyLicenseFileSignature)(parsed.parsed) : null;
        return {
            source: options.source,
            label: options.label,
            configured: options.configured,
            found: true,
            readable: true,
            malformed: parsed.malformed,
            readableInstalledLicenseCount: null,
            payload,
            signatureVerification,
            licensePath: options.filePath,
            sourceDescription: parsed.malformed
                ? `${options.label} resolved to a readable but malformed license file.`
                : `${options.label} resolved to a readable license file; raw payload and signature were not printed.`,
        };
    }
    catch {
        return {
            source: options.source,
            label: options.label,
            configured: options.configured,
            found: true,
            readable: false,
            malformed: false,
            readableInstalledLicenseCount: null,
            payload: null,
            signatureVerification: null,
            licensePath: options.filePath,
            sourceDescription: `${options.label} resolved to a license file that could not be read.`,
        };
    }
}
function readUserLicenseDirectoryAttempt(directoryPath, currentCliVersion) {
    if (!node_fs_1.default.existsSync(directoryPath)) {
        return {
            source: 'user-local-state',
            label: 'user-local license directory',
            configured: false,
            found: false,
            readable: false,
            malformed: false,
            readableInstalledLicenseCount: 0,
            payload: null,
            signatureVerification: null,
            licensePath: null,
            sourceDescription: 'User-local license directory was not present; inventory used unlicensed fallback.',
        };
    }
    try {
        const filenames = node_fs_1.default
            .readdirSync(directoryPath)
            .filter((filename) => filename.endsWith('.json'))
            .sort();
        let readableInstalledLicenseCount = 0;
        let selectedAttempt = null;
        for (const filename of filenames) {
            const licensePath = node_path_1.default.join(directoryPath, filename);
            try {
                const parsed = (0, license_file_1.parseLicenseFile)(licensePath);
                readableInstalledLicenseCount += 1;
                const payload = parsed.ok ? parsed.parsed.safePayload : null;
                const signatureVerification = parsed.ok ? (0, license_file_1.verifyLicenseFileSignature)(parsed.parsed) : null;
                const evaluatedStatus = (0, license_status_1.evaluateSafeLicenseStatus)({
                    payload,
                    signatureVerification,
                    configuredPathError: false,
                    malformed: parsed.malformed,
                    currentCliVersion,
                });
                const candidateAttempt = {
                    source: 'user-local-state',
                    label: 'user-local license directory',
                    configured: false,
                    found: true,
                    readable: true,
                    malformed: parsed.malformed,
                    readableInstalledLicenseCount,
                    payload,
                    signatureVerification,
                    evaluatedStatus,
                    licensePath,
                    sourceDescription: `User-local license directory contained ${readableInstalledLicenseCount} readable *.json license file(s).`,
                };
                if (selectedAttempt === null ||
                    compareDirectoryCandidateStatus(evaluatedStatus, selectedAttempt.evaluatedStatus) < 0) {
                    selectedAttempt = candidateAttempt;
                }
            }
            catch {
                continue;
            }
        }
        if (selectedAttempt !== null) {
            return {
                ...selectedAttempt,
                readableInstalledLicenseCount,
                sourceDescription: userLicenseDirectoryDescription(readableInstalledLicenseCount, selectedAttempt.evaluatedStatus),
            };
        }
        return {
            source: 'user-local-state',
            label: 'user-local license directory',
            configured: false,
            found: readableInstalledLicenseCount > 0,
            readable: true,
            malformed: false,
            readableInstalledLicenseCount,
            payload: null,
            signatureVerification: null,
            licensePath: null,
            sourceDescription: `User-local license directory contained ${readableInstalledLicenseCount} readable *.json license file(s).`,
        };
    }
    catch {
        return {
            source: 'user-local-state',
            label: 'user-local license directory',
            configured: false,
            found: true,
            readable: false,
            malformed: false,
            readableInstalledLicenseCount: 0,
            payload: null,
            signatureVerification: null,
            licensePath: null,
            sourceDescription: 'User-local license directory could not be read; inventory used unlicensed fallback.',
        };
    }
}
function compareDirectoryCandidateStatus(left, right) {
    if (right === undefined) {
        return -1;
    }
    return directoryCandidateRank(left) - directoryCandidateRank(right);
}
function directoryCandidateRank(status) {
    if (status.suppressesReminders) {
        return 0;
    }
    switch (status.reasonCode) {
        case 'version_not_covered':
            return 10;
        case 'expired_trial':
            return 20;
        case 'missing_required_feature':
            return 30;
        case 'wrong_product':
            return 40;
        case 'malformed':
            return 50;
        case 'unsupported_algorithm':
        case 'unsupported_key_id':
        case 'invalid_signature':
            return 60;
        case 'verification_not_available':
            return 70;
        case 'missing':
            return 80;
        case 'valid':
            return 90;
    }
}
function userLicenseDirectoryDescription(readableInstalledLicenseCount, status) {
    const selectionDescription = status?.suppressesReminders
        ? 'a suppressing license was selected for the current CLI version'
        : 'no suppressing license was selected for the current CLI version';
    return `User-local license directory contained ${readableInstalledLicenseCount} readable *.json license file(s); ${selectionDescription}.`;
}
function createUnlicensedFallbackAttempt() {
    return {
        source: 'runtime-derived',
        label: 'unlicensed_fallback',
        configured: false,
        found: false,
        readable: false,
        malformed: false,
        readableInstalledLicenseCount: 0,
        payload: null,
        signatureVerification: null,
        licensePath: null,
        sourceDescription: 'No configured, host-local, or user-local suppressing license was available; inventory used unlicensed fallback.',
    };
}
function printedEntry(sourceKind, sourceDescription, effectiveValue) {
    return {
        valueState: 'available',
        sourceKind,
        sourceDescription,
        effectiveValue,
        safeToPrintEffectiveValue: true,
    };
}
function availabilityEntry(sourceKind, sourceDescription, effectiveValue) {
    if (effectiveValue === null || effectiveValue === undefined) {
        return {
            valueState: 'not-resolved',
            sourceKind,
            sourceDescription,
            safeToPrintEffectiveValue: false,
        };
    }
    return printedEntry(sourceKind, sourceDescription, effectiveValue);
}
function summaryEntry(sourceKind, sourceDescription) {
    return {
        valueState: 'available',
        sourceKind,
        sourceDescription,
        safeToPrintEffectiveValue: false,
    };
}
function redactedEntry(sourceKind, sourceDescription) {
    return {
        valueState: 'not-resolved',
        sourceKind,
        sourceDescription,
        safeToPrintEffectiveValue: false,
    };
}
function configuredPathSource(commandLicenseFile, environmentLicenseFile, selectedAttempt) {
    if (commandLicenseFile !== undefined) {
        return 'command-input';
    }
    if (environmentLicenseFile !== undefined) {
        return 'environment';
    }
    return selectedAttempt.source === 'host-state' ? 'host-state' : 'runtime-derived';
}
function configuredPathDescription(commandLicenseFile, environmentLicenseFile, selectedAttempt) {
    if (commandLicenseFile !== undefined) {
        return selectedAttempt.sourceDescription.includes('--license-file')
            ? selectedAttempt.sourceDescription
            : '--license-file was supplied; lower-priority license sources were not used.';
    }
    if (environmentLicenseFile !== undefined) {
        return selectedAttempt.sourceDescription.includes('DAY_SHIFT_LICENSE_FILE')
            ? selectedAttempt.sourceDescription
            : 'DAY_SHIFT_LICENSE_FILE was supplied; lower-priority license sources were not used.';
    }
    if (selectedAttempt.source === 'host-state') {
        return selectedAttempt.sourceDescription;
    }
    return 'No explicit configured license path was supplied.';
}
function selectedInstalledLicenseDescription(selectedInstalledLicenseId) {
    if (selectedInstalledLicenseId === null) {
        return 'No installed license ID is available for inventory output.';
    }
    return 'An installed license ID is available and redacted from inventory output.';
}
function selectedSuppressingLicenseDescription(selectedSuppressingLicenseId) {
    if (selectedSuppressingLicenseId === null) {
        return 'No suppressing license ID is available for inventory output.';
    }
    return 'A suppressing license ID is available and redacted from inventory output.';
}
function unlicensedFallbackDescription(selectedAttempt, statusResult) {
    if (statusResult.suppresses_reminders) {
        return 'Unlicensed fallback was not used because a suppressing license was selected.';
    }
    if (selectedAttempt.configured) {
        return 'Configured license evidence was preserved; lower-priority fallback sources were not used.';
    }
    return 'No suppressing license was available; CLI remains in unlicensed fallback mode.';
}
function getHostLicensePath(env, platform = process.platform) {
    if (platform === 'win32') {
        const programData = normalizeOptionalInput(env.PROGRAMDATA) ?? 'C:\\ProgramData';
        return node_path_1.default.win32.join(programData, 'DayShift', 'license.json');
    }
    return '/etc/day-shift/license.json';
}
function getUserLicenseDirectory(env, platform = process.platform, homeDirectory = node_os_1.default.homedir()) {
    if (platform === 'darwin') {
        return node_path_1.default.posix.join(homeDirectory, 'Library', 'Application Support', 'day-shift', 'licenses');
    }
    if (platform === 'win32') {
        const appData = normalizeOptionalInput(env.APPDATA) ?? node_path_1.default.win32.join(homeDirectory, 'AppData', 'Roaming');
        return node_path_1.default.win32.join(appData, 'DayShift', 'licenses');
    }
    const configHome = normalizeOptionalInput(env.XDG_CONFIG_HOME) ?? node_path_1.default.posix.join(homeDirectory, '.config');
    return node_path_1.default.posix.join(configHome, 'day-shift', 'licenses');
}
function getUserStateDirectory(env) {
    const stateDir = normalizeOptionalInput(env.DAY_SHIFT_STATE_DIR);
    if (stateDir !== undefined) {
        return stateDir;
    }
    if (process.platform === 'darwin') {
        return node_path_1.default.join(node_os_1.default.homedir(), 'Library', 'Application Support', 'day-shift');
    }
    if (process.platform === 'win32') {
        return node_path_1.default.join(env.APPDATA ?? node_path_1.default.join(node_os_1.default.homedir(), 'AppData', 'Roaming'), 'DayShift');
    }
    return node_path_1.default.join(env.XDG_CONFIG_HOME ?? node_path_1.default.join(node_os_1.default.homedir(), '.config'), 'day-shift');
}
function normalizeOptionalInput(value) {
    if (value === undefined || value.trim() === '') {
        return undefined;
    }
    return value;
}
function isRecord(value) {
    return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function stringValue(value) {
    return typeof value === 'string' ? value : undefined;
}
function nullableStringValue(value) {
    if (value === null) {
        return null;
    }
    return stringValue(value);
}
function nonNegativeIntegerValue(value) {
    return Number.isInteger(value) && typeof value === 'number' && value >= 0 ? value : undefined;
}
