"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildResolvedConfigEntries = buildResolvedConfigEntries;
const config_catalog_1 = require("./config-catalog");
const structural_pressure_scan_defaults_1 = require("./structural-pressure-scan-defaults");
function buildResolvedConfigEntries(options) {
    return Object.freeze(Object.fromEntries(config_catalog_1.CONFIG_CATALOG.map((catalogEntry) => [
        catalogEntry.key,
        resolveCatalogEntry(catalogEntry, options)
    ])));
}
function resolveCatalogEntry(catalogEntry, options) {
    if (catalogEntry.persistedConfigContract !== undefined) {
        return resolvePersistedCatalogEntry(catalogEntry, options);
    }
    if (catalogEntry.key.startsWith("structural_pressure.")) {
        return resolveStructuralPressureThresholdCatalogEntry(catalogEntry, options);
    }
    if (catalogEntry.key.startsWith("runtime_evidence.path_policy.")) {
        return resolveRuntimeEvidencePathPolicyCatalogEntry(catalogEntry, options);
    }
    if (catalogEntry.key.startsWith("derived.")) {
        return resolveDerivedCatalogEntry(catalogEntry, options.derived);
    }
    if (catalogEntry.key.startsWith("license.") || catalogEntry.key.startsWith("reminder.")) {
        const licenseEntry = options.licenseProvenance?.entries[catalogEntry.key];
        if (licenseEntry !== undefined) {
            return createResolvedEntry({
                catalogEntry,
                valueState: licenseEntry.valueState,
                sourceKind: licenseEntry.sourceKind,
                sourcePath: licenseEntry.sourcePath,
                sourceDescription: licenseEntry.sourceDescription,
                effectiveValue: licenseEntry.effectiveValue,
                includeEffectiveValue: licenseEntry.safeToPrintEffectiveValue
                    && licenseEntry.effectiveValue !== undefined
                    && isPrintable(catalogEntry)
            });
        }
    }
    return resolveNonPersistedCatalogEntry(catalogEntry);
}
function resolveStructuralPressureThresholdCatalogEntry(catalogEntry, options) {
    const thresholdKey = parseStructuralPressureThresholdKey(catalogEntry.key);
    if (thresholdKey !== null) {
        const configuredValue = options.repositoryConfig?.structural_pressure?.[thresholdKey.family]?.[thresholdKey.threshold];
        if (configuredValue !== undefined) {
            return createResolvedEntry({
                catalogEntry,
                valueState: "available",
                sourceKind: "repository",
                sourceLayer: "repository",
                sourcePath: options.derived.sharedConfigPath,
                sourceDescription: "Resolved from .day-shift/config.toml.",
                effectiveValue: configuredValue,
                includeEffectiveValue: isPrintable(catalogEntry)
            });
        }
        const defaultValue = parseSafeDefaultValue(catalogEntry);
        return createResolvedEntry({
            catalogEntry,
            valueState: "available",
            sourceKind: "defaults",
            sourceLayer: "defaults",
            sourceDescription: "Resolved from built-in defaults.",
            effectiveValue: defaultValue,
            includeEffectiveValue: defaultValue !== undefined && isPrintable(catalogEntry)
        });
    }
    const exclusionKey = parseStructuralPressureExclusionKey(catalogEntry.key);
    if (exclusionKey !== null) {
        const configuredValue = options.repositoryConfig?.structural_pressure?.[exclusionKey];
        if (configuredValue !== undefined) {
            return createResolvedEntry({
                catalogEntry,
                valueState: "available",
                sourceKind: "repository",
                sourceLayer: "repository",
                sourcePath: options.derived.sharedConfigPath,
                sourceDescription: "Resolved from .day-shift/config.toml.",
                effectiveValue: configuredValue,
                includeEffectiveValue: isPrintable(catalogEntry)
            });
        }
        const defaultValue = exclusionKey === "excluded_extensions"
            ? [...structural_pressure_scan_defaults_1.STRUCTURAL_PRESSURE_DEFAULT_EXCLUDED_EXTENSIONS]
            : exclusionKey === "blocked_segments"
                ? [...structural_pressure_scan_defaults_1.STRUCTURAL_PRESSURE_DEFAULT_BLOCKED_SCAN_SEGMENTS]
                : [...structural_pressure_scan_defaults_1.STRUCTURAL_PRESSURE_DEFAULT_EXCLUDED_BASENAMES];
        return createResolvedEntry({
            catalogEntry,
            valueState: "available",
            sourceKind: "defaults",
            sourceLayer: "defaults",
            sourceDescription: "Resolved from built-in defaults.",
            effectiveValue: defaultValue,
            includeEffectiveValue: isPrintable(catalogEntry)
        });
    }
    return resolveNonPersistedCatalogEntry(catalogEntry);
}
function resolveRuntimeEvidencePathPolicyCatalogEntry(catalogEntry, options) {
    const policyKey = parseRuntimeEvidencePathPolicyKey(catalogEntry.key);
    if (policyKey === null) {
        return resolveNonPersistedCatalogEntry(catalogEntry);
    }
    const configuredValue = options.repositoryConfig?.runtime_evidence?.path_policy?.[policyKey];
    if (configuredValue !== undefined) {
        return createResolvedEntry({
            catalogEntry,
            valueState: "available",
            sourceKind: "repository",
            sourceLayer: "repository",
            sourcePath: options.derived.sharedConfigPath,
            sourceDescription: "Resolved from .day-shift/config.toml.",
            effectiveValue: configuredValue,
            includeEffectiveValue: isPrintable(catalogEntry)
        });
    }
    return createResolvedEntry({
        catalogEntry,
        valueState: "available",
        sourceKind: "defaults",
        sourceLayer: "defaults",
        sourceDescription: "Resolved from built-in defaults.",
        effectiveValue: [],
        includeEffectiveValue: isPrintable(catalogEntry)
    });
}
function resolvePersistedCatalogEntry(catalogEntry, options) {
    const persistedKey = catalogEntry.persistedConfigContract?.key;
    const value = options.values[persistedKey];
    const sourceLayer = options.sources[persistedKey];
    const valueState = value === undefined ? "not-supplied" : "available";
    return createResolvedEntry({
        catalogEntry,
        valueState,
        sourceKind: sourceLayer,
        sourceLayer,
        sourcePath: persistedSourcePath(sourceLayer, options.derived),
        sourceDescription: persistedSourceDescription(sourceLayer),
        effectiveValue: value,
        includeEffectiveValue: valueState === "available" && isPrintable(catalogEntry)
    });
}
function resolveDerivedCatalogEntry(catalogEntry, derived) {
    const derivedField = catalogEntry.key.slice("derived.".length);
    const value = derived[derivedField];
    return createResolvedEntry({
        catalogEntry,
        valueState: value === undefined ? "not-resolved" : "available",
        sourceKind: "runtime-derived",
        sourceDescription: "Computed at runtime from the repository root and resolved config values.",
        effectiveValue: value,
        includeEffectiveValue: value !== undefined && isPrintable(catalogEntry)
    });
}
function resolveNonPersistedCatalogEntry(catalogEntry) {
    const defaultValue = parseSafeDefaultValue(catalogEntry);
    const hasDefaultValue = defaultValue !== undefined;
    const sourceKind = defaultSourceKind(catalogEntry);
    return createResolvedEntry({
        catalogEntry,
        valueState: hasDefaultValue ? "default-described" : defaultValueState(catalogEntry),
        sourceKind,
        sourceDescription: nonPersistedSourceDescription(catalogEntry, sourceKind),
        effectiveValue: defaultValue,
        includeEffectiveValue: hasDefaultValue && isPrintable(catalogEntry)
    });
}
function createResolvedEntry(options) {
    const resolvedEntry = {
        catalogKey: options.catalogEntry.key,
        catalogEntry: options.catalogEntry,
        catalog: catalogMetadata(options.catalogEntry),
        valueState: options.valueState,
        sourceKind: options.sourceKind,
        sourceLayer: options.sourceLayer,
        sourcePath: options.sourcePath,
        sourceDescription: options.sourceDescription,
        inventoryDisplay: options.catalogEntry.inventoryDisplay,
        safeToPrintEffectiveValue: options.includeEffectiveValue
    };
    if (options.includeEffectiveValue) {
        resolvedEntry.effectiveValue = options.effectiveValue;
    }
    return resolvedEntry;
}
function catalogMetadata(catalogEntry) {
    return {
        key: catalogEntry.key,
        valueFamily: catalogEntry.valueFamily,
        valueType: catalogEntry.valueType,
        mutability: catalogEntry.mutability,
        sensitivity: catalogEntry.sensitivity,
        owningCommandFamily: catalogEntry.owningCommandFamily,
        discoverability: catalogEntry.discoverability,
        validationRule: catalogEntry.validationRule,
        writePolicy: catalogEntry.writePolicy,
        description: catalogEntry.description,
        migrationNote: catalogEntry.migrationNote
    };
}
function persistedSourcePath(sourceLayer, derived) {
    if (sourceLayer === "repository") {
        return derived.sharedConfigPath;
    }
    if (sourceLayer === "local") {
        return derived.localConfigPath;
    }
    return undefined;
}
function persistedSourceDescription(sourceLayer) {
    if (sourceLayer === "repository") {
        return "Resolved from .day-shift/config.toml.";
    }
    if (sourceLayer === "local") {
        return "Resolved from .day-shift/local.toml.";
    }
    return "Resolved from built-in defaults.";
}
function nonPersistedSourceDescription(catalogEntry, sourceKind) {
    if (catalogEntry.key.startsWith("structural_pressure.")) {
        return `Planned structural-pressure threshold default from ${sourceKind} catalog provenance.`;
    }
    if (catalogEntry.defaultValueDescription !== undefined) {
        return `Catalog-described default from ${sourceKind} provenance: ${catalogEntry.defaultValueDescription}`;
    }
    if (catalogEntry.derivedValueDescription !== undefined) {
        return catalogEntry.derivedValueDescription;
    }
    return `Catalog-visible value represented by ${sourceKind} provenance.`;
}
function defaultSourceKind(catalogEntry) {
    if (catalogEntry.valueFamily === "environment-input") {
        return "environment";
    }
    if (catalogEntry.valueFamily === "command-input") {
        return "command-input";
    }
    if (catalogEntry.valueFamily === "derived-runtime-state") {
        return "runtime-derived";
    }
    if (catalogEntry.valueFamily === "future-candidate") {
        return "future-candidate";
    }
    if (catalogEntry.valueFamily === "host-state") {
        return "host-state";
    }
    if (catalogEntry.valueFamily === "local-state") {
        return catalogEntry.allowedSourceLayers.includes("product-policy")
            ? "product-policy"
            : "user-local-state";
    }
    return catalogEntry.allowedSourceLayers[0] ?? "product-policy";
}
function defaultValueState(catalogEntry) {
    if (catalogEntry.valueFamily === "environment-input" ||
        catalogEntry.valueFamily === "command-input") {
        return "not-supplied";
    }
    return "not-resolved";
}
function parseSafeDefaultValue(catalogEntry) {
    if (catalogEntry.key.startsWith("runtime_evidence.path_policy.")) {
        return [];
    }
    if (!catalogEntry.key.startsWith("structural_pressure.")) {
        return undefined;
    }
    const description = catalogEntry.defaultValueDescription;
    if (description === undefined) {
        return undefined;
    }
    const parsed = Number(description);
    return Number.isFinite(parsed) ? parsed : undefined;
}
function isPrintable(catalogEntry) {
    return catalogEntry.inventoryDisplay.mode === "printable";
}
function parseRuntimeEvidencePathPolicyKey(key) {
    if (key === "runtime_evidence.path_policy.documentation_only_paths") {
        return "documentation_only_paths";
    }
    if (key === "runtime_evidence.path_policy.runtime_eligible_paths") {
        return "runtime_eligible_paths";
    }
    return null;
}
function parseStructuralPressureThresholdKey(key) {
    const match = /^structural_pressure\.(source|test)\.(watch|pressure|hotspot)$/.exec(key);
    if (match === null) {
        return null;
    }
    return {
        family: match[1],
        threshold: match[2]
    };
}
function parseStructuralPressureExclusionKey(key) {
    if (key === "structural_pressure.excluded_extensions") {
        return "excluded_extensions";
    }
    if (key === "structural_pressure.blocked_segments") {
        return "blocked_segments";
    }
    if (key === "structural_pressure.excluded_basenames") {
        return "excluded_basenames";
    }
    return null;
}
