import { existsSync } from 'fs';
import { dirname, isAbsolute, resolve } from 'path';
import { fileURLToPath } from 'url';
function resolveCliEntrypoint() {
    const currentDir = dirname(fileURLToPath(import.meta.url));
    const candidates = [
        resolve(currentDir, '..', 'cli.js'),
        resolve(currentDir, '..', '..', 'dist', 'cli.js'),
    ];
    return candidates.find((candidate) => existsSync(candidate)) ?? null;
}
export function buildNexusMcpCommand() {
    const cliPath = resolveCliEntrypoint();
    if (cliPath) {
        return {
            command: process.execPath,
            args: [cliPath, 'mcp'],
        };
    }
    return {
        command: 'nexus-prime',
        args: ['mcp'],
    };
}
export function buildNexusMcpEnv(workspaceRoot) {
    return {
        NEXUS_MCP_TOOL_PROFILE: 'autonomous',
        NEXUS_MCP_AUTO_CONFIG: '0',
        NEXUS_MCP_DAEMON_TIMEOUT_MS: '5000',
        NEXUS_DAEMON_AUTOSPAWN: '0',
        NEXUS_DASHBOARD_IN_MCP: '0',
        NEXUS_ARCHITECTS_LAZY: '1',
        NEXUS_SYNAPSE_LAZY: '1',
        NEXUS_AUTOMATION_SCHEDULER_DISABLED: '1',
        NEXUS_MCP_FULL_DNA_ON_DISCONNECT: '1',
        ...(workspaceRoot ? { NEXUS_WORKSPACE_ROOT: workspaceRoot } : {}),
    };
}
export function buildNexusMcpServerConfig(workspaceRoot) {
    const { command, args } = buildNexusMcpCommand();
    return {
        command,
        args,
        env: buildNexusMcpEnv(workspaceRoot),
    };
}
function sameResolvedPath(a, b) {
    if (typeof a !== 'string' || !a.trim())
        return false;
    try {
        return resolve(a) === resolve(b);
    }
    catch {
        return false;
    }
}
export function isStableNexusMcpServerConfig(server, envKey = 'env', expectedWorkspaceRoot) {
    const env = server?.[envKey];
    const command = typeof server?.command === 'string' ? server.command : '';
    const args = Array.isArray(server?.args) ? server.args.map((arg) => String(arg)) : [];
    const cliArg = args.find((arg) => /(?:^|[/\\])cli\.js$/.test(arg));
    const workspaceOk = expectedWorkspaceRoot
        ? sameResolvedPath(env?.NEXUS_WORKSPACE_ROOT, expectedWorkspaceRoot)
        : true;
    return Boolean(server
        && command
        && command !== 'npx'
        && command !== 'nexus-prime'
        && isAbsolute(command)
        && cliArg
        && isAbsolute(cliArg)
        && args.includes('mcp')
        && !args.includes('-y')
        && env?.NEXUS_MCP_TOOL_PROFILE === 'autonomous'
        && env?.NEXUS_MCP_AUTO_CONFIG === '0'
        && env?.NEXUS_DAEMON_AUTOSPAWN === '0'
        && env?.NEXUS_MCP_FULL_DNA_ON_DISCONNECT === '1'
        && workspaceOk);
}
