"use strict";
/**
 * Auto-Sync Watcher
 *
 * Watches for profile settings changes and automatically syncs to local CLIProxy config.
 * Uses debouncing to prevent sync storms during rapid edits.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resetWatcherState = exports.getAutoSyncStatus = exports.restartAutoSyncWatcher = exports.stopAutoSyncWatcher = exports.startAutoSyncWatcher = exports.isAutoSyncEnabled = void 0;
const chokidar = __importStar(require("chokidar"));
const path = __importStar(require("path"));
const local_config_sync_1 = require("./local-config-sync");
const config_loader_facade_1 = require("../../config/config-loader-facade");
/** Debounce delay in milliseconds */
const DEBOUNCE_MS = 3000;
/** Singleton watcher instance */
let watcherInstance = null;
let syncTimeout = null;
let isSyncing = false;
/**
 * Check if auto-sync is enabled in config.
 */
function isAutoSyncEnabled() {
    try {
        const config = (0, config_loader_facade_1.loadOrCreateUnifiedConfig)();
        // For local sync, check cliproxy.auto_sync (simpler config location)
        return config.cliproxy?.auto_sync === true;
    }
    catch {
        return false;
    }
}
exports.isAutoSyncEnabled = isAutoSyncEnabled;
/**
 * Log auto-sync message.
 */
function log(message) {
    console.log(`[auto-sync] ${message}`);
}
/**
 * Execute sync to local CLIProxy config.
 */
async function triggerSync() {
    if (isSyncing) {
        log('Sync already in progress, skipping');
        return;
    }
    if (!isAutoSyncEnabled()) {
        log('Auto-sync disabled, skipping');
        return;
    }
    isSyncing = true;
    try {
        const result = (0, local_config_sync_1.syncToLocalConfig)();
        if (!result.success) {
            log(`Sync failed: ${result.error}`);
            return;
        }
        if (result.syncedCount === 0) {
            log('No profiles to sync');
            return;
        }
        log(`Success: ${result.syncedCount} profile(s) synced to ${result.configPath}`);
    }
    catch (error) {
        log(`Sync error: ${error.message}`);
    }
    finally {
        isSyncing = false;
    }
}
/**
 * Handle file change event with debouncing.
 */
function onFileChange(filePath) {
    const fileName = path.basename(filePath);
    log(`Profile change detected: ${fileName}`);
    // Clear existing timeout
    if (syncTimeout) {
        clearTimeout(syncTimeout);
    }
    log(`Waiting ${DEBOUNCE_MS / 1000}s for additional changes...`);
    // Set new debounced timeout
    syncTimeout = setTimeout(() => {
        syncTimeout = null;
        triggerSync().catch((err) => {
            log(`Sync error: ${err.message}`);
        });
    }, DEBOUNCE_MS);
}
/**
 * Start the auto-sync watcher.
 * Watches ~/.ccs/*.settings.json for changes.
 */
function startAutoSyncWatcher() {
    if (watcherInstance) {
        log('Watcher already running');
        return;
    }
    if (!isAutoSyncEnabled()) {
        // Don't start if disabled, but log nothing (called at startup)
        return;
    }
    const ccsDir = (0, config_loader_facade_1.getCcsDir)();
    const watchPattern = path.join(ccsDir, '*.settings.json');
    log(`Starting watcher on ${watchPattern}`);
    watcherInstance = chokidar.watch(watchPattern, {
        ignoreInitial: true, // Don't trigger on initial scan
        persistent: true,
        awaitWriteFinish: {
            stabilityThreshold: 500,
            pollInterval: 100,
        },
    });
    watcherInstance.on('change', onFileChange);
    watcherInstance.on('add', onFileChange);
    watcherInstance.on('unlink', onFileChange);
    watcherInstance.on('error', (error) => {
        log(`Watcher error: ${error.message}`);
    });
    log('Watcher started');
}
exports.startAutoSyncWatcher = startAutoSyncWatcher;
/**
 * Stop the auto-sync watcher.
 */
async function stopAutoSyncWatcher() {
    if (syncTimeout) {
        clearTimeout(syncTimeout);
        syncTimeout = null;
    }
    if (watcherInstance) {
        const closePromise = watcherInstance.close();
        const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error('Close timeout')), 5000));
        try {
            await Promise.race([closePromise, timeoutPromise]);
        }
        catch (err) {
            log(`Warning: ${err.message}, forcing cleanup`);
        }
        watcherInstance = null;
        log('Watcher stopped');
    }
    // Reset flag to prevent stale state
    isSyncing = false;
}
exports.stopAutoSyncWatcher = stopAutoSyncWatcher;
/**
 * Restart the watcher (after config change).
 */
async function restartAutoSyncWatcher() {
    // Wait for any active sync to complete (max 10s)
    const maxWait = 10000;
    const start = Date.now();
    while (isSyncing && Date.now() - start < maxWait) {
        await new Promise((resolve) => setTimeout(resolve, 100));
    }
    if (isSyncing) {
        log('Warning: Sync still in progress after 10s timeout, proceeding with restart');
    }
    await stopAutoSyncWatcher();
    startAutoSyncWatcher();
}
exports.restartAutoSyncWatcher = restartAutoSyncWatcher;
/**
 * Get watcher status.
 */
function getAutoSyncStatus() {
    return {
        enabled: isAutoSyncEnabled(),
        watching: watcherInstance !== null,
        syncing: isSyncing,
    };
}
exports.getAutoSyncStatus = getAutoSyncStatus;
/**
 * Reset watcher state for test cleanup.
 * Stops watcher and clears all singleton state.
 */
async function resetWatcherState() {
    await stopAutoSyncWatcher();
    watcherInstance = null;
    syncTimeout = null;
    isSyncing = false;
}
exports.resetWatcherState = resetWatcherState;
//# sourceMappingURL=auto-sync-watcher.js.map