"use strict";
/**
 * System Health Checks - Claude CLI and CCS Directory
 */
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.runSystemChecks = exports.CcsDirectoryChecker = exports.ClaudeCliChecker = void 0;
const fs = __importStar(require("fs"));
const child_process_1 = require("child_process");
const claude_detector_1 = require("../../utils/claude-detector");
const shell_executor_1 = require("../../utils/shell-executor");
const ui_1 = require("../../utils/ui");
const types_1 = require("./types");
const config_loader_facade_1 = require("../../config/config-loader-facade");
const ora = (0, types_1.createSpinner)();
/**
 * Check Claude CLI availability and version
 */
class ClaudeCliChecker {
    constructor() {
        this.name = 'Claude CLI';
    }
    async run(results) {
        const spinner = ora('Checking Claude CLI').start();
        const cliInfo = (0, claude_detector_1.getClaudeCliInfo)();
        if (!cliInfo) {
            spinner.fail();
            console.log(`  ${(0, ui_1.fail)('Claude CLI'.padEnd(22))}  Not found in PATH`);
            results.addCheck('Claude CLI', 'error', 'Claude CLI not found in PATH', 'Install from: https://docs.claude.com/en/docs/claude-code/installation', { status: 'ERROR', info: 'Not installed' });
            return;
        }
        const { path: claudeCli, needsShell } = cliInfo;
        // Try to execute claude --version
        try {
            const result = await new Promise((resolve, reject) => {
                // When shell is needed (Windows .cmd/.bat files), concatenate into string
                // to avoid DEP0190 warning about passing args with shell: true
                const child = needsShell
                    ? (0, child_process_1.spawn)([claudeCli, '--version'].map(shell_executor_1.escapeShellArg).join(' '), {
                        stdio: 'pipe',
                        timeout: 5000,
                        shell: (0, shell_executor_1.getWindowsEscapedCommandShell)(),
                        env: (0, shell_executor_1.stripClaudeCodeEnv)(process.env),
                    })
                    : (0, child_process_1.spawn)(claudeCli, ['--version'], {
                        stdio: 'pipe',
                        timeout: 5000,
                        env: (0, shell_executor_1.stripClaudeCodeEnv)(process.env),
                    });
                let output = '';
                child.stdout?.on('data', (data) => (output += data));
                child.stderr?.on('data', (data) => (output += data));
                child.on('close', (code) => {
                    if (code === 0)
                        resolve(output);
                    else
                        reject(new Error('Exit code ' + code));
                });
                child.on('error', reject);
            });
            // Extract version from output
            const versionMatch = result.match(/(\d+\.\d+\.\d+)/);
            const version = versionMatch ? versionMatch[1] : 'unknown';
            spinner.succeed();
            console.log(`  ${(0, ui_1.ok)('Claude CLI'.padEnd(22))}  v${version} (${claudeCli})`);
            results.addCheck('Claude CLI', 'success', `Found: ${claudeCli}`, undefined, {
                status: 'OK',
                info: `v${version} (${claudeCli})`,
            });
        }
        catch (_err) {
            spinner.fail();
            console.log(`  ${(0, ui_1.fail)('Claude CLI'.padEnd(22))}  Not found or not working`);
            results.addCheck('Claude CLI', 'error', 'Claude CLI not found or not working', 'Install from: https://docs.claude.com/en/docs/claude-code/installation', { status: 'ERROR', info: 'Not installed' });
        }
    }
}
exports.ClaudeCliChecker = ClaudeCliChecker;
/**
 * Check ~/.ccs/ directory exists
 */
class CcsDirectoryChecker {
    constructor() {
        this.name = 'CCS Directory';
        this.ccsDir = (0, config_loader_facade_1.getCcsDir)();
    }
    run(results) {
        const spinner = ora('Checking ~/.ccs/ directory').start();
        if (fs.existsSync(this.ccsDir)) {
            spinner.succeed();
            console.log(`  ${(0, ui_1.ok)('CCS Directory'.padEnd(22))}  ~/.ccs/`);
            results.addCheck('CCS Directory', 'success', undefined, undefined, {
                status: 'OK',
                info: '~/.ccs/',
            });
        }
        else {
            spinner.fail();
            console.log(`  ${(0, ui_1.fail)('CCS Directory'.padEnd(22))}  Not found`);
            results.addCheck('CCS Directory', 'error', '~/.ccs/ directory not found', 'Run: npm install -g @kaitranntt/ccs --force', { status: 'ERROR', info: 'Not found' });
        }
    }
}
exports.CcsDirectoryChecker = CcsDirectoryChecker;
/**
 * Run all system checks
 */
async function runSystemChecks(results) {
    const cliChecker = new ClaudeCliChecker();
    const dirChecker = new CcsDirectoryChecker();
    await cliChecker.run(results);
    dirChecker.run(results);
}
exports.runSystemChecks = runSystemChecks;
//# sourceMappingURL=system-check.js.map