"use strict";
/**
 * Profile and Delegation Health Checks
 */
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.runProfileChecks = exports.DelegationChecker = exports.InstancesChecker = exports.ProfilesChecker = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ui_1 = require("../../utils/ui");
const types_1 = require("./types");
const config_loader_facade_1 = require("../../config/config-loader-facade");
const instance_directory_1 = require("../instance-directory");
const ora = (0, types_1.createSpinner)();
/**
 * Check profile configurations in config.yaml (preferred) or config.json (legacy)
 */
class ProfilesChecker {
    constructor() {
        this.name = 'Profiles';
        this.ccsDir = (0, config_loader_facade_1.getCcsDir)();
    }
    run(results) {
        const spinner = ora('Checking profiles').start();
        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) {
            try {
                const yaml = require('js-yaml');
                const content = fs.readFileSync(configYamlPath, 'utf8');
                const config = yaml.load(content);
                this.validateProfiles(config, 'config.yaml', spinner, results);
                return;
            }
            catch (e) {
                spinner.fail();
                console.log(`  ${(0, ui_1.fail)('Profiles'.padEnd(22))}  Invalid config.yaml: ${e.message}`);
                results.addCheck('Profiles', 'error', `Invalid config.yaml: ${e.message}`, undefined, {
                    status: 'ERROR',
                    info: e.message,
                });
                return;
            }
        }
        // Fallback to config.json (legacy format)
        if (jsonExists) {
            try {
                const config = JSON.parse(fs.readFileSync(configJsonPath, 'utf8'));
                this.validateProfiles(config, 'config.json', spinner, results);
                return;
            }
            catch (e) {
                spinner.fail();
                console.log(`  ${(0, ui_1.fail)('Profiles'.padEnd(22))}  Invalid config.json: ${e.message}`);
                results.addCheck('Profiles', 'error', `Invalid config.json: ${e.message}`, undefined, {
                    status: 'ERROR',
                    info: e.message,
                });
                return;
            }
        }
        // Neither exists
        spinner.info();
        console.log(`  ${(0, ui_1.info)('Profiles'.padEnd(22))}  No config file found (config.yaml or config.json)`);
    }
    /**
     * Validate profiles object from parsed config
     */
    validateProfiles(config, configFileName, spinner, results) {
        if (!config.profiles || typeof config.profiles !== 'object') {
            spinner.fail();
            console.log(`  ${(0, ui_1.fail)('Profiles'.padEnd(22))}  Missing profiles object in ${configFileName}`);
            results.addCheck('Profiles', 'error', `${configFileName} missing profiles object`, 'Run: npm install -g @kaitranntt/ccs --force', { status: 'ERROR', info: 'Missing profiles object' });
            return;
        }
        const profileCount = Object.keys(config.profiles).length;
        const profileNames = Object.keys(config.profiles).join(', ');
        spinner.succeed();
        console.log(`  ${(0, ui_1.ok)('Profiles'.padEnd(22))}  ${profileCount} configured (${profileNames})`);
        results.addCheck('Profiles', 'success', `${profileCount} profiles configured`, undefined, {
            status: 'OK',
            info: `${profileCount} configured (${profileNames.length > 30 ? profileNames.substring(0, 27) + '...' : profileNames})`,
        });
    }
}
exports.ProfilesChecker = ProfilesChecker;
/**
 * Check instance directories (account-based profiles)
 */
class InstancesChecker {
    constructor() {
        this.name = 'Instances';
        this.ccsDir = (0, config_loader_facade_1.getCcsDir)();
    }
    run(results) {
        const spinner = ora('Checking instances').start();
        const instancesDir = path.join(this.ccsDir, 'instances');
        if (!fs.existsSync(instancesDir)) {
            spinner.info();
            console.log(`  ${(0, ui_1.info)('Instances'.padEnd(22))}  No account profiles`);
            results.addCheck('Instances', 'success', 'No account profiles configured');
            return;
        }
        const instances = (0, instance_directory_1.listAccountInstanceNames)(instancesDir);
        if (instances.length === 0) {
            spinner.info();
            console.log(`  ${(0, ui_1.info)('Instances'.padEnd(22))}  No account profiles`);
            results.addCheck('Instances', 'success', 'No account profiles');
            return;
        }
        spinner.succeed();
        console.log(`  ${(0, ui_1.ok)('Instances'.padEnd(22))}  ${instances.length} account profiles`);
        results.addCheck('Instances', 'success', `${instances.length} account profiles`);
    }
}
exports.InstancesChecker = InstancesChecker;
/**
 * Check delegation system (commands and ready profiles)
 */
class DelegationChecker {
    constructor() {
        this.name = 'Delegation';
        this.ccsDir = (0, config_loader_facade_1.getCcsDir)();
    }
    run(results) {
        const spinner = ora('Checking delegation').start();
        // Check if delegation commands exist in ~/.ccs/.claude/commands/
        const ccsClaudeCommandsDir = path.join(this.ccsDir, '.claude', 'commands');
        const hasCcsCommand = fs.existsSync(path.join(ccsClaudeCommandsDir, 'ccs.md'));
        const hasContinueCommand = fs.existsSync(path.join(ccsClaudeCommandsDir, 'ccs', 'continue.md'));
        if (!hasCcsCommand || !hasContinueCommand) {
            spinner.warn();
            console.log(`  ${(0, ui_1.warn)('Delegation'.padEnd(22))}  Not installed`);
            results.addCheck('Delegation', 'warning', 'Delegation commands not found', 'Install with: npm install -g @kaitranntt/ccs --force', { status: 'WARN', info: 'Not installed' });
            return;
        }
        // Check profile validity using DelegationValidator (dynamic discovery)
        const { DelegationValidator } = require('../../utils/delegation-validator');
        const readyProfiles = DelegationValidator.getReadyProfiles();
        if (readyProfiles.length === 0) {
            spinner.warn();
            console.log(`  ${(0, ui_1.warn)('Delegation'.padEnd(22))}  No profiles ready`);
            results.addCheck('Delegation', 'warning', 'Delegation installed but no profiles configured', 'Configure profiles with valid API keys (not placeholders)', { status: 'WARN', info: 'No profiles ready' });
            return;
        }
        spinner.succeed();
        console.log(`  ${(0, ui_1.ok)('Delegation'.padEnd(22))}  ${readyProfiles.length} profiles ready (${readyProfiles.join(', ')})`);
        results.addCheck('Delegation', 'success', `${readyProfiles.length} profile(s) ready: ${readyProfiles.join(', ')}`, undefined, { status: 'OK', info: `${readyProfiles.length} profiles ready` });
    }
}
exports.DelegationChecker = DelegationChecker;
/**
 * Run all profile checks
 */
function runProfileChecks(results) {
    const profilesChecker = new ProfilesChecker();
    const instancesChecker = new InstancesChecker();
    const delegationChecker = new DelegationChecker();
    profilesChecker.run(results);
    instancesChecker.run(results);
    delegationChecker.run(results);
}
exports.runProfileChecks = runProfileChecks;
//# sourceMappingURL=profile-check.js.map