"use strict";
/**
 * Cursor Routes - Cursor IDE integration via cursor proxy daemon
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDaemonStartPreconditionError = exports.getAutoDetectFailureStatus = void 0;
const express_1 = require("express");
const cursor_1 = require("../../cursor");
const cursor_settings_routes_1 = __importDefault(require("./cursor-settings-routes"));
const config_loader_facade_1 = require("../../config/config-loader-facade");
const router = (0, express_1.Router)();
function getAutoDetectFailureStatus(reason) {
    switch (reason) {
        case 'sqlite_unavailable':
            return 503;
        case 'db_query_failed':
            return 500;
        case 'invalid_token_format':
            return 400;
        default:
            return 404;
    }
}
exports.getAutoDetectFailureStatus = getAutoDetectFailureStatus;
function getPublicAutoDetectError(result) {
    switch (result.reason) {
        case 'db_not_found':
            return 'Cursor state database not found on this host.';
        case 'sqlite_unavailable':
            return 'Cursor state database was found, but sqlite3 is not available in PATH.';
        case 'db_query_failed':
            return 'Cursor state database was found, but CCS could not query it.';
        default:
            return result.error ?? 'Token not found';
    }
}
function getDaemonStartPreconditionError(input) {
    if (!input.enabled) {
        return {
            status: 400,
            error: 'Cursor integration is disabled. Enable it before starting daemon.',
        };
    }
    if (!input.authenticated) {
        return {
            status: 401,
            error: 'Cursor authentication required. Import credentials before starting daemon.',
        };
    }
    if (input.tokenExpired) {
        return {
            status: 401,
            error: 'Cursor credentials expired. Re-authenticate before starting daemon.',
        };
    }
    return null;
}
exports.getDaemonStartPreconditionError = getDaemonStartPreconditionError;
// Mount settings sub-routes
router.use('/settings', cursor_settings_routes_1.default);
/**
 * GET /api/cursor/status - Get Cursor status (auth + daemon)
 */
router.get('/status', async (_req, res) => {
    try {
        const cursorConfig = (0, config_loader_facade_1.getCursorConfig)();
        const authStatus = (0, cursor_1.checkAuthStatus)();
        const daemonStatus = await (0, cursor_1.getDaemonStatus)(cursorConfig.port);
        res.json({
            enabled: cursorConfig.enabled,
            authenticated: authStatus.authenticated,
            auth_method: authStatus.credentials?.authMethod ?? null,
            token_age: authStatus.tokenAge ?? null,
            token_expired: authStatus.expired ?? false,
            daemon_running: daemonStatus.running,
            port: cursorConfig.port,
            auto_start: cursorConfig.auto_start,
            ghost_mode: cursorConfig.ghost_mode,
        });
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
/**
 * POST /api/cursor/auth/import - Import Cursor token manually
 */
router.post('/auth/import', async (req, res) => {
    try {
        const { accessToken, machineId } = req.body;
        if (!accessToken || !machineId) {
            res.status(400).json({ error: 'Missing accessToken or machineId' });
            return;
        }
        // Validate token format
        if (!(0, cursor_1.validateToken)(accessToken, machineId)) {
            res.status(400).json({ error: 'Invalid token or machine ID format' });
            return;
        }
        // Save credentials
        (0, cursor_1.saveCredentials)({
            accessToken,
            machineId,
            authMethod: 'manual',
            importedAt: new Date().toISOString(),
        });
        res.json({ success: true, message: 'Token imported successfully' });
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
/**
 * POST /api/cursor/auth/auto-detect - Auto-detect token from SQLite
 */
router.post('/auth/auto-detect', async (_req, res) => {
    try {
        const result = (0, cursor_1.autoDetectTokens)();
        if (!result.found || !result.accessToken || !result.machineId) {
            const status = getAutoDetectFailureStatus(result.reason);
            res.status(status).json({
                error: getPublicAutoDetectError(result),
                reason: result.reason ?? null,
            });
            return;
        }
        // Save credentials
        (0, cursor_1.saveCredentials)({
            accessToken: result.accessToken,
            machineId: result.machineId,
            authMethod: 'auto-detect',
            importedAt: new Date().toISOString(),
        });
        res.json({ success: true, message: 'Token auto-detected and imported' });
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
/**
 * GET /api/cursor/models - List available models
 */
router.get('/models', async (_req, res) => {
    try {
        const cursorConfig = (0, config_loader_facade_1.getCursorConfig)();
        const models = await (0, cursor_1.getAvailableModels)(cursorConfig.port);
        res.json({ models, current: cursorConfig.model });
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
/**
 * POST /api/cursor/probe - Run a live authenticated runtime probe
 */
router.post('/probe', async (_req, res) => {
    try {
        const cursorConfig = (0, config_loader_facade_1.getCursorConfig)();
        const result = await (0, cursor_1.probeCursorRuntime)(cursorConfig);
        res.status(result.status).json(result);
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
/**
 * POST /api/cursor/daemon/start - Start cursor proxy daemon
 * Path matches copilot convention: /api/{provider}/daemon/{action}
 */
router.post('/daemon/start', async (_req, res) => {
    try {
        const cursorConfig = (0, config_loader_facade_1.getCursorConfig)();
        const authStatus = (0, cursor_1.checkAuthStatus)();
        const preconditionError = getDaemonStartPreconditionError({
            enabled: cursorConfig.enabled,
            authenticated: authStatus.authenticated,
            tokenExpired: authStatus.expired ?? false,
        });
        if (preconditionError) {
            res.status(preconditionError.status).json({
                success: false,
                error: preconditionError.error,
            });
            return;
        }
        const result = await (0, cursor_1.startDaemon)({
            port: cursorConfig.port,
            ghost_mode: cursorConfig.ghost_mode,
        });
        res.json(result);
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
/**
 * POST /api/cursor/daemon/stop - Stop cursor proxy daemon
 * Path matches copilot convention: /api/{provider}/daemon/{action}
 */
router.post('/daemon/stop', async (_req, res) => {
    try {
        const result = await (0, cursor_1.stopDaemon)();
        res.json(result);
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
exports.default = router;
//# sourceMappingURL=cursor-routes.js.map