"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const claude_extension_hosts_1 = require("../../shared/claude-extension-hosts");
const claude_extension_setup_1 = require("../../shared/claude-extension-setup");
const claude_extension_binding_service_1 = require("../services/claude-extension-binding-service");
const claude_extension_settings_service_1 = require("../services/claude-extension-settings-service");
const auth_middleware_1 = require("../middleware/auth-middleware");
const router = (0, express_1.Router)();
const VALID_HOSTS = new Set(claude_extension_hosts_1.CLAUDE_EXTENSION_HOSTS.map((host) => host.id));
const SETUP_LOCAL_ACCESS_ERROR = 'Claude extension setup requires localhost access when dashboard auth is disabled.';
const VALID_TARGETS = new Set(['shared', 'ide', 'all']);
function getHostFromRequest(req) {
    const rawHost = String(req.query.host || 'vscode');
    if (!VALID_HOSTS.has(rawHost)) {
        throw new Error(`Invalid host "${rawHost}". Use: ${claude_extension_hosts_1.CLAUDE_EXTENSION_HOSTS.map((host) => host.id).join(', ')}`);
    }
    return rawHost;
}
function getActionTarget(req) {
    const rawTarget = req.body && typeof req.body.target === 'string' ? req.body.target.trim().toLowerCase() : 'all';
    if (!VALID_TARGETS.has(rawTarget)) {
        throw new Error('Invalid target. Use: shared, ide, or all');
    }
    return rawTarget;
}
function serializeBinding(id) {
    const binding = (0, claude_extension_binding_service_1.getClaudeExtensionBinding)(id);
    return {
        ...binding,
        effectiveIdeSettingsPath: (0, claude_extension_settings_service_1.resolveClaudeExtensionIdeSettingsPath)(binding),
        usesDefaultIdeSettingsPath: !binding.ideSettingsPath,
    };
}
function handleRouteError(res, error) {
    const message = error.message;
    if (message.startsWith('Binding not found')) {
        res.status(404).json({ error: message });
        return;
    }
    res.status(400).json({ error: message });
}
router.get('/profiles', (_req, res) => {
    res.json({
        profiles: (0, claude_extension_setup_1.listClaudeExtensionProfiles)(),
        hosts: claude_extension_hosts_1.CLAUDE_EXTENSION_HOSTS.map((host) => ({
            ...host,
            defaultSettingsPath: (0, claude_extension_settings_service_1.getDefaultClaudeExtensionIdeSettingsPath)(host.id),
        })),
    });
});
router.get('/setup', async (req, res) => {
    if (!(0, auth_middleware_1.requireLocalAccessWhenAuthDisabled)(req, res, SETUP_LOCAL_ACCESS_ERROR)) {
        return;
    }
    const rawProfile = typeof req.query.profile === 'string' ? req.query.profile.trim() : '';
    if (!rawProfile) {
        res.status(400).json({ error: 'Missing required query parameter: profile' });
        return;
    }
    try {
        const host = getHostFromRequest(req);
        const setup = await (0, claude_extension_setup_1.resolveClaudeExtensionSetup)(rawProfile);
        const hostDefinition = (0, claude_extension_hosts_1.getClaudeExtensionHostDefinition)(host);
        res.json({
            profile: {
                requestedProfile: setup.requestedProfile,
                resolvedProfileName: setup.resolvedProfileName,
                profileType: setup.profileType,
                label: setup.profileLabel,
                description: setup.profileDescription,
            },
            host: hostDefinition,
            env: Object.entries(setup.extensionEnv).map(([name, value]) => ({ name, value })),
            warnings: setup.warnings,
            notes: setup.notes,
            removeEnvKeys: setup.removeEnvKeys,
            sharedSettings: {
                path: (0, claude_extension_setup_1.getClaudeSharedSettingsPath)(),
                command: `ccs persist ${rawProfile}`,
                json: (0, claude_extension_setup_1.renderSharedClaudeSettingsJson)(setup),
            },
            ideSettings: {
                path: (0, claude_extension_settings_service_1.getDefaultClaudeExtensionIdeSettingsPath)(host),
                targetLabel: hostDefinition.settingsTargetLabel,
                json: (0, claude_extension_setup_1.renderClaudeExtensionSettingsJson)(setup, host),
            },
        });
    }
    catch (error) {
        handleRouteError(res, error);
    }
});
router.get('/bindings', (_req, res) => {
    try {
        res.json({
            bindings: (0, claude_extension_binding_service_1.listClaudeExtensionBindings)().map((binding) => ({
                ...binding,
                effectiveIdeSettingsPath: (0, claude_extension_settings_service_1.resolveClaudeExtensionIdeSettingsPath)(binding),
                usesDefaultIdeSettingsPath: !binding.ideSettingsPath,
            })),
        });
    }
    catch (error) {
        handleRouteError(res, error);
    }
});
router.post('/bindings', (req, res) => {
    try {
        const binding = (0, claude_extension_binding_service_1.createClaudeExtensionBinding)(req.body);
        res.status(201).json({ binding: serializeBinding(binding.id) });
    }
    catch (error) {
        handleRouteError(res, error);
    }
});
router.put('/bindings/:id', (req, res) => {
    try {
        const binding = (0, claude_extension_binding_service_1.updateClaudeExtensionBinding)(req.params.id, req.body);
        res.json({ binding: serializeBinding(binding.id) });
    }
    catch (error) {
        handleRouteError(res, error);
    }
});
router.delete('/bindings/:id', (req, res) => {
    try {
        (0, claude_extension_binding_service_1.deleteClaudeExtensionBinding)(req.params.id);
        res.status(204).end();
    }
    catch (error) {
        handleRouteError(res, error);
    }
});
router.get('/bindings/:id/verify', async (req, res) => {
    try {
        const binding = (0, claude_extension_binding_service_1.getClaudeExtensionBinding)(req.params.id);
        const status = await (0, claude_extension_settings_service_1.verifyClaudeExtensionBinding)(binding);
        res.json({ binding: serializeBinding(binding.id), ...status });
    }
    catch (error) {
        handleRouteError(res, error);
    }
});
router.post('/bindings/:id/apply', async (req, res) => {
    try {
        const binding = (0, claude_extension_binding_service_1.getClaudeExtensionBinding)(req.params.id);
        const status = await (0, claude_extension_settings_service_1.applyClaudeExtensionBinding)(binding, getActionTarget(req));
        res.json({ binding: serializeBinding(binding.id), ...status });
    }
    catch (error) {
        handleRouteError(res, error);
    }
});
router.post('/bindings/:id/reset', async (req, res) => {
    try {
        const binding = (0, claude_extension_binding_service_1.getClaudeExtensionBinding)(req.params.id);
        const status = await (0, claude_extension_settings_service_1.resetClaudeExtensionBinding)(binding, getActionTarget(req));
        res.json({ binding: serializeBinding(binding.id), ...status });
    }
    catch (error) {
        handleRouteError(res, error);
    }
});
exports.default = router;
//# sourceMappingURL=claude-extension-routes.js.map