"use strict";
/**
 * Unified Config Loader — orchestrator
 *
 * Loads and saves the unified YAML configuration.
 * Provides fallback to legacy JSON format for backward compatibility.
 *
 * Phase 1-6 refactor (issue #1164):
 *   Phase 1 → src/config/loader/io-locks.ts
 *   Phase 2 → src/config/loader/normalizers.ts
 *   Phase 3 → src/config/loader/yaml-serializer.ts
 *   Phase 4 → src/config/loader/defaults-merger.ts
 *   Phase 5 → src/config/loader/config-getters.ts
 *
 * This file re-exports the full public API so all existing import sites
 * continue to work without modification.
 */
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.setDefaultProfile = exports.getDefaultProfile = exports.isUnifiedMode = exports.updateUnifiedConfig = exports.mutateUnifiedConfig = exports.saveUnifiedConfig = exports.loadOrCreateUnifiedConfig = exports.loadUnifiedConfig = exports.getConfigFormat = exports.getCursorConfig = exports.getLoggingConfig = exports.getImageAnalysisConfig = exports.getBrowserConfig = exports.getDashboardAuthConfig = exports.isDashboardAuthEnabled = exports.getOfficialChannelsConfig = exports.getThinkingConfig = exports.getCliproxySafetyConfig = exports.getContinuityInheritanceMap = exports.getGlobalEnvConfig = exports.getWebSearchConfig = exports.mergeWithDefaults = exports.generateYamlWithComments = exports.generateYamlHeader = exports.normalizeOfficialChannelsConfig = exports.normalizeContinuityConfig = exports.normalizeContinuityInheritanceMap = exports.validateCompositeVariants = exports.hasPositiveDuration = exports.normalizeSessionAffinityTtl = exports.canonicalizeBrowserConfig = exports.normalizeBrowserEvalMode = exports.normalizeBrowserPolicy = exports.normalizeBrowserDevtoolsPort = exports.withConfigWriteLock = exports.sleepSync = exports.hasLegacyConfig = exports.hasUnifiedConfig = exports.releaseLock = exports.acquireLock = exports.getConfigJsonPath = exports.getConfigYamlPath = exports.GO_DURATION_PATTERN = exports.GO_DURATION_SEGMENT = exports.LOCK_STALE_MS = exports.CONFIG_LOCK = exports.CONFIG_JSON = exports.CONFIG_YAML = void 0;
const fs = __importStar(require("fs"));
const yaml = __importStar(require("js-yaml"));
const unified_config_types_1 = require("./unified-config-types");
const feature_flags_1 = require("./feature-flags");
// ---------------------------------------------------------------------------
// Phase 1 re-exports: io-locks
// ---------------------------------------------------------------------------
var io_locks_1 = require("./loader/io-locks");
Object.defineProperty(exports, "CONFIG_YAML", { enumerable: true, get: function () { return io_locks_1.CONFIG_YAML; } });
Object.defineProperty(exports, "CONFIG_JSON", { enumerable: true, get: function () { return io_locks_1.CONFIG_JSON; } });
Object.defineProperty(exports, "CONFIG_LOCK", { enumerable: true, get: function () { return io_locks_1.CONFIG_LOCK; } });
Object.defineProperty(exports, "LOCK_STALE_MS", { enumerable: true, get: function () { return io_locks_1.LOCK_STALE_MS; } });
Object.defineProperty(exports, "GO_DURATION_SEGMENT", { enumerable: true, get: function () { return io_locks_1.GO_DURATION_SEGMENT; } });
Object.defineProperty(exports, "GO_DURATION_PATTERN", { enumerable: true, get: function () { return io_locks_1.GO_DURATION_PATTERN; } });
Object.defineProperty(exports, "getConfigYamlPath", { enumerable: true, get: function () { return io_locks_1.getConfigYamlPath; } });
Object.defineProperty(exports, "getConfigJsonPath", { enumerable: true, get: function () { return io_locks_1.getConfigJsonPath; } });
Object.defineProperty(exports, "acquireLock", { enumerable: true, get: function () { return io_locks_1.acquireLock; } });
Object.defineProperty(exports, "releaseLock", { enumerable: true, get: function () { return io_locks_1.releaseLock; } });
Object.defineProperty(exports, "hasUnifiedConfig", { enumerable: true, get: function () { return io_locks_1.hasUnifiedConfig; } });
Object.defineProperty(exports, "hasLegacyConfig", { enumerable: true, get: function () { return io_locks_1.hasLegacyConfig; } });
Object.defineProperty(exports, "sleepSync", { enumerable: true, get: function () { return io_locks_1.sleepSync; } });
Object.defineProperty(exports, "withConfigWriteLock", { enumerable: true, get: function () { return io_locks_1.withConfigWriteLock; } });
const io_locks_2 = require("./loader/io-locks");
// ---------------------------------------------------------------------------
// Phase 2 re-exports: normalizers
// ---------------------------------------------------------------------------
var normalizers_1 = require("./loader/normalizers");
Object.defineProperty(exports, "normalizeBrowserDevtoolsPort", { enumerable: true, get: function () { return normalizers_1.normalizeBrowserDevtoolsPort; } });
Object.defineProperty(exports, "normalizeBrowserPolicy", { enumerable: true, get: function () { return normalizers_1.normalizeBrowserPolicy; } });
Object.defineProperty(exports, "normalizeBrowserEvalMode", { enumerable: true, get: function () { return normalizers_1.normalizeBrowserEvalMode; } });
Object.defineProperty(exports, "canonicalizeBrowserConfig", { enumerable: true, get: function () { return normalizers_1.canonicalizeBrowserConfig; } });
Object.defineProperty(exports, "normalizeSessionAffinityTtl", { enumerable: true, get: function () { return normalizers_1.normalizeSessionAffinityTtl; } });
Object.defineProperty(exports, "hasPositiveDuration", { enumerable: true, get: function () { return normalizers_1.hasPositiveDuration; } });
Object.defineProperty(exports, "validateCompositeVariants", { enumerable: true, get: function () { return normalizers_1.validateCompositeVariants; } });
Object.defineProperty(exports, "normalizeContinuityInheritanceMap", { enumerable: true, get: function () { return normalizers_1.normalizeContinuityInheritanceMap; } });
Object.defineProperty(exports, "normalizeContinuityConfig", { enumerable: true, get: function () { return normalizers_1.normalizeContinuityConfig; } });
Object.defineProperty(exports, "normalizeOfficialChannelsConfig", { enumerable: true, get: function () { return normalizers_1.normalizeOfficialChannelsConfig; } });
const normalizers_2 = require("./loader/normalizers");
// ---------------------------------------------------------------------------
// Phase 3 re-exports: yaml-serializer
// ---------------------------------------------------------------------------
var yaml_serializer_1 = require("./loader/yaml-serializer");
Object.defineProperty(exports, "generateYamlHeader", { enumerable: true, get: function () { return yaml_serializer_1.generateYamlHeader; } });
Object.defineProperty(exports, "generateYamlWithComments", { enumerable: true, get: function () { return yaml_serializer_1.generateYamlWithComments; } });
const yaml_serializer_2 = require("./loader/yaml-serializer");
// ---------------------------------------------------------------------------
// Phase 4 re-exports: defaults-merger
// ---------------------------------------------------------------------------
var defaults_merger_1 = require("./loader/defaults-merger");
Object.defineProperty(exports, "mergeWithDefaults", { enumerable: true, get: function () { return defaults_merger_1.mergeWithDefaults; } });
const defaults_merger_2 = require("./loader/defaults-merger");
var config_getters_1 = require("./loader/config-getters");
Object.defineProperty(exports, "getWebSearchConfig", { enumerable: true, get: function () { return config_getters_1.getWebSearchConfig; } });
Object.defineProperty(exports, "getGlobalEnvConfig", { enumerable: true, get: function () { return config_getters_1.getGlobalEnvConfig; } });
Object.defineProperty(exports, "getContinuityInheritanceMap", { enumerable: true, get: function () { return config_getters_1.getContinuityInheritanceMap; } });
Object.defineProperty(exports, "getCliproxySafetyConfig", { enumerable: true, get: function () { return config_getters_1.getCliproxySafetyConfig; } });
Object.defineProperty(exports, "getThinkingConfig", { enumerable: true, get: function () { return config_getters_1.getThinkingConfig; } });
Object.defineProperty(exports, "getOfficialChannelsConfig", { enumerable: true, get: function () { return config_getters_1.getOfficialChannelsConfig; } });
Object.defineProperty(exports, "isDashboardAuthEnabled", { enumerable: true, get: function () { return config_getters_1.isDashboardAuthEnabled; } });
Object.defineProperty(exports, "getDashboardAuthConfig", { enumerable: true, get: function () { return config_getters_1.getDashboardAuthConfig; } });
Object.defineProperty(exports, "getBrowserConfig", { enumerable: true, get: function () { return config_getters_1.getBrowserConfig; } });
Object.defineProperty(exports, "getImageAnalysisConfig", { enumerable: true, get: function () { return config_getters_1.getImageAnalysisConfig; } });
Object.defineProperty(exports, "getLoggingConfig", { enumerable: true, get: function () { return config_getters_1.getLoggingConfig; } });
Object.defineProperty(exports, "getCursorConfig", { enumerable: true, get: function () { return config_getters_1.getCursorConfig; } });
// ---------------------------------------------------------------------------
// getConfigFormat
// ---------------------------------------------------------------------------
/**
 * Determine which config format is active.
 * Returns 'yaml' if unified config exists or is enabled,
 * 'json' if only legacy config exists,
 * 'none' if no config exists.
 */
function getConfigFormat() {
    if ((0, io_locks_2.hasUnifiedConfig)())
        return 'yaml';
    if ((0, feature_flags_1.isUnifiedConfigEnabled)())
        return 'yaml';
    if ((0, io_locks_2.hasLegacyConfig)())
        return 'json';
    return 'none';
}
exports.getConfigFormat = getConfigFormat;
// ---------------------------------------------------------------------------
// Core load / save / mutate
// ---------------------------------------------------------------------------
/**
 * Load unified config from YAML file.
 * Returns null if file doesn't exist.
 * Auto-upgrades config if version is outdated (regenerates comments).
 */
function loadUnifiedConfig() {
    const yamlPath = (0, io_locks_2.getConfigYamlPath)();
    if (!fs.existsSync(yamlPath)) {
        return null;
    }
    try {
        const content = fs.readFileSync(yamlPath, 'utf8');
        const parsed = yaml.load(content);
        if (!(0, unified_config_types_1.isUnifiedConfig)(parsed)) {
            throw new Error(`Invalid config format in ${yamlPath}`);
        }
        // Auto-upgrade if version is outdated (regenerates YAML with new comments and fields)
        if ((parsed.version ?? 1) < unified_config_types_1.UNIFIED_CONFIG_VERSION) {
            const upgraded = (0, defaults_merger_2.mergeWithDefaults)(parsed);
            upgraded.version = unified_config_types_1.UNIFIED_CONFIG_VERSION;
            try {
                saveUnifiedConfig(upgraded);
                if (process.env.CCS_DEBUG) {
                    console.error(`[i] Config upgraded to v${unified_config_types_1.UNIFIED_CONFIG_VERSION}`);
                }
                return upgraded;
            }
            catch (saveError) {
                console.error('[!] Config upgrade failed to save:', saveError.message);
                // Continue using the upgraded version in-memory even if save fails
            }
        }
        return parsed;
    }
    catch (err) {
        // U3: Provide better context for YAML syntax errors
        if (err instanceof yaml.YAMLException) {
            const mark = err.mark;
            console.error(`[X] YAML syntax error in ${yamlPath}:`);
            console.error(`    Line ${(mark?.line ?? 0) + 1}, Column ${(mark?.column ?? 0) + 1}: ${err.reason || 'Invalid syntax'}`);
            if (mark?.snippet) {
                console.error(`    ${mark.snippet}`);
            }
            console.error(`    Tip: Check for missing colons, incorrect indentation, or unquoted special characters.`);
        }
        else {
            const error = err instanceof Error ? err.message : 'Unknown error';
            console.error(`[X] Failed to load config: ${error}`);
        }
        throw err;
    }
}
exports.loadUnifiedConfig = loadUnifiedConfig;
/**
 * Load config, preferring YAML if available, falling back to creating empty config.
 * Merges with defaults to ensure all sections exist.
 */
function loadOrCreateUnifiedConfig() {
    const existing = loadUnifiedConfig();
    if (existing) {
        const merged = (0, defaults_merger_2.mergeWithDefaults)(existing);
        (0, normalizers_2.validateCompositeVariants)(merged);
        return merged;
    }
    return (0, unified_config_types_1.createEmptyUnifiedConfig)();
}
exports.loadOrCreateUnifiedConfig = loadOrCreateUnifiedConfig;
/**
 * Save unified config to YAML file.
 * Uses atomic write (temp file + rename) to prevent corruption.
 * Uses lockfile to prevent concurrent writes.
 */
function saveUnifiedConfig(config) {
    (0, io_locks_2.withConfigWriteLock)(() => {
        (0, io_locks_2.writeUnifiedConfigWithLockHeld)(config, yaml_serializer_2.generateYamlHeader, yaml_serializer_2.generateYamlWithComments);
    });
}
exports.saveUnifiedConfig = saveUnifiedConfig;
/**
 * Atomically mutate unified config with lock held across read-modify-write.
 * Prevents stale writes from overwriting concurrent updates.
 */
function mutateUnifiedConfig(mutator) {
    return (0, io_locks_2.withConfigWriteLock)(() => {
        const current = (0, io_locks_2.loadUnifiedConfigWithLockHeld)(defaults_merger_2.mergeWithDefaults, normalizers_2.validateCompositeVariants);
        const previousBrowser = current.browser
            ? (0, normalizers_2.canonicalizeBrowserConfig)(current.browser)
            : undefined;
        mutator(current);
        if (current.browser) {
            current.browser = (0, normalizers_2.canonicalizeBrowserConfig)(current.browser, previousBrowser);
        }
        (0, io_locks_2.writeUnifiedConfigWithLockHeld)(current, yaml_serializer_2.generateYamlHeader, yaml_serializer_2.generateYamlWithComments);
        return current;
    });
}
exports.mutateUnifiedConfig = mutateUnifiedConfig;
/**
 * Update unified config with partial data.
 * Loads existing config, merges changes, and saves.
 */
function updateUnifiedConfig(updates) {
    return mutateUnifiedConfig((config) => {
        Object.assign(config, updates);
    });
}
exports.updateUnifiedConfig = updateUnifiedConfig;
// ---------------------------------------------------------------------------
// Derived helpers
// ---------------------------------------------------------------------------
/**
 * Check if unified config mode is active.
 * Returns true if config.yaml exists OR CCS_UNIFIED_CONFIG=1.
 */
function isUnifiedMode() {
    return (0, io_locks_2.hasUnifiedConfig)() || (0, feature_flags_1.isUnifiedConfigEnabled)();
}
exports.isUnifiedMode = isUnifiedMode;
/**
 * Get default profile name from config.
 */
function getDefaultProfile() {
    const config = loadUnifiedConfig();
    return config?.default;
}
exports.getDefaultProfile = getDefaultProfile;
/**
 * Set default profile name in config.
 */
function setDefaultProfile(name) {
    updateUnifiedConfig({ default: name });
}
exports.setDefaultProfile = setDefaultProfile;
//# sourceMappingURL=unified-config-loader.js.map