"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveArchitectureWorkspaceDiscoveryDefaults = resolveArchitectureWorkspaceDiscoveryDefaults;
exports.resolveArchitectureWorkspaceDiscoveryDefaultsFromModel = resolveArchitectureWorkspaceDiscoveryDefaultsFromModel;
exports.loadArchitectureWorkspaceDiscoveryDefaults = loadArchitectureWorkspaceDiscoveryDefaults;
const architectureInit_1 = require("./architectureInit");
const architectureWorkspaceModel_1 = require("./architectureWorkspaceModel");
const stackAdapters_1 = require("./stackAdapters");
function normalizePath(value) {
    return value
        .replace(/\\/g, '/')
        .replace(/\/+/gu, '/')
        .replace(/^\.\//u, '')
        .replace(/\/+$/u, '')
        .trim() || '.';
}
function joinWorkspacePath(root, relativePath) {
    const normalizedRelativePath = normalizePath(relativePath);
    if (!root || root === '.') {
        return normalizedRelativePath;
    }
    if (normalizedRelativePath === '.') {
        return normalizePath(root);
    }
    return normalizePath(`${root}/${normalizedRelativePath}`);
}
function uniqueSorted(values) {
    return [...new Set(values.map(normalizePath))]
        .filter((value) => value.length > 0)
        .sort((left, right) => left.localeCompare(right));
}
function resolveStackForKind(stacks, projectKinds, kind) {
    if (kind === 'frontend') {
        return stacks.frontendStack;
    }
    if (kind === 'backend' || kind === 'worker') {
        return stacks.backendStack;
    }
    if (kind === 'library') {
        return stacks.libraryStack;
    }
    if (projectKinds.includes('backend')) {
        return stacks.backendStack;
    }
    if (projectKinds.includes('frontend')) {
        return stacks.frontendStack;
    }
    if (projectKinds.includes('library')) {
        return stacks.libraryStack;
    }
    return stacks.backendStack ?? stacks.frontendStack ?? stacks.libraryStack;
}
function resolveComponentAdapter(component) {
    const explicitStack = typeof component.stack === 'string'
        ? component.stack
        : undefined;
    return (0, stackAdapters_1.getStackAdapterById)(explicitStack ??
        resolveStackForKind(component.stacks, component.projectKinds, component.kind));
}
function resolveSourceRoots(component, adapter) {
    const defaults = adapter.getDefaults();
    const componentRoot = component.path ? normalizePath(component.path) : undefined;
    return uniqueSorted(defaults.sourceRoots.map((root) => joinWorkspacePath(componentRoot, root)));
}
function resolveModuleRoots(component, adapter) {
    if (!component.path || component.id === architectureWorkspaceModel_1.VIRTUAL_WORKSPACE_COMPONENT_ID) {
        const configuredModulesRoot = component.structure.modulesRoot;
        if (configuredModulesRoot && configuredModulesRoot.trim().length > 0) {
            return [normalizePath(configuredModulesRoot)];
        }
    }
    const defaults = adapter.getDefaults();
    const componentRoot = component.path ? normalizePath(component.path) : undefined;
    return uniqueSorted(defaults.moduleRootCandidates.map((root) => joinWorkspacePath(componentRoot, root)));
}
function resolvePrefixedDefaults(component, values) {
    const componentRoot = component.path ? normalizePath(component.path) : undefined;
    return uniqueSorted(values.map((value) => joinWorkspacePath(componentRoot, value)));
}
function resolveContractDefaults(component, adapter) {
    const contractsRoot = normalizePath(component.structure.contractsRoot ?? '.archpilot/contracts');
    const isVirtualWorkspace = component.id === architectureWorkspaceModel_1.VIRTUAL_WORKSPACE_COMPONENT_ID;
    const componentContractsRoot = isVirtualWorkspace
        ? undefined
        : `${contractsRoot}/${component.id}`;
    return {
        contractsRoot,
        ...(componentContractsRoot ? { componentContractsRoot } : {}),
        moduleContractPattern: isVirtualWorkspace
            ? `${contractsRoot}/{module}.contract.json`
            : `${componentContractsRoot}/{module}.contract.json`,
        ...(adapter.scaffoldingDefaults?.moduleIndexFileName
            ? { moduleIndexFileName: adapter.scaffoldingDefaults.moduleIndexFileName }
            : {}),
        publicEntrypointDirectories: [...adapter.publicEntrypointDirectoryNames],
    };
}
function resolveEntrypointHints(component, adapter) {
    return resolvePrefixedDefaults(component, adapter.defaultEntrypointHints);
}
function resolveArchitectureWorkspaceDiscoveryDefaults(contract) {
    const model = (0, architectureWorkspaceModel_1.normalizeArchitectureWorkspaceModel)(contract);
    return resolveArchitectureWorkspaceDiscoveryDefaultsFromModel(model);
}
function resolveArchitectureWorkspaceDiscoveryDefaultsFromModel(model) {
    return {
        version: model.version,
        projectName: model.projectName,
        components: model.components.map((component) => {
            const adapter = resolveComponentAdapter(component);
            const adapterDefaults = adapter.getDefaults();
            return {
                componentId: component.id,
                componentName: component.name,
                ...(component.path ? { componentPath: normalizePath(component.path) } : {}),
                ...(component.type ? { componentType: component.type } : {}),
                ...(component.kind ? { componentKind: component.kind } : {}),
                adapterId: adapter.id,
                adapterLabel: adapter.label,
                sourceRoots: resolveSourceRoots(component, adapter),
                moduleRoots: resolveModuleRoots(component, adapter),
                apiRoots: resolvePrefixedDefaults(component, adapterDefaults.apiRoots),
                databaseRoots: resolvePrefixedDefaults(component, adapterDefaults.databaseRoots),
                configFiles: resolvePrefixedDefaults(component, adapterDefaults.configFiles),
                fileExtensions: [...adapter.relevantFileExtensions],
                dependencyFileExtensions: [...adapter.dependencyParsingFileExtensions],
                importExtractionMode: adapter.dependencyExtractionStrategyHint,
                entrypointHints: resolveEntrypointHints(component, adapter),
                contractDefaults: resolveContractDefaults(component, adapter),
                declaredModules: { ...component.modules },
            };
        }),
    };
}
async function loadArchitectureWorkspaceDiscoveryDefaults(workspaceRoot) {
    const contract = await (0, architectureInit_1.loadArchitectureContract)(workspaceRoot);
    return contract ? resolveArchitectureWorkspaceDiscoveryDefaults(contract) : undefined;
}
//# sourceMappingURL=architectureComponentDiscoveryDefaults.js.map