"use strict";
/**
 * Configuration Health Checks - Config files and Claude settings
 */
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.runConfigChecks = exports.ClaudeSettingsChecker = exports.ConfigFilesChecker = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ui_1 = require("../../utils/ui");
const types_1 = require("./types");
const claude_config_path_1 = require("../../utils/claude-config-path");
const config_loader_facade_1 = require("../../config/config-loader-facade");
const stale_codex_translator_settings_1 = require("../../shared/stale-codex-translator-settings");
const ora = (0, types_1.createSpinner)();
/**
 * Check CCS config files exist and are valid
 * - Prefers config.yaml (v2) over config.json (legacy)
 * - Settings files are optional (only checked if profile exists)
 */
class ConfigFilesChecker {
    constructor() {
        this.name = 'Config Files';
        this.ccsDir = (0, config_loader_facade_1.getCcsDir)();
    }
    run(results) {
        const { DelegationValidator } = require('../../utils/delegation-validator');
        // Check main config file (yaml preferred, json fallback)
        this.checkMainConfig(results);
        // Check optional settings files (only if profile exists in config)
        this.checkOptionalSettingsFiles(results, DelegationValidator);
    }
    /**
     * Check main configuration file (config.yaml preferred, config.json fallback)
     */
    checkMainConfig(results) {
        const configYamlPath = path.join(this.ccsDir, 'config.yaml');
        const configJsonPath = path.join(this.ccsDir, 'config.json');
        const yamlExists = fs.existsSync(configYamlPath);
        const jsonExists = fs.existsSync(configJsonPath);
        // Check config.yaml first (preferred format)
        if (yamlExists) {
            const spinner = ora('Checking config.yaml').start();
            try {
                const yaml = require('js-yaml');
                const content = fs.readFileSync(configYamlPath, 'utf8');
                yaml.load(content);
                spinner.succeed();
                console.log(`  ${(0, ui_1.ok)('config.yaml'.padEnd(22))}  Valid`);
                results.addCheck('config.yaml', 'success', undefined, undefined, {
                    status: 'OK',
                    info: 'Valid',
                });
                // Inform if legacy config.json also exists (purely informational, not a check)
                if (jsonExists) {
                    console.log(`  ${(0, ui_1.info)('config.json'.padEnd(22))}  Legacy (ignored)`);
                }
                return;
            }
            catch (e) {
                spinner.fail();
                console.log(`  ${(0, ui_1.fail)('config.yaml'.padEnd(22))}  Invalid YAML`);
                results.addCheck('config.yaml', 'error', `Invalid YAML: ${e.message}`, `Backup and recreate: mv ${configYamlPath} ${configYamlPath}.backup && npm install -g @kaitranntt/ccs --force`, { status: 'ERROR', info: 'Invalid YAML' });
                return;
            }
        }
        // Fallback to config.json (legacy format)
        if (jsonExists) {
            const spinner = ora('Checking config.json').start();
            try {
                const content = fs.readFileSync(configJsonPath, 'utf8');
                JSON.parse(content);
                spinner.succeed();
                console.log(`  ${(0, ui_1.ok)('config.json'.padEnd(22))}  Valid (legacy)`);
                results.addCheck('config.json', 'success', undefined, undefined, {
                    status: 'OK',
                    info: 'Valid (legacy)',
                });
            }
            catch (e) {
                spinner.fail();
                console.log(`  ${(0, ui_1.fail)('config.json'.padEnd(22))}  Invalid JSON`);
                results.addCheck('config.json', 'error', `Invalid JSON: ${e.message}`, `Backup and recreate: mv ${configJsonPath} ${configJsonPath}.backup && npm install -g @kaitranntt/ccs --force`, { status: 'ERROR', info: 'Invalid JSON' });
            }
            return;
        }
        // Neither exists - error
        const spinner = ora('Checking config').start();
        spinner.fail();
        console.log(`  ${(0, ui_1.fail)('config.yaml'.padEnd(22))}  Not found`);
        results.addCheck('config.yaml', 'error', 'No configuration file found (config.yaml or config.json)', 'Run: npm install -g @kaitranntt/ccs --force', { status: 'ERROR', info: 'Not found' });
    }
    /**
     * Check optional settings files (only if corresponding profile is configured)
     * These files are NOT required - they're only created when user configures a profile
     */
    checkOptionalSettingsFiles(results, DelegationValidator) {
        // Settings files to check (only if profile exists)
        const settingsFiles = [
            { name: 'glm.settings.json', profile: 'glm', displayName: 'GLM Settings' },
            { name: 'kimi.settings.json', profile: 'kimi', displayName: 'Kimi Settings' },
        ];
        for (const file of settingsFiles) {
            const filePath = path.join(this.ccsDir, file.name);
            const exists = fs.existsSync(filePath);
            if (!exists) {
                // Not an error - these are optional files
                // Only show info if user might expect them
                continue;
            }
            // File exists - validate it
            const spinner = ora(`Checking ${file.name}`).start();
            try {
                const content = fs.readFileSync(filePath, 'utf8');
                JSON.parse(content);
                // Check if API key is properly configured
                const validation = DelegationValidator.validate(file.profile);
                let fileInfo = 'Valid JSON';
                let status = 'OK';
                if (validation.valid) {
                    fileInfo = 'Key configured';
                    status = 'OK';
                }
                else if (validation.error && validation.error.includes('placeholder')) {
                    fileInfo = 'Placeholder key';
                    status = 'WARN';
                }
                if (status === 'WARN') {
                    spinner.warn();
                    console.log(`  ${(0, ui_1.warn)(file.name.padEnd(22))}  ${fileInfo}`);
                }
                else {
                    spinner.succeed();
                    console.log(`  ${(0, ui_1.ok)(file.name.padEnd(22))}  ${fileInfo}`);
                }
                results.addCheck(file.name, status === 'OK' ? 'success' : 'warning', undefined, undefined, {
                    status: status,
                    info: fileInfo,
                });
            }
            catch (e) {
                spinner.fail();
                console.log(`  ${(0, ui_1.fail)(file.name.padEnd(22))}  Invalid JSON`);
                results.addCheck(file.name, 'error', `Invalid JSON: ${e.message}`, `Backup and recreate: mv ${filePath} ${filePath}.backup`, { status: 'ERROR', info: 'Invalid JSON' });
            }
        }
    }
}
exports.ConfigFilesChecker = ConfigFilesChecker;
/**
 * Check Claude settings.json
 */
class ClaudeSettingsChecker {
    constructor() {
        this.name = 'Claude Settings';
        this.claudeDir = (0, claude_config_path_1.getClaudeConfigDir)();
    }
    run(results) {
        const spinner = ora('Checking ~/.claude/settings.json').start();
        const settingsPath = path.join(this.claudeDir, 'settings.json');
        const settingsName = '~/.claude/settings.json';
        if (!fs.existsSync(settingsPath)) {
            spinner.warn();
            console.log(`  ${(0, ui_1.warn)(settingsName.padEnd(22))}  Not found`);
            results.addCheck('Claude Settings', 'warning', '~/.claude/settings.json not found', 'Run: claude /login');
            return;
        }
        // Validate JSON
        try {
            const content = fs.readFileSync(settingsPath, 'utf8');
            const settings = JSON.parse(content);
            const codexTranslatorUrlPaths = (0, stale_codex_translator_settings_1.findCodexTranslatorUrlPaths)(settings);
            if (codexTranslatorUrlPaths.length > 0) {
                const formattedPaths = (0, stale_codex_translator_settings_1.formatSettingsPathList)(codexTranslatorUrlPaths);
                spinner.warn();
                console.log(`  ${(0, ui_1.warn)(settingsName.padEnd(22))}  Codex CLIProxy bridge persisted at ${formattedPaths}`);
                results.addCheck('Claude Settings', 'warning', `Claude settings route Claude Code through the Codex CLIProxy translator at ${formattedPaths} (${stale_codex_translator_settings_1.CODEX_TRANSLATOR_URL_MARKER})`, 'Run: ccs persist default --yes; use ccsxp or ccs codex --target codex for Codex');
                return;
            }
            spinner.succeed();
            console.log(`  ${(0, ui_1.ok)(settingsName.padEnd(22))}  Valid`);
            results.addCheck('Claude Settings', 'success');
        }
        catch (e) {
            spinner.warn();
            console.log(`  ${(0, ui_1.warn)(settingsName.padEnd(22))}  Invalid JSON`);
            results.addCheck('Claude Settings', 'warning', `Invalid JSON: ${e.message}`, 'Run: claude /login');
        }
    }
}
exports.ClaudeSettingsChecker = ClaudeSettingsChecker;
/**
 * Run all config checks
 */
function runConfigChecks(results) {
    const configChecker = new ConfigFilesChecker();
    const claudeChecker = new ClaudeSettingsChecker();
    configChecker.run(results);
    claudeChecker.run(results);
}
exports.runConfigChecks = runConfigChecks;
//# sourceMappingURL=config-check.js.map