"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.previewArchitectureModelRefresh = previewArchitectureModelRefresh;
exports.applyArchitectureModelRefresh = applyArchitectureModelRefresh;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const architectureInit_1 = require("./architectureInit");
const managedArtifacts_1 = require("./managedArtifacts");
const moduleContractsGenerator_1 = require("./moduleContractsGenerator");
const smartInit_1 = require("./smartInit");
function normalizePath(value) {
    return value.replace(/\\/g, '/');
}
function sortUnique(values) {
    return [...new Set(values)].sort((left, right) => left.localeCompare(right));
}
function getModuleRegistryEntries(modules) {
    return Object.entries(modules ?? {}).sort(([left], [right]) => left.localeCompare(right));
}
function resolveCandidateMap(candidates) {
    return new Map(candidates.map((candidate) => [candidate.name, candidate]));
}
function mergeCandidates(left, right) {
    const byName = new Map();
    for (const candidate of [...left, ...right]) {
        byName.set(candidate.name, candidate);
    }
    return [...byName.values()].sort((a, b) => {
        const classificationCompare = a.classification.localeCompare(b.classification);
        if (classificationCompare !== 0) {
            return classificationCompare;
        }
        return a.name.localeCompare(b.name);
    });
}
function contractDetectedStacks(contract) {
    const allowed = new Set([
        'node_typescript',
        'express',
        'nestjs',
        'java',
        'spring',
        'fastapi',
        'django',
        'flask',
        'python',
        'php',
        'laravel',
        'go',
        'dotnet',
        'ruby_rails',
        'kotlin',
        'kotlin_spring',
        'react',
        'nextjs',
        'angular',
        'vue',
        'terraform',
        'ansible',
        'other',
        'unknown',
    ]);
    const stacksRecord = contract.stacks && typeof contract.stacks === 'object' && !Array.isArray(contract.stacks)
        ? contract.stacks
        : {};
    return Object.values(stacksRecord)
        .filter((value) => typeof value === 'string' && allowed.has(value));
}
async function previewArchitectureModelRefresh(input) {
    const contract = await (0, architectureInit_1.loadArchitectureContract)(input.workspaceRoot);
    if (!contract) {
        throw new Error('ArchPilot is not initialized in this workspace.');
    }
    const detection = (0, smartInit_1.detectSmartInit)(input.workspaceRoot);
    const configuredRootCandidates = contract.structure.modulesRoot
        ? (0, smartInit_1.detectModuleCandidatesForRoot)(input.workspaceRoot, contract.structure.modulesRoot, {
            projectKinds: contract.projectKinds,
            stacks: contractDetectedStacks(contract),
        })
        : [];
    const candidates = mergeCandidates(detection.proposal?.moduleCandidates ?? [], configuredRootCandidates);
    const candidateMap = resolveCandidateMap(candidates);
    const registryEntries = getModuleRegistryEntries(contract.modules);
    const currentModules = registryEntries.map(([moduleName]) => moduleName);
    const selectedModules = sortUnique((input.selectedModules ?? currentModules)
        .map((entry) => entry.trim())
        .filter((entry) => entry.length > 0));
    const currentSet = new Set(currentModules);
    const selectedSet = new Set(selectedModules);
    const modulesToAdd = selectedModules.filter((moduleName) => !currentSet.has(moduleName));
    const modulesToRemove = currentModules.filter((moduleName) => !selectedSet.has(moduleName));
    const contractsToGenerate = [];
    const generatedContractsPrunable = [];
    const userAuthoredContractsPreserved = [];
    const moduleRegistry = contract.modules ?? {};
    for (const moduleName of selectedModules) {
        const registryEntry = moduleRegistry[moduleName];
        const contractPath = normalizePath(registryEntry?.contract ?? (0, architectureInit_1.buildDefaultModuleContractPath)(moduleName, contract));
        try {
            await node_fs_1.promises.access(path.join(input.workspaceRoot, ...contractPath.split('/')));
        }
        catch {
            contractsToGenerate.push(contractPath);
        }
    }
    for (const moduleName of modulesToRemove) {
        const contractPath = moduleRegistry[moduleName]?.contract;
        if (!contractPath) {
            continue;
        }
        const plan = await (0, managedArtifacts_1.classifyManagedArtifact)(input.workspaceRoot, normalizePath(contractPath), 'json');
        if (plan.status === 'update-managed') {
            generatedContractsPrunable.push(plan.relativePath);
        }
        else if (plan.status === 'preserve-user-owned') {
            userAuthoredContractsPreserved.push(plan.relativePath);
        }
    }
    const notes = selectedModules
        .filter((moduleName) => !candidateMap.has(moduleName) && !currentSet.has(moduleName))
        .map((moduleName) => `Selected module '${moduleName}' was not in the latest discovery candidates; explicit selection still wins.`);
    return {
        candidates,
        currentModules,
        selectedModules,
        modulesToAdd,
        modulesToRemove,
        contractsToGenerate: sortUnique(contractsToGenerate),
        generatedContractsPrunable: sortUnique(generatedContractsPrunable),
        userAuthoredContractsPreserved: sortUnique(userAuthoredContractsPreserved),
        notes,
    };
}
async function applyArchitectureModelRefresh(input) {
    const contract = await (0, architectureInit_1.loadArchitectureContract)(input.workspaceRoot);
    if (!contract) {
        throw new Error('ArchPilot is not initialized in this workspace.');
    }
    const preview = await previewArchitectureModelRefresh(input);
    const detection = (0, smartInit_1.detectSmartInit)(input.workspaceRoot);
    const candidateMap = resolveCandidateMap(detection.proposal?.moduleCandidates ?? []);
    const nextModules = {};
    const moduleRegistry = contract.modules ?? {};
    for (const moduleName of preview.selectedModules) {
        const existing = moduleRegistry[moduleName];
        const candidate = candidateMap.get(moduleName);
        nextModules[moduleName] = {
            ...(existing ?? {}),
            path: normalizePath(existing?.path ?? candidate?.path ?? `${contract.structure.modulesRoot ?? 'src/modules'}/${moduleName}`),
            contract: normalizePath(existing?.contract ?? (0, architectureInit_1.buildDefaultModuleContractPath)(moduleName, contract)),
            publicEntrypoints: sortUnique(existing?.publicEntrypoints ?? (0, architectureInit_1.buildDefaultModulePublicEntrypoints)(moduleName, contract)),
        };
    }
    contract.modules = nextModules;
    await (0, architectureInit_1.saveArchitectureContract)(input.workspaceRoot, contract);
    const contractGeneration = preview.selectedModules.length > 0
        ? await (0, moduleContractsGenerator_1.generateMissingModuleContracts)(input.workspaceRoot)
        : { createdContracts: [], updatedManagedContracts: [], unchangedManagedContracts: [] };
    const prunedContracts = [];
    if (input.pruneGeneratedContracts) {
        for (const contractPath of preview.generatedContractsPrunable) {
            const absolutePath = path.join(input.workspaceRoot, ...contractPath.split('/'));
            await node_fs_1.promises.unlink(absolutePath).catch(() => undefined);
            prunedContracts.push(contractPath);
        }
    }
    return {
        ...preview,
        architectureUpdated: preview.modulesToAdd.length > 0 || preview.modulesToRemove.length > 0,
        createdContracts: sortUnique(contractGeneration.createdContracts),
        updatedManagedContracts: sortUnique(contractGeneration.updatedManagedContracts),
        unchangedManagedContracts: sortUnique(contractGeneration.unchangedManagedContracts),
        prunedContracts: sortUnique(prunedContracts),
    };
}
//# sourceMappingURL=architectureModelRefresh.js.map