"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.readRiskPolicyConfig = readRiskPolicyConfig;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const riskPolicyEnforcement_1 = require("./riskPolicyEnforcement");
const policyFileRelativePath = '.archpilot/policy.json';
const validRiskLevels = ['low', 'moderate', 'high', 'critical'];
const validRegressionMinimumLevels = [
    'warn',
    'require-adr',
    'fail',
];
function isRiskLevel(value) {
    return typeof value === 'string' && validRiskLevels.includes(value);
}
function isRegressionMinimumLevel(value) {
    return (typeof value === 'string' &&
        validRegressionMinimumLevels.includes(value));
}
function riskLevelOrder(level) {
    if (level === 'low') {
        return 0;
    }
    if (level === 'moderate') {
        return 1;
    }
    if (level === 'high') {
        return 2;
    }
    return 3;
}
function normalizePolicyConfig(raw) {
    if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
        return undefined;
    }
    const typed = raw;
    const rawEnforcementLevels = typed.enforcementLevels;
    if (rawEnforcementLevels !== undefined &&
        (!rawEnforcementLevels ||
            typeof rawEnforcementLevels !== 'object' ||
            Array.isArray(rawEnforcementLevels))) {
        return undefined;
    }
    const rawRiskThresholds = typed.riskThresholds;
    if (rawRiskThresholds !== undefined &&
        (!rawRiskThresholds || typeof rawRiskThresholds !== 'object' || Array.isArray(rawRiskThresholds))) {
        return undefined;
    }
    const rawRequireAdr = typed.requireADR;
    if (rawRequireAdr !== undefined &&
        (!rawRequireAdr || typeof rawRequireAdr !== 'object' || Array.isArray(rawRequireAdr))) {
        return undefined;
    }
    const rawBaselineRegression = typed.baselineRegression;
    if (rawBaselineRegression !== undefined &&
        (!rawBaselineRegression ||
            typeof rawBaselineRegression !== 'object' ||
            Array.isArray(rawBaselineRegression))) {
        return undefined;
    }
    if (typed.allowOverrideWithJustification !== undefined &&
        typeof typed.allowOverrideWithJustification !== 'boolean') {
        return undefined;
    }
    const warnAt = rawEnforcementLevels?.warnAt ?? rawRiskThresholds?.warn;
    const requireAdrAt = rawEnforcementLevels?.requireAdrAt ?? rawRequireAdr?.level;
    const failAt = rawEnforcementLevels?.failAt ?? rawRiskThresholds?.block;
    const regressionMinimum = rawBaselineRegression?.minimumLevelOnRegression;
    const warn = rawRiskThresholds?.warn;
    const block = rawRiskThresholds?.block;
    const requireAdrLevel = rawRequireAdr?.level;
    if (warnAt !== undefined && !isRiskLevel(warnAt)) {
        return undefined;
    }
    if (requireAdrAt !== undefined && !isRiskLevel(requireAdrAt)) {
        return undefined;
    }
    if (failAt !== undefined && !isRiskLevel(failAt)) {
        return undefined;
    }
    if (warn !== undefined && !isRiskLevel(warn)) {
        return undefined;
    }
    if (block !== undefined && !isRiskLevel(block)) {
        return undefined;
    }
    if (requireAdrLevel !== undefined && !isRiskLevel(requireAdrLevel)) {
        return undefined;
    }
    if (rawBaselineRegression?.elevateOnRegression !== undefined &&
        typeof rawBaselineRegression.elevateOnRegression !== 'boolean') {
        return undefined;
    }
    if (regressionMinimum !== undefined && !isRegressionMinimumLevel(regressionMinimum)) {
        return undefined;
    }
    const normalizedWarnAt = warnAt ?? riskPolicyEnforcement_1.defaultPolicyConfig.enforcementLevels.warnAt;
    const normalizedRequireAdrAt = requireAdrAt ??
        riskPolicyEnforcement_1.defaultPolicyConfig.enforcementLevels.requireAdrAt;
    const normalizedFailAt = failAt ?? riskPolicyEnforcement_1.defaultPolicyConfig.enforcementLevels.failAt;
    if (riskLevelOrder(normalizedWarnAt) > riskLevelOrder(normalizedRequireAdrAt) ||
        riskLevelOrder(normalizedRequireAdrAt) > riskLevelOrder(normalizedFailAt)) {
        return undefined;
    }
    return {
        enforcementLevels: {
            warnAt: normalizedWarnAt,
            requireAdrAt: normalizedRequireAdrAt,
            failAt: normalizedFailAt,
        },
        riskThresholds: {
            warn: normalizedWarnAt,
            block: normalizedFailAt,
        },
        requireADR: {
            level: normalizedRequireAdrAt,
        },
        baselineRegression: {
            elevateOnRegression: rawBaselineRegression?.elevateOnRegression ??
                riskPolicyEnforcement_1.defaultPolicyConfig.baselineRegression.elevateOnRegression,
            minimumLevelOnRegression: regressionMinimum ??
                riskPolicyEnforcement_1.defaultPolicyConfig.baselineRegression.minimumLevelOnRegression,
        },
        allowOverrideWithJustification: typed.allowOverrideWithJustification ?? riskPolicyEnforcement_1.defaultPolicyConfig.allowOverrideWithJustification,
    };
}
async function readRiskPolicyConfig(workspaceRoot) {
    const policyPath = path.join(workspaceRoot, '.archpilot', 'policy.json');
    let contents;
    try {
        contents = await node_fs_1.promises.readFile(policyPath, { encoding: 'utf8' });
    }
    catch (error) {
        if (error.code === 'ENOENT') {
            return {
                config: riskPolicyEnforcement_1.defaultPolicyConfig,
                source: 'default',
            };
        }
        return {
            config: riskPolicyEnforcement_1.defaultPolicyConfig,
            source: 'fallback-default',
            configError: error instanceof Error
                ? `ArchPilot policy configuration could not be read. ${error.message}`
                : `ArchPilot policy configuration could not be read. Please verify ${policyFileRelativePath}.`,
        };
    }
    let parsed;
    try {
        parsed = JSON.parse(contents);
    }
    catch {
        return {
            config: riskPolicyEnforcement_1.defaultPolicyConfig,
            source: 'fallback-default',
            configError: 'ArchPilot policy configuration is invalid JSON. Please fix .archpilot/policy.json.',
        };
    }
    const normalized = normalizePolicyConfig(parsed);
    if (!normalized) {
        return {
            config: riskPolicyEnforcement_1.defaultPolicyConfig,
            source: 'fallback-default',
            configError: 'ArchPilot policy configuration is invalid: .archpilot/policy.json must define valid enforcement levels, baseline regression settings, and policy flags.',
        };
    }
    return {
        config: normalized,
        source: 'policy-file',
    };
}
//# sourceMappingURL=riskPolicyConfig.js.map