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 { resolveSkillSourceDir, ensureDirectoryExists } from '../utils/file-utils.js';
import { normalizeSdkAppFlags } from '../utils/mcp-utils.js';
export const skillsRouter = Router();
const TOGGLEABLE_APP_IDS = new Set(['acode', 'claudecode', 'opencode']);
skillsRouter.post('/cc-switch/skills/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 skills = sdk.getAllSkills();
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        res.json({ ok: true, agentId: String(agentId), imported, skills, state: synced.state });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'list skills failed' });
    }
});
skillsRouter.post('/cc-switch/skills/get', validateToken, async (req, res) => {
    const { agentId, skillId } = req.body || {};
    if (!agentId || !skillId) {
        res.status(400).json({ error: 'agentId and skillId are required' });
        return;
    }
    try {
        const sdk = await loadCcSwitchSdk(agentId);
        const skill = sdk.getSkillById(String(skillId));
        if (!skill) {
            res.status(404).json({ error: 'skill not found' });
            return;
        }
        res.json({ ok: true, agentId: String(agentId), skill });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'get skill failed' });
    }
});
skillsRouter.post('/cc-switch/skills/create', validateToken, async (req, res) => {
    const { agentId, skill } = req.body || {};
    if (!agentId) {
        res.status(400).json({ error: 'agentId is required' });
        return;
    }
    try {
        const sourceDir = resolveSkillSourceDir(skill);
        await ensureDirectoryExists(sourceDir);
        const sdk = await loadCcSwitchSdk(agentId);
        const created = await sdk.installSkill({
            sourceDir,
            name: skill?.name ? String(skill.name).trim() : undefined,
            description: skill?.description == null ? undefined : String(skill.description),
            apps: normalizeSdkAppFlags(skill?.apps),
        });
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        const adapterResult = await runCcSwitchAdapter('create-skill', agentId, created);
        res.json({ ok: true, agentId: String(agentId), skill: created, state: synced.state, adapterResult });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'create skill failed' });
    }
});
skillsRouter.post('/cc-switch/skills/update', validateToken, async (req, res) => {
    const { agentId, skillId, skill } = req.body || {};
    if (!agentId || !skillId) {
        res.status(400).json({ error: 'agentId and skillId are required' });
        return;
    }
    try {
        const sdk = await loadCcSwitchSdk(agentId);
        const updated = await sdk.updateSkill(String(skillId), {
            name: skill?.name == null ? undefined : String(skill.name).trim(),
            description: skill?.description == null ? undefined : String(skill.description),
            apps: normalizeSdkAppFlags(skill?.apps),
        });
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        const adapterResult = await runCcSwitchAdapter('update-skill', agentId, updated);
        res.json({ ok: true, agentId: String(agentId), skill: updated, state: synced.state, adapterResult });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'update skill failed' });
    }
});
skillsRouter.post('/cc-switch/skills/toggle-app', validateToken, async (req, res) => {
    const { agentId, skillId, appId, enabled } = req.body || {};
    if (!agentId || !skillId || !appId) {
        res.status(400).json({ error: 'agentId, skillId 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 acode, claudecode, opencode' });
            return;
        }
        const sdk = await loadCcSwitchSdk(agentId);
        const updated = await sdk.toggleSkillApp(String(skillId), normalizedAppId, enabled === true);
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        const adapterResult = await runCcSwitchAdapter('toggle-skill-app', agentId, updated, sdk);
        res.json({ ok: true, agentId: String(agentId), skill: updated, state: synced.state, adapterResult });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'toggle skill app failed' });
    }
});
skillsRouter.post('/cc-switch/skills/delete', validateToken, async (req, res) => {
    const { agentId, skillId } = req.body || {};
    if (!agentId || !skillId) {
        res.status(400).json({ error: 'agentId and skillId are required' });
        return;
    }
    try {
        const sdk = await loadCcSwitchSdk(agentId);
        const existing = sdk.getSkillById(String(skillId));
        if (!existing) {
            res.status(404).json({ error: 'skill not found' });
            return;
        }
        await sdk.uninstallSkill(String(skillId));
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        const adapterResult = await runCcSwitchAdapter('delete-skill', agentId, existing);
        res.json({ ok: true, agentId: String(agentId), removedSkill: existing, state: synced.state, adapterResult });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'delete skill failed' });
    }
});
skillsRouter.post('/cc-switch/add-skill', validateToken, async (req, res) => {
    const { agentId, skill } = req.body || {};
    if (!agentId) {
        res.status(400).json({ error: 'agentId is required' });
        return;
    }
    try {
        const sourceDir = resolveSkillSourceDir(skill);
        await ensureDirectoryExists(sourceDir);
        const sdk = await loadCcSwitchSdk(agentId);
        const created = await sdk.installSkill({
            sourceDir,
            name: skill?.name ? String(skill.name).trim() : undefined,
            description: skill?.description == null ? undefined : String(skill.description),
            apps: normalizeSdkAppFlags(skill?.apps),
        });
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        const adapterResult = await runCcSwitchAdapter('create-skill', agentId, created);
        res.json({ ok: true, agentId: String(agentId), skill: created, state: synced.state, adapterResult });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'add skill failed' });
    }
});
skillsRouter.post('/cc-switch/remove-skill', validateToken, async (req, res) => {
    const { agentId, skillId } = req.body || {};
    if (!agentId || !skillId) {
        res.status(400).json({ error: 'agentId and skillId are required' });
        return;
    }
    try {
        const sdk = await loadCcSwitchSdk(agentId);
        const existing = sdk.getSkillById(String(skillId));
        if (!existing) {
            res.status(404).json({ error: 'skill not found' });
            return;
        }
        await sdk.uninstallSkill(String(skillId));
        const synced = await syncLegacyStateFromSdk(agentId, sdk);
        const adapterResult = await runCcSwitchAdapter('delete-skill', agentId, existing);
        res.json({ ok: true, agentId: String(agentId), removedSkill: existing, state: synced.state, adapterResult });
    }
    catch (error) {
        const err = error;
        res.status(400).json({ error: err?.message || 'remove skill failed' });
    }
});
