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 { ClaudecodeMcpAdapter } from './mcp-claudecode.js';
let tempDir;
let configPath;
function buildServer(name = 'agents-work-studio') {
    return {
        id: 'mcp_test',
        name,
        server: {
            type: 'stdio',
            command: 'cmd',
            args: ['/c', 'node', 'D:\\code\\AgentsWorkStudio\\aws-runtime-bridge\\package\\aws-client-agent-mcp\\dist\\index.js'],
            env: {
                AWS_SERVER_URL: 'ws://localhost:8080/ws/agent',
            },
        },
        apps: {
            claude: false,
            claudecode: true,
            codex: false,
            gemini: false,
            opencode: false,
            openclaw: false,
        },
    };
}
beforeEach(async () => {
    tempDir = await mkdtemp(path.join(os.tmpdir(), 'claudecode-mcp-adapter-'));
    configPath = path.join(tempDir, '.claude.json');
});
afterEach(async () => {
    await rm(tempDir, { recursive: true, force: true });
});
describe('ClaudecodeMcpAdapter', () => {
    it('syncs MCP servers into Claude Code global mcpServers', async () => {
        const adapter = new ClaudecodeMcpAdapter(configPath);
        await adapter.syncServer(buildServer());
        const written = JSON.parse(await readFile(configPath, 'utf-8'));
        expect(written.mcpServers?.['agents-work-studio']).toMatchObject({
            type: 'stdio',
            command: 'cmd',
            args: ['/c', 'node', 'D:\\code\\AgentsWorkStudio\\aws-runtime-bridge\\package\\aws-client-agent-mcp\\dist\\index.js'],
            env: {
                AWS_SERVER_URL: 'ws://localhost:8080/ws/agent',
            },
        });
    });
    it('removes MCP servers from Claude Code global mcpServers while preserving other settings', async () => {
        const adapter = new ClaudecodeMcpAdapter(configPath);
        await writeFile(configPath, JSON.stringify({
            env: { ANTHROPIC_MODEL: 'test' },
            mcpServers: {
                'agents-work-studio': {
                    command: 'cmd',
                    args: ['/c', 'node', 'old.js'],
                    type: 'stdio',
                },
                playwright: {
                    command: 'cmd',
                    args: ['/c', 'npx', '@playwright/mcp@latest'],
                    type: 'stdio',
                },
            },
        }), 'utf-8');
        await adapter.removeServer(buildServer());
        const written = JSON.parse(await readFile(configPath, 'utf-8'));
        expect(written.env?.ANTHROPIC_MODEL).toBe('test');
        expect(written.mcpServers?.['agents-work-studio']).toBeUndefined();
        expect(written.mcpServers?.playwright).toBeDefined();
    });
});
