import { Router } from 'express';
import { validateToken } from '../middleware/auth.js';
import { discoverCcSwitchConfiguredItems, loadCcSwitchSdk, runCcSwitchAdapter } from '../services/cc-switch-sdk.js';
import { syncLegacyStateFromSdk } from '../services/instance-init-service.js';
import { normalizeSdkAppFlags, normalizeSdkMcpServerSpec } from '../utils/mcp-utils.js';
export const mcpRouter = Router();
const TOGGLEABLE_APP_IDS = new Set(['claudecode', 'opencode', 'codex']);
mcpRouter.post('/cc-switch/mcp/list', validateToken, async (req, res) => {
    const { agentId } = req.body || {};
    if (!agentId) {
        res.status(400).json({ error: 'agentId is required' });
        return;
    }
    try {
        const sdk = await loadCcSwitchSdk(agentId);
        const imported = await discoverCcSwitchConfiguredItems(sdk);
        const mcpServers = sdk.getAllMcpServers();
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        res.json({ ok: true, agentId: String(agentId), imported, mcpServers, state: synced.state, configPath: synced.configPath });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'list mcp failed' });
    }
});
mcpRouter.post('/cc-switch/mcp/get', validateToken, async (req, res) => {
    const { agentId, mcpId } = req.body || {};
    if (!agentId || !mcpId) {
        res.status(400).json({ error: 'agentId and mcpId are required' });
        return;
    }
    try {
        const sdk = await loadCcSwitchSdk(agentId);
        const mcp = sdk.getMcpServerById(String(mcpId));
        if (!mcp) {
            res.status(404).json({ error: 'mcp not found' });
            return;
        }
        res.json({ ok: true, agentId: String(agentId), mcp });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'get mcp failed' });
    }
});
mcpRouter.post('/cc-switch/mcp/create', validateToken, async (req, res) => {
    const { agentId, mcp } = req.body || {};
    if (!agentId) {
        res.status(400).json({ error: 'agentId is required' });
        return;
    }
    try {
        const name = String(mcp?.name || '').trim();
        if (!name) {
            throw new Error('mcp.name is required');
        }
        const sdk = await loadCcSwitchSdk(agentId);
        const input = {
            name,
            server: normalizeSdkMcpServerSpec(mcp),
            description: mcp?.description == null ? undefined : String(mcp.description),
            apps: normalizeSdkAppFlags(mcp?.apps),
        };
        const created = await sdk.createMcpServer(input);
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        const adapterResult = await runCcSwitchAdapter('create-mcp', agentId, created);
        res.json({ ok: true, agentId: String(agentId), mcp: created, state: synced.state, configPath: synced.configPath, adapterResult });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'create mcp failed' });
    }
});
mcpRouter.post('/cc-switch/mcp/update', validateToken, async (req, res) => {
    const { agentId, mcpId, mcp } = req.body || {};
    if (!agentId || !mcpId) {
        res.status(400).json({ error: 'agentId and mcpId are required' });
        return;
    }
    try {
        const sdk = await loadCcSwitchSdk(agentId);
        const input = {
            name: mcp?.name == null ? undefined : String(mcp.name).trim(),
            server: mcp?.server || mcp?.transport || mcp?.command || mcp?.url || mcp?.args || mcp?.env || mcp?.headers
                ? normalizeSdkMcpServerSpec(mcp)
                : undefined,
            description: mcp?.description == null ? undefined : String(mcp.description),
            apps: normalizeSdkAppFlags(mcp?.apps),
        };
        const updated = await sdk.updateMcpServer(String(mcpId), input);
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        const adapterResult = await runCcSwitchAdapter('update-mcp', agentId, updated);
        res.json({ ok: true, agentId: String(agentId), mcp: updated, state: synced.state, configPath: synced.configPath, adapterResult });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'update mcp failed' });
    }
});
mcpRouter.post('/cc-switch/mcp/toggle-app', validateToken, async (req, res) => {
    const { agentId, mcpId, appId, enabled } = req.body || {};
    if (!agentId || !mcpId || !appId) {
        res.status(400).json({ error: 'agentId, mcpId and appId are required' });
        return;
    }
    try {
        const normalizedAppId = String(appId).trim().toLowerCase();
        if (!TOGGLEABLE_APP_IDS.has(normalizedAppId)) {
            res.status(400).json({ error: 'appId must be one of claudecode, opencode, codex' });
            return;
        }
        const sdk = await loadCcSwitchSdk(agentId);
        const updated = await sdk.toggleMcpApp(String(mcpId), normalizedAppId, enabled === true);
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        const adapterResult = await runCcSwitchAdapter('toggle-mcp-app', agentId, updated, sdk);
        res.json({ ok: true, agentId: String(agentId), mcp: updated, state: synced.state, configPath: synced.configPath, adapterResult });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'toggle mcp app failed' });
    }
});
mcpRouter.post('/cc-switch/mcp/delete', validateToken, async (req, res) => {
    const { agentId, mcpId } = req.body || {};
    if (!agentId || !mcpId) {
        res.status(400).json({ error: 'agentId and mcpId are required' });
        return;
    }
    try {
        const sdk = await loadCcSwitchSdk(agentId);
        const existing = sdk.getMcpServerById(String(mcpId));
        if (!existing) {
            res.status(404).json({ error: 'mcp not found' });
            return;
        }
        await sdk.deleteMcpServer(String(mcpId));
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        const adapterResult = await runCcSwitchAdapter('delete-mcp', agentId, existing);
        res.json({ ok: true, agentId: String(agentId), removedMcp: existing, state: synced.state, configPath: synced.configPath, adapterResult });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'delete mcp failed' });
    }
});
mcpRouter.post('/cc-switch/add-mcp', validateToken, async (req, res) => {
    const { agentId, mcp } = req.body || {};
    if (!agentId) {
        res.status(400).json({ error: 'agentId is required' });
        return;
    }
    try {
        const name = String(mcp?.name || '').trim();
        if (!name) {
            throw new Error('mcp.name is required');
        }
        const sdk = await loadCcSwitchSdk(agentId);
        const input = {
            name,
            server: normalizeSdkMcpServerSpec(mcp),
            description: mcp?.description == null ? undefined : String(mcp.description),
            apps: normalizeSdkAppFlags(mcp?.apps),
        };
        const created = await sdk.createMcpServer(input);
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        const adapterResult = await runCcSwitchAdapter('create-mcp', agentId, created);
        res.json({ ok: true, agentId: String(agentId), mcp: created, state: synced.state, configPath: synced.configPath, adapterResult });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'add mcp failed' });
    }
});
mcpRouter.post('/cc-switch/remove-mcp', validateToken, async (req, res) => {
    const { agentId, mcpId } = req.body || {};
    if (!agentId || !mcpId) {
        res.status(400).json({ error: 'agentId and mcpId are required' });
        return;
    }
    try {
        const sdk = await loadCcSwitchSdk(agentId);
        const existing = sdk.getMcpServerById(String(mcpId));
        if (!existing) {
            res.status(404).json({ error: 'mcp not found' });
            return;
        }
        await sdk.deleteMcpServer(String(mcpId));
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        const adapterResult = await runCcSwitchAdapter('delete-mcp', agentId, existing);
        res.json({ ok: true, agentId: String(agentId), removedMcp: existing, state: synced.state, configPath: synced.configPath, adapterResult });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'remove mcp failed' });
    }
});
