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 { OpenCodeMcpAdapter } from './mcp-opencode.js';
let tempDir;
let configPath;
function buildServer(name = 'new-server') {
    return {
        id: 'mcp_test',
        name,
        server: { type: 'stdio', command: 'node', args: ['server.js'] },
        apps: {
            acode: false,
            claude: false,
            claudecode: false,
            codex: false,
            gemini: false,
            opencode: true,
            openclaw: false,
        },
    };
}
beforeEach(async () => {
    tempDir = await mkdtemp(path.join(os.tmpdir(), 'opencode-mcp-adapter-'));
    configPath = path.join(tempDir, 'opencode.json');
});
afterEach(async () => {
    await rm(tempDir, { recursive: true, force: true });
});
describe('OpenCodeMcpAdapter', () => {
    it('imports both current mcp and legacy mcpServers maps', async () => {
        await writeFile(configPath, JSON.stringify({
            mcp: {
                current: { type: 'local', command: ['node', 'current.js'] },
            },
            mcpServers: {
                legacy: { type: 'remote', url: 'http://legacy.example.com/sse' },
            },
        }), 'utf-8');
        const adapter = new OpenCodeMcpAdapter(configPath);
        const imported = await adapter.importServers();
        expect(imported.map((item) => item.name).sort()).toEqual(['current', 'legacy']);
    });
    it('writes merged MCP map back to mcp and removes legacy mcpServers', async () => {
        await writeFile(configPath, JSON.stringify({
            theme: 'dark',
            mcpServers: {
                legacy: { type: 'remote', url: 'http://legacy.example.com/sse' },
            },
        }), 'utf-8');
        const adapter = new OpenCodeMcpAdapter(configPath);
        await adapter.syncServer(buildServer());
        const written = JSON.parse(await readFile(configPath, 'utf-8'));
        expect(written.theme).toBe('dark');
        expect(written.mcpServers).toBeUndefined();
        expect(written.mcp).toMatchObject({
            legacy: { type: 'remote', url: 'http://legacy.example.com/sse' },
            'new-server': { type: 'local', command: ['node', 'server.js'] },
        });
    });
});
