"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LICENSE_STATUS_CONFIGURED_IO_EXIT_CODE = exports.LICENSE_STATUS_CONFIGURED_FAILURE_EXIT_CODE = exports.DAY_SHIFT_LICENSE_PRODUCT = exports.COMMERCIAL_REMINDERS_SUPPRESSED_FEATURE = void 0;
exports.evaluateSafeLicenseStatus = evaluateSafeLicenseStatus;
exports.createLicenseStatusResult = createLicenseStatusResult;
exports.getLicenseStatusExitCode = getLicenseStatusExitCode;
exports.evaluateLicensePayloadEligibility = evaluateLicensePayloadEligibility;
exports.evaluateReleaseLineEntitlement = evaluateReleaseLineEntitlement;
const runtime_contract_1 = require("../runtime/runtime-contract");
exports.COMMERCIAL_REMINDERS_SUPPRESSED_FEATURE = "commercial_reminders_suppressed";
exports.DAY_SHIFT_LICENSE_PRODUCT = "day-shift";
const SUPPORTED_MVP_LICENSE_TYPES = [
    "individual",
    "company_seat",
    "automation_host",
    "company_site",
    "trial",
    "internal"
];
const PURCHASED_COMMERCIAL_LICENSE_TYPES = new Set([
    "individual",
    "company_seat",
    "automation_host",
    "company_site"
]);
const MVP_ENTITLEMENT_KIND = "perpetual_release_line";
exports.LICENSE_STATUS_CONFIGURED_FAILURE_EXIT_CODE = 2;
exports.LICENSE_STATUS_CONFIGURED_IO_EXIT_CODE = 3;
function evaluateSafeLicenseStatus(options) {
    const currentCliVersion = options.currentCliVersion ?? runtime_contract_1.CLI_VERSION;
    if (options.malformed) {
        return createStatus({
            effectiveStatus: options.configuredPathError ? "configured-license-error" : "invalid-license",
            reasonCode: "malformed",
            currentCliVersion
        });
    }
    if (options.payload === null) {
        return createStatus({
            effectiveStatus: options.configuredPathError ? "configured-license-error" : "unlicensed",
            reasonCode: "missing",
            currentCliVersion
        });
    }
    if (options.signatureVerification === null || options.signatureVerification === undefined) {
        return createStatus({
            effectiveStatus: nonSuppressingStatus(options.configuredPathError),
            reasonCode: "verification_not_available",
            currentCliVersion
        });
    }
    if (!options.signatureVerification.ok) {
        return createStatus({
            effectiveStatus: nonSuppressingStatus(options.configuredPathError),
            reasonCode: reasonCodeFromSignatureVerificationFailure(options.signatureVerification.reason),
            currentCliVersion,
            entitlementKind: options.payload.entitlementKind ?? "unknown",
            coveredReleaseLine: options.payload.entitlementVersion ?? null,
            currentVersionCoverageState: evaluateReleaseLineEntitlement(currentCliVersion, options.payload.entitlementVersion),
            temporaryExpirationState: getTemporaryExpirationState(options.payload.licenseType, options.payload.expiresAt, options.currentTimeMs),
            effectiveCoveragePath: coveragePathFromLicenseType(options.payload.licenseType),
            selectedInstalledLicenseId: options.payload.licenseId ?? null,
            discountedUpgradeProvenance: hasDiscountedUpgradeProvenance(options.payload)
        });
    }
    const eligibility = evaluateLicensePayloadEligibility(options.payload);
    if (!eligibility.ok) {
        return createStatus({
            effectiveStatus: nonSuppressingStatus(options.configuredPathError),
            reasonCode: eligibility.reasonCode,
            currentCliVersion,
            entitlementKind: options.payload.entitlementKind ?? "unknown",
            coveredReleaseLine: options.payload.entitlementVersion ?? null,
            effectiveCoveragePath: "unlicensed",
            selectedInstalledLicenseId: options.payload.licenseId ?? null,
            discountedUpgradeProvenance: hasDiscountedUpgradeProvenance(options.payload)
        });
    }
    const coverageState = evaluateReleaseLineEntitlement(currentCliVersion, options.payload.entitlementVersion);
    const expirationState = getTemporaryExpirationState(options.payload.licenseType, options.payload.expiresAt, options.currentTimeMs);
    const entitlementKind = options.payload.entitlementKind ?? "unknown";
    const coveredReleaseLine = options.payload.entitlementVersion ?? null;
    const selectedInstalledLicenseId = options.payload.licenseId ?? null;
    const discountedUpgradeProvenance = hasDiscountedUpgradeProvenance(options.payload);
    if (coverageState === "not-covered") {
        return createStatus({
            effectiveStatus: nonSuppressingStatus(options.configuredPathError),
            reasonCode: "version_not_covered",
            currentCliVersion,
            entitlementKind,
            coveredReleaseLine,
            currentVersionCoverageState: coverageState,
            temporaryExpirationState: expirationState,
            effectiveCoveragePath: "unlicensed",
            selectedInstalledLicenseId,
            discountedUpgradeProvenance
        });
    }
    if (coverageState !== "covered") {
        return createStatus({
            effectiveStatus: nonSuppressingStatus(options.configuredPathError),
            reasonCode: "malformed",
            currentCliVersion,
            entitlementKind,
            coveredReleaseLine,
            currentVersionCoverageState: coverageState,
            temporaryExpirationState: expirationState,
            effectiveCoveragePath: "unlicensed",
            selectedInstalledLicenseId,
            discountedUpgradeProvenance
        });
    }
    if (expirationState === "expired") {
        return createStatus({
            effectiveStatus: nonSuppressingStatus(options.configuredPathError),
            reasonCode: "expired_trial",
            currentCliVersion,
            entitlementKind,
            coveredReleaseLine,
            currentVersionCoverageState: coverageState,
            temporaryExpirationState: expirationState,
            effectiveCoveragePath: "unlicensed",
            selectedInstalledLicenseId,
            discountedUpgradeProvenance
        });
    }
    return createStatus({
        effectiveStatus: "licensed",
        reasonCode: "valid",
        currentCliVersion,
        entitlementKind,
        coveredReleaseLine,
        currentVersionCoverageState: coverageState,
        temporaryExpirationState: expirationState,
        effectiveCoveragePath: coveragePathFromLicenseType(options.payload.licenseType),
        suppressesReminders: true,
        selectedInstalledLicenseId,
        selectedSuppressingLicenseId: selectedInstalledLicenseId,
        discountedUpgradeProvenance
    });
}
function createLicenseStatusResult(options) {
    const licensePath = options.selectedSource.license_path;
    return {
        effective_status: options.evaluation.effectiveStatus,
        reason_code: options.evaluation.reasonCode,
        suppresses_reminders: options.evaluation.suppressesReminders,
        selected_source: { ...options.selectedSource },
        configured_source: { ...options.configuredSource },
        fallback_mode: options.fallbackMode,
        license_path: licensePath,
        current_cli_version: options.evaluation.currentCliVersion,
        entitlement_kind: options.evaluation.entitlementKind,
        covered_release_line: options.evaluation.coveredReleaseLine,
        current_version_coverage_state: options.evaluation.currentVersionCoverageState,
        temporary_expiration_state: options.evaluation.temporaryExpirationState,
        effective_coverage_path: options.evaluation.effectiveCoveragePath,
        selected_installed_license_id: options.evaluation.selectedInstalledLicenseId,
        selected_suppressing_license_id: options.evaluation.selectedSuppressingLicenseId,
        discounted_upgrade_provenance: options.evaluation.discountedUpgradeProvenance,
        effective_license: createEffectiveSuppressingLicenseMetadata(options.evaluation, options.payload ?? null, licensePath),
        configured_license_diagnostic: createConfiguredLicenseDiagnostic(options),
        diagnostics: {
            configured_source_error: options.evaluation.effectiveStatus === "configured-license-error",
            invalid_license: options.evaluation.effectiveStatus === "invalid-license",
            selected_source_found: options.selectedSource.found,
            selected_source_readable: options.selectedSource.readable
        }
    };
}
function getLicenseStatusExitCode(status) {
    const diagnostic = status.configured_license_diagnostic;
    if (diagnostic === null) {
        return 0;
    }
    return diagnostic.planned_license_status_exit_code;
}
function createConfiguredLicenseDiagnostic(options) {
    const configuredSource = options.configuredSource;
    if (options.evaluation.effectiveStatus !== "configured-license-error" ||
        options.fallbackMode !== "configured_source_no_fallback" ||
        !configuredSource.configured ||
        configuredSource.license_path === null ||
        !isConfigurableLicenseSource(configuredSource.source) ||
        !isConfiguredLicenseLabel(configuredSource.label)) {
        return null;
    }
    return {
        source: configuredSource.source,
        label: configuredSource.label,
        configured_path: configuredSource.license_path,
        reason_code: options.evaluation.reasonCode,
        failure_kind: configuredDiagnosticFailureKind(configuredSource, options.evaluation.reasonCode),
        suppresses_reminders: false,
        fallback_mode: "configured_source_no_fallback",
        normal_commands_may_continue: true,
        planned_license_status_exit_code: configuredLicenseStatusExitCode(configuredDiagnosticFailureKind(configuredSource, options.evaluation.reasonCode))
    };
}
function configuredLicenseStatusExitCode(failureKind) {
    return failureKind === "missing" || failureKind === "unreadable"
        ? exports.LICENSE_STATUS_CONFIGURED_IO_EXIT_CODE
        : exports.LICENSE_STATUS_CONFIGURED_FAILURE_EXIT_CODE;
}
function configuredDiagnosticFailureKind(configuredSource, reasonCode) {
    if (configuredSource.found === false) {
        return "missing";
    }
    if (configuredSource.readable === false) {
        return "unreadable";
    }
    if (reasonCode === "malformed") {
        return "malformed";
    }
    return "non_suppressing_license";
}
function isConfigurableLicenseSource(source) {
    return source === "command-input" || source === "environment";
}
function isConfiguredLicenseLabel(label) {
    return label === "--license-file" || label === "DAY_SHIFT_LICENSE_FILE";
}
function createStatus(options) {
    return {
        effectiveStatus: options.effectiveStatus,
        reasonCode: options.reasonCode,
        suppressesReminders: options.suppressesReminders ?? false,
        currentCliVersion: options.currentCliVersion,
        entitlementKind: options.entitlementKind ?? "unlicensed",
        coveredReleaseLine: options.coveredReleaseLine ?? null,
        currentVersionCoverageState: options.currentVersionCoverageState ?? "not-applicable",
        temporaryExpirationState: options.temporaryExpirationState ?? "not-applicable",
        effectiveCoveragePath: options.effectiveCoveragePath ?? "unlicensed",
        selectedInstalledLicenseId: options.selectedInstalledLicenseId ?? null,
        selectedSuppressingLicenseId: options.selectedSuppressingLicenseId ?? null,
        discountedUpgradeProvenance: options.discountedUpgradeProvenance ?? false
    };
}
function createEffectiveSuppressingLicenseMetadata(evaluation, payload, licensePath) {
    if (evaluation.selectedSuppressingLicenseId === null) {
        return null;
    }
    return {
        license_id: evaluation.selectedSuppressingLicenseId,
        license_type: payload?.licenseType ?? null,
        licensed_party: payload?.licensedParty ?? null,
        entitlement_release_line: evaluation.coveredReleaseLine,
        coverage_path: evaluation.effectiveCoveragePath,
        license_path: licensePath
    };
}
function nonSuppressingStatus(configuredPathError) {
    return configuredPathError ? "configured-license-error" : "invalid-license";
}
function evaluateLicensePayloadEligibility(payload) {
    if (payload.licenseId === undefined ||
        payload.product === undefined ||
        payload.licenseType === undefined ||
        payload.entitlementKind === undefined ||
        payload.entitlementVersion === undefined ||
        !payload.featureValuesAreStrings ||
        (payload.expiresAtPresent && payload.expiresAt === undefined)) {
        return { ok: false, reasonCode: "malformed" };
    }
    if (payload.product !== exports.DAY_SHIFT_LICENSE_PRODUCT) {
        return { ok: false, reasonCode: "wrong_product" };
    }
    if (!isSupportedMvpLicenseType(payload.licenseType)) {
        return { ok: false, reasonCode: "malformed" };
    }
    if (payload.entitlementKind !== MVP_ENTITLEMENT_KIND) {
        return { ok: false, reasonCode: "malformed" };
    }
    if (isPurchasedCommercialLicenseType(payload.licenseType) && payload.expiresAt !== undefined && payload.expiresAt !== null) {
        return { ok: false, reasonCode: "malformed" };
    }
    if (!payload.features.includes(exports.COMMERCIAL_REMINDERS_SUPPRESSED_FEATURE)) {
        return { ok: false, reasonCode: "missing_required_feature" };
    }
    return { ok: true };
}
function reasonCodeFromSignatureVerificationFailure(reason) {
    switch (reason) {
        case "unsupported_algorithm":
            return "unsupported_algorithm";
        case "unsupported_key_id":
            return "unsupported_key_id";
        case "malformed_signature":
        case "signature_mismatch":
        case "canonical_payload_not_encodable":
            return "invalid_signature";
    }
}
function hasDiscountedUpgradeProvenance(payload) {
    return typeof payload.upgradeFromLicenseId === "string" && payload.upgradeFromLicenseId.length > 0;
}
function isSupportedMvpLicenseType(licenseType) {
    return SUPPORTED_MVP_LICENSE_TYPES.includes(licenseType);
}
function isPurchasedCommercialLicenseType(licenseType) {
    return PURCHASED_COMMERCIAL_LICENSE_TYPES.has(licenseType);
}
function evaluateReleaseLineEntitlement(currentCliVersion, coveredReleaseLine) {
    if (coveredReleaseLine === undefined) {
        return "not-available";
    }
    const current = /^(\d+)\.(\d+)\.(\d+)$/.exec(currentCliVersion);
    const covered = /^(\d+)\.(\d+)$/.exec(coveredReleaseLine);
    if (current === null || covered === null) {
        return "malformed";
    }
    return current[1] === covered[1] && current[2] === covered[2]
        ? "covered"
        : "not-covered";
}
function getTemporaryExpirationState(licenseType, expiresAt, currentTimeMs = Date.now()) {
    if (expiresAt === undefined || expiresAt === null) {
        return licenseType === "trial" ? "missing" : "not-applicable";
    }
    if (!/^\d{4}-\d{2}-\d{2}$/.test(expiresAt)) {
        return "malformed";
    }
    const expirationEnd = Date.parse(`${expiresAt}T23:59:59.999Z`);
    if (!Number.isFinite(expirationEnd)) {
        return "malformed";
    }
    return currentTimeMs <= expirationEnd ? "active" : "expired";
}
function coveragePathFromLicenseType(licenseType) {
    switch (licenseType) {
        case "individual":
            return "individual-machine";
        case "company_seat":
            return "company-seat";
        case "automation_host":
            return "automation-host";
        case "company_site":
            return "company-site";
        case "trial":
            return "trial";
        case "internal":
            return "internal";
        default:
            return "unlicensed";
    }
}
