import { mkdir, mkdtemp, readFile, readdir, 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 { discoverCcSwitchConfiguredItems, loadCcSwitchSdk } from './cc-switch-sdk.js';
import { getAgentInitRoot } from './instance-state.js';
import { syncLegacyStateFromSdk } from './instance-init-service.js';
describe('CC Switch discovery flow', () => {
    const previousRuntimeHome = process.env.AWS_RUNTIME_HOME_DIR;
    let runtimeHome = '';
    let agentId = '';
    beforeEach(async () => {
        runtimeHome = await mkdtemp(path.join(os.tmpdir(), 'cc-switch-discovery-runtime-'));
        agentId = `agent-discovery-${Date.now()}-${Math.random().toString(36).slice(2)}`;
        process.env.AWS_RUNTIME_HOME_DIR = runtimeHome;
    });
    afterEach(async () => {
        if (previousRuntimeHome === undefined) {
            delete process.env.AWS_RUNTIME_HOME_DIR;
        }
        else {
            process.env.AWS_RUNTIME_HOME_DIR = previousRuntimeHome;
        }
        await rm(runtimeHome, { recursive: true, force: true });
        if (agentId) {
            await rm(getAgentInitRoot(agentId), { recursive: true, force: true });
        }
    });
    it('discovers configured MCP and Skill items into instance state without rewriting source app files', async () => {
        const opencodeConfigPath = path.join(runtimeHome, '.config', 'opencode', 'opencode.json');
        const codexSkillDir = path.join(runtimeHome, '.codex', 'skills', 'codex-review');
        const opencodeConfig = {
            theme: 'dark',
            mcpServers: {
                'legacy-opencode': {
                    type: 'remote',
                    url: 'http://localhost:9999/sse',
                },
            },
        };
        await mkdir(path.dirname(opencodeConfigPath), { recursive: true });
        await writeFile(opencodeConfigPath, JSON.stringify(opencodeConfig, null, 2), 'utf-8');
        await mkdir(codexSkillDir, { recursive: true });
        await writeFile(path.join(codexSkillDir, 'SKILL.md'), '---\nname: Codex Review\ndescription: Review code with Codex\n---\n# Skill\n', 'utf-8');
        const beforeOpencodeRaw = await readFile(opencodeConfigPath, 'utf-8');
        const beforeCodexEntries = await readdir(path.dirname(codexSkillDir));
        const sdk = await loadCcSwitchSdk(agentId);
        const imported = await discoverCcSwitchConfiguredItems(sdk);
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        expect(imported).toEqual({ mcpServers: 1, skills: 1 });
        expect(synced.state.mcpServers.some((item) => item.name === 'legacy-opencode')).toBe(true);
        expect(synced.state.skills.some((item) => item.name === 'Codex Review')).toBe(true);
        expect(await readFile(opencodeConfigPath, 'utf-8')).toBe(beforeOpencodeRaw);
        expect(await readdir(path.dirname(codexSkillDir))).toEqual(beforeCodexEntries);
    });
});
