"use strict";
/**
 * CLIProxy Sync Routes - Local sync management for CLIProxy profiles
 */
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const sync_1 = require("../../cliproxy/sync");
const config_loader_facade_1 = require("../../config/config-loader-facade");
const router = (0, express_1.Router)();
/**
 * GET /api/cliproxy/sync/status - Get local sync status
 * Returns: { configExists, configPath, currentKeyCount, syncableProfileCount }
 */
router.get('/status', async (_req, res) => {
    try {
        const status = (0, sync_1.getLocalSyncStatus)();
        res.json({
            configured: status.configExists,
            configPath: status.configPath,
            currentKeyCount: status.currentKeyCount,
            syncableProfileCount: status.syncableProfileCount,
        });
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
/**
 * GET /api/cliproxy/sync/preview - Get sync preview (dry run)
 * Returns: { profiles: SyncPreviewItem[], payload: ClaudeKey[] }
 */
router.get('/preview', async (_req, res) => {
    try {
        const preview = (0, sync_1.generateSyncPreview)();
        const payload = (0, sync_1.generateSyncPayload)();
        // Mask API keys in payload for preview
        const maskedPayload = payload.map((key) => ({
            ...key,
            'api-key': maskApiKey(key['api-key']),
        }));
        res.json({
            profiles: preview,
            payload: maskedPayload,
            count: payload.length,
        });
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
/**
 * POST /api/cliproxy/sync - Execute sync to local CLIProxy config
 * Returns: { success, syncedCount, configPath, error? }
 */
router.post('/', async (_req, res) => {
    try {
        const result = (0, sync_1.syncToLocalConfig)();
        if (!result.success) {
            res.status(500).json({
                success: false,
                error: result.error,
                configPath: result.configPath,
            });
            return;
        }
        if (result.syncedCount === 0) {
            res.json({
                success: true,
                syncedCount: 0,
                message: 'No profiles to sync',
                configPath: result.configPath,
            });
            return;
        }
        const preview = (0, sync_1.generateSyncPreview)();
        res.json({
            success: true,
            syncedCount: result.syncedCount,
            configPath: result.configPath,
            profiles: preview.map((p) => p.name),
        });
    }
    catch (error) {
        res.status(500).json({
            success: false,
            error: error.message,
        });
    }
});
// ==================== Auto-Sync ====================
/**
 * GET /api/cliproxy/sync/auto-sync - Get auto-sync status
 * Returns: { enabled, watching, syncing }
 */
router.get('/auto-sync', async (_req, res) => {
    try {
        const status = (0, sync_1.getAutoSyncStatus)();
        res.json(status);
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
/**
 * PUT /api/cliproxy/sync/auto-sync - Toggle auto-sync setting
 * Body: { enabled: boolean }
 * Returns: { success: true, enabled }
 */
router.put('/auto-sync', async (req, res) => {
    try {
        const { enabled } = req.body;
        if (typeof enabled !== 'boolean') {
            res.status(400).json({ error: 'Invalid field: enabled must be a boolean' });
            return;
        }
        try {
            (0, config_loader_facade_1.mutateConfig)((config) => {
                if (!config.cliproxy) {
                    throw new Error('CLIProxy config not initialized');
                }
                config.cliproxy.auto_sync = enabled;
            });
        }
        catch (error) {
            res.status(500).json({ error: `Failed to save config: ${error.message}` });
            return;
        }
        // Restart watcher (separate operation)
        try {
            await (0, sync_1.restartAutoSyncWatcher)();
        }
        catch (watcherError) {
            // Log but don't fail - config was saved successfully
            console.warn('Watcher restart failed:', watcherError.message);
        }
        res.json({ success: true, enabled });
    }
    catch (error) {
        res.status(500).json({ error: error.message });
    }
});
/**
 * Mask API key for display (show first 4 and last 4 chars).
 */
function maskApiKey(key) {
    if (key.length <= 12) {
        return '***';
    }
    return `${key.slice(0, 4)}...${key.slice(-4)}`;
}
exports.default = router;
//# sourceMappingURL=cliproxy-sync-routes.js.map