"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.bootstrapArchitectureConfig = bootstrapArchitectureConfig;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const architectureMap_1 = require("./architectureMap");
const moduleContractsGenerator_1 = require("./moduleContractsGenerator");
function normalizePath(value) {
    return value.replace(/\\/g, '/');
}
function toAbsolutePath(workspaceRoot, relativePath) {
    return path.join(workspaceRoot, ...relativePath.split('/'));
}
async function pathExists(targetPath) {
    try {
        await node_fs_1.promises.access(targetPath);
        return true;
    }
    catch {
        return false;
    }
}
function sortUnique(values) {
    return [...new Set(values)].sort((left, right) => left.localeCompare(right));
}
function renderDependencyRulesConfig(input) {
    const modules = input.modules.reduce((accumulator, moduleName) => {
        accumulator[moduleName] = {
            allowedDependencies: sortUnique(input.allowedDependenciesByModule.get(moduleName) ?? []),
            publicEntrypointsOnly: true,
        };
        return accumulator;
    }, {});
    return `${JSON.stringify({ modules }, null, 2)}\n`;
}
function renderLayerRulesConfig(modules) {
    const moduleLayers = modules.reduce((accumulator, moduleName) => {
        accumulator[moduleName] = 'module';
        return accumulator;
    }, {});
    return `${JSON.stringify({ layers: ['module'], moduleLayers }, null, 2)}\n`;
}
function buildAllowedDependenciesBySource(edges) {
    const bySource = new Map();
    for (const edge of edges) {
        const set = bySource.get(edge.source) ?? new Set();
        set.add(edge.target);
        bySource.set(edge.source, set);
    }
    return new Map([...bySource.entries()]
        .sort(([left], [right]) => left.localeCompare(right))
        .map(([source, targets]) => [
        source,
        [...targets].sort((left, right) => left.localeCompare(right)),
    ]));
}
async function bootstrapArchitectureConfig(workspaceRoot, options) {
    const map = await (0, architectureMap_1.generateArchitectureMap)(workspaceRoot);
    const modules = map.modules
        .map((entry) => entry.moduleName)
        .sort((left, right) => left.localeCompare(right));
    const allowedDependenciesByModule = buildAllowedDependenciesBySource(map.edges.map((edge) => ({ source: edge.source, target: edge.target })));
    const createdFiles = [];
    const skippedExistingFiles = [];
    const ensuredDirectories = [];
    const archpilotDirectory = path.join(workspaceRoot, '.archpilot');
    const contractsDirectory = path.join(archpilotDirectory, 'contracts');
    await node_fs_1.promises.mkdir(archpilotDirectory, { recursive: true });
    await node_fs_1.promises.mkdir(contractsDirectory, { recursive: true });
    ensuredDirectories.push('.archpilot', '.archpilot/contracts');
    const dependencyRulesPath = '.archpilot/dependency-rules.json';
    const dependencyRulesAbsolutePath = toAbsolutePath(workspaceRoot, dependencyRulesPath);
    if (await pathExists(dependencyRulesAbsolutePath)) {
        skippedExistingFiles.push(dependencyRulesPath);
    }
    else {
        await node_fs_1.promises.writeFile(dependencyRulesAbsolutePath, renderDependencyRulesConfig({ modules, allowedDependenciesByModule }), { encoding: 'utf8' });
        createdFiles.push(dependencyRulesPath);
    }
    const layerRulesPath = '.archpilot/layer-rules.json';
    const layerRulesAbsolutePath = toAbsolutePath(workspaceRoot, layerRulesPath);
    if (await pathExists(layerRulesAbsolutePath)) {
        skippedExistingFiles.push(layerRulesPath);
    }
    else {
        await node_fs_1.promises.writeFile(layerRulesAbsolutePath, renderLayerRulesConfig(modules), {
            encoding: 'utf8',
        });
        createdFiles.push(layerRulesPath);
    }
    let contractGeneration;
    let contractGenerationSkippedReason;
    if (options?.includeContracts) {
        try {
            contractGeneration = await (0, moduleContractsGenerator_1.generateMissingModuleContracts)(workspaceRoot);
        }
        catch (error) {
            if (error instanceof Error &&
                error.message.includes('ArchPilot is not initialized in this workspace.')) {
                contractGenerationSkippedReason =
                    'Contract generation skipped: initialize .archpilot/architecture.json first.';
            }
            else {
                throw error;
            }
        }
    }
    return {
        createdFiles: sortUnique(createdFiles.map((entry) => normalizePath(entry))),
        ensuredDirectories: sortUnique(ensuredDirectories.map((entry) => normalizePath(entry))),
        skippedExistingFiles: sortUnique(skippedExistingFiles.map((entry) => normalizePath(entry))),
        moduleCount: modules.length,
        ...(contractGeneration ? { contractGeneration } : {}),
        ...(contractGenerationSkippedReason ? { contractGenerationSkippedReason } : {}),
    };
}
//# sourceMappingURL=bootstrapArchitectureConfig.js.map