"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.applyRulePack = applyRulePack;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const architectureInit_1 = require("./architectureInit");
function sortObjectEntries(value) {
    return Object.entries(value).sort(([left], [right]) => left.localeCompare(right));
}
function renderSortedJson(value) {
    return `${JSON.stringify(value, null, 2)}\n`;
}
async function applyRulePack(workspaceRoot, pack) {
    const contract = await (0, architectureInit_1.loadArchitectureContract)(workspaceRoot);
    if (!contract) {
        throw new Error('ArchPilot is not initialized in this workspace. Run `archpilot init` or initialize via the extension first.');
    }
    const archpilotDir = path.join(workspaceRoot, '.archpilot');
    await node_fs_1.promises.mkdir(archpilotDir, { recursive: true });
    const normalizedRules = sortObjectEntries(pack.validationConfig.rules).reduce((accumulator, [ruleId, config]) => {
        accumulator[ruleId] = {
            ...(config.enabled !== undefined ? { enabled: config.enabled } : {}),
            ...(config.severity ? { severity: config.severity } : {}),
        };
        return accumulator;
    }, {});
    const filesWritten = [];
    const rulesPath = path.join(archpilotDir, 'rules.json');
    await node_fs_1.promises.writeFile(rulesPath, renderSortedJson({
        rules: normalizedRules,
    }), { encoding: 'utf8' });
    filesWritten.push(rulesPath);
    if (pack.dependencyRulesTemplate) {
        const dependencyModules = sortObjectEntries(pack.dependencyRulesTemplate.modules).reduce((accumulator, [moduleName, moduleRules]) => {
            accumulator[moduleName] = {
                ...(moduleRules.allowedDependencies
                    ? {
                        allowedDependencies: [...moduleRules.allowedDependencies].sort((left, right) => left.localeCompare(right)),
                    }
                    : {}),
                ...(moduleRules.publicEntrypointsOnly !== undefined
                    ? { publicEntrypointsOnly: moduleRules.publicEntrypointsOnly }
                    : {}),
            };
            return accumulator;
        }, {});
        const dependencyRulesPath = path.join(archpilotDir, 'dependency-rules.json');
        await node_fs_1.promises.writeFile(dependencyRulesPath, renderSortedJson({
            modules: dependencyModules,
        }), { encoding: 'utf8' });
        filesWritten.push(dependencyRulesPath);
    }
    if (pack.layerRulesTemplate) {
        const moduleLayers = sortObjectEntries(pack.layerRulesTemplate.moduleLayers).reduce((accumulator, [moduleName, layer]) => {
            accumulator[moduleName] = layer;
            return accumulator;
        }, {});
        const layerRulesPath = path.join(archpilotDir, 'layer-rules.json');
        await node_fs_1.promises.writeFile(layerRulesPath, renderSortedJson({
            layers: [...pack.layerRulesTemplate.layers].sort((left, right) => left.localeCompare(right)),
            moduleLayers,
        }), { encoding: 'utf8' });
        filesWritten.push(layerRulesPath);
    }
    const metadata = {
        appliedRulePackId: pack.id,
        appliedAtUtc: new Date().toISOString(),
        architectureStyle: pack.architectureStyle,
        version: 1,
    };
    const rulePackMetadataPath = path.join(archpilotDir, 'rule-pack.json');
    await node_fs_1.promises.writeFile(rulePackMetadataPath, renderSortedJson(metadata), {
        encoding: 'utf8',
    });
    filesWritten.push(rulePackMetadataPath);
    return {
        appliedPackId: pack.id,
        filesWritten: filesWritten
            .map((filePath) => path.relative(workspaceRoot, filePath).replace(/\\/g, '/'))
            .sort((left, right) => left.localeCompare(right)),
        metadata,
    };
}
//# sourceMappingURL=applyRulePack.js.map