"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupAiAgentsGenerator = setupAiAgentsGenerator;
exports.setupAiAgentsGeneratorImpl = setupAiAgentsGeneratorImpl;
const path_1 = require("path");
const format_changed_files_with_prettier_if_available_1 = require("../../generators/internal-utils/format-changed-files-with-prettier-if-available");
const json_1 = require("../../generators/utils/json");
const package_json_1 = require("../../utils/package-json");
const provenance_1 = require("../../utils/provenance");
const get_agent_rules_1 = require("./get-agent-rules");
async function setupAiAgentsGenerator(tree, options, inner = false) {
    const normalizedOptions = normalizeOptions(options);
    // Use environment variable to force local execution
    if (process.env.NX_AI_FILES_USE_LOCAL === 'true' || inner) {
        return await setupAiAgentsGeneratorImpl(tree, normalizedOptions);
    }
    try {
        await (0, provenance_1.ensurePackageHasProvenance)('nx', normalizedOptions.packageVersion);
        const { tempDir, cleanup } = (0, package_json_1.installPackageToTmp)('nx', normalizedOptions.packageVersion);
        let modulePath = (0, path_1.join)(tempDir, 'node_modules', 'nx', 'src/ai/set-up-ai-agents/set-up-ai-agents.js');
        const module = await Promise.resolve(`${modulePath}`).then(s => require(s));
        const setupAiAgentsGeneratorResult = await module.setupAiAgentsGenerator(tree, normalizedOptions, true);
        cleanup();
        return setupAiAgentsGeneratorResult;
    }
    catch (error) {
        return await setupAiAgentsGeneratorImpl(tree, normalizedOptions);
    }
}
function normalizeOptions(options) {
    return {
        directory: options.directory,
        writeNxCloudRules: options.writeNxCloudRules ?? false,
        packageVersion: options.packageVersion ?? 'latest',
    };
}
async function setupAiAgentsGeneratorImpl(tree, options) {
    const claudePath = (0, path_1.join)(options.directory, 'CLAUDE.md');
    if (!tree.exists(claudePath)) {
        tree.write(claudePath, (0, get_agent_rules_1.getAgentRules)(options.writeNxCloudRules));
    }
    const agentsPath = (0, path_1.join)(options.directory, 'AGENTS.md');
    if (!tree.exists(agentsPath)) {
        tree.write(agentsPath, (0, get_agent_rules_1.getAgentRules)(options.writeNxCloudRules));
    }
    const mcpJsonPath = (0, path_1.join)(options.directory, '.mcp.json');
    if (!tree.exists(mcpJsonPath)) {
        (0, json_1.writeJson)(tree, mcpJsonPath, {});
    }
    (0, json_1.updateJson)(tree, mcpJsonPath, mcpConfigUpdater);
    const geminiPath = (0, path_1.join)(options.directory, '.gemini', 'settings.json');
    if (!tree.exists(geminiPath)) {
        (0, json_1.writeJson)(tree, geminiPath, {});
    }
    (0, json_1.updateJson)(tree, geminiPath, mcpConfigUpdater);
    // Only set contextFileName to AGENTS.md if GEMINI.md doesn't exist already to preserve existing setups
    if (!tree.exists((0, path_1.join)(options.directory, 'GEMINI.md'))) {
        (0, json_1.updateJson)(tree, geminiPath, (json) => ({
            ...json,
            contextFileName: 'AGENTS.md',
        }));
    }
    await (0, format_changed_files_with_prettier_if_available_1.formatChangedFilesWithPrettierIfAvailable)(tree);
}
function mcpConfigUpdater(existing) {
    if (existing.mcpServers) {
        existing.mcpServers['nx-mcp'] = {
            type: 'stdio',
            command: 'npx',
            args: ['nx', 'mcp'],
        };
    }
    else {
        existing.mcpServers = {
            'nx-mcp': {
                type: 'stdio',
                command: 'npx',
                args: ['nx', 'mcp'],
            },
        };
    }
    return existing;
}
exports.default = setupAiAgentsGenerator;
