import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { CodexMcpAdapter } from './mcp-codex.js';
let tempDir;
let configPath;
function buildServer(name = 'aws-client-agent-mcp') {
    return {
        id: 'mcp_test',
        name,
        server: {
            type: 'stdio',
            command: 'node',
            args: ['D:\\code\\AgentsWorkStudio\\aws-runtime-bridge\\package\\cc-switch-sdk\\dist\\index.js'],
            env: {
                AWS_AGENT_ID: 'agent-1',
            },
        },
        apps: {
            claude: false,
            claudecode: false,
            codex: true,
            gemini: false,
            opencode: false,
            openclaw: false,
        },
    };
}
beforeEach(async () => {
    tempDir = await mkdtemp(path.join(os.tmpdir(), 'codex-mcp-adapter-'));
    configPath = path.join(tempDir, 'config.toml');
});
afterEach(async () => {
    await rm(tempDir, { recursive: true, force: true });
});
describe('CodexMcpAdapter', () => {
    it('creates a Codex config with an MCP block when none exists', async () => {
        const adapter = new CodexMcpAdapter(configPath);
        await adapter.syncServer(buildServer());
        const written = await readFile(configPath, 'utf-8');
        expect(written).toContain('[mcp_servers."aws-client-agent-mcp"]');
        expect(written).toContain('command = "node"');
        expect(written).toContain('args = ["D:\\\\code\\\\AgentsWorkStudio\\\\aws-runtime-bridge\\\\package\\\\cc-switch-sdk\\\\dist\\\\index.js"]');
        expect(written).toContain('[mcp_servers."aws-client-agent-mcp".env]');
        expect(written).toContain('AWS_AGENT_ID = "agent-1"');
    });
    it('preserves unrelated Codex model/provider config while appending MCP config', async () => {
        const existing = [
            '# user comment',
            'model = "gpt-5.1"',
            'model_provider = "custom"',
            '',
            '[model_providers.custom]',
            'name = "Custom"',
            'base_url = "https://example.test/v1"',
            '',
        ].join('\n');
        await writeFile(configPath, existing, 'utf-8');
        const adapter = new CodexMcpAdapter(configPath);
        await adapter.syncServer(buildServer());
        const written = await readFile(configPath, 'utf-8');
        expect(written).toContain(existing.trimEnd());
        expect(written).toContain('[mcp_servers."aws-client-agent-mcp"]');
    });
    it('updates an existing MCP block without duplicating it', async () => {
        const adapter = new CodexMcpAdapter(configPath);
        await adapter.syncServer(buildServer());
        await adapter.syncServer({
            ...buildServer(),
            server: {
                type: 'stdio',
                command: 'node',
                args: ['new-index.js'],
                env: {
                    AWS_AGENT_ID: 'agent-2',
                },
            },
        });
        const written = await readFile(configPath, 'utf-8');
        expect(written.match(/\[mcp_servers\."aws-client-agent-mcp"\]/g)).toHaveLength(1);
        expect(written).toContain('args = ["new-index.js"]');
        expect(written).toContain('AWS_AGENT_ID = "agent-2"');
        expect(written).not.toContain('agent-1');
    });
    it('removes the MCP block and its nested env table only', async () => {
        const adapter = new CodexMcpAdapter(configPath);
        await writeFile(configPath, [
            'model = "gpt-5.1"',
            '',
            '[mcp_servers."aws-client-agent-mcp"]',
            'command = "node"',
            'args = ["old.js"]',
            '',
            '[mcp_servers."aws-client-agent-mcp".env]',
            'AWS_AGENT_ID = "agent-1"',
            '',
            '[model_providers.custom]',
            'name = "Custom"',
            '',
        ].join('\n'), 'utf-8');
        await adapter.removeServer(buildServer());
        const written = await readFile(configPath, 'utf-8');
        expect(written).toContain('model = "gpt-5.1"');
        expect(written).toContain('[model_providers.custom]');
        expect(written).not.toContain('aws-client-agent-mcp');
        expect(written).not.toContain('AWS_AGENT_ID');
    });
    it('imports Codex MCP blocks', async () => {
        const adapter = new CodexMcpAdapter(configPath);
        await adapter.syncServer(buildServer());
        const servers = await adapter.importServers();
        expect(servers).toHaveLength(1);
        expect(servers[0]).toMatchObject({
            name: 'aws-client-agent-mcp',
            apps: { codex: true },
            server: {
                type: 'stdio',
                command: 'node',
                args: ['D:\\code\\AgentsWorkStudio\\aws-runtime-bridge\\package\\cc-switch-sdk\\dist\\index.js'],
                env: { AWS_AGENT_ID: 'agent-1' },
            },
        });
    });
});
