"use strict";
/**
 * Health Check Service
 *
 * Orchestrates comprehensive health checks for CCS dashboard matching `ccs doctor` output.
 * Groups: System, Environment, Configuration, Profiles & Delegation, System Health, CLIProxy, OAuth Readiness
 */
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;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fixHealthIssue = exports.runHealthChecks = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const config_manager_1 = require("../utils/config-manager");
const package_json_1 = __importDefault(require("../../package.json"));
// Import all check functions from modular components
const health_1 = require("./health");
const config_loader_facade_1 = require("../config/config-loader-facade");
/**
 * Run all health checks and return report
 */
async function runHealthChecks() {
    const homedir = os.homedir();
    const ccsDir = (0, config_loader_facade_1.getCcsDir)();
    const claudeDir = path.join(homedir, '.claude');
    const version = package_json_1.default.version;
    const groups = [];
    // Group 1: System
    const systemChecks = [];
    systemChecks.push(await (0, health_1.checkClaudeCli)());
    systemChecks.push((0, health_1.checkCcsDirectory)(ccsDir));
    groups.push({ id: 'system', name: 'System', icon: 'Monitor', checks: systemChecks });
    // Group 2: Environment
    const envChecks = [];
    envChecks.push((0, health_1.checkEnvironment)());
    groups.push({ id: 'environment', name: 'Environment', icon: 'Laptop', checks: envChecks });
    // Group 3: Configuration
    const configChecks = [];
    configChecks.push((0, health_1.checkConfigFile)());
    configChecks.push(...(0, health_1.checkSettingsFiles)(ccsDir));
    configChecks.push((0, health_1.checkClaudeSettings)(claudeDir));
    groups.push({
        id: 'configuration',
        name: 'Configuration',
        icon: 'Settings',
        checks: configChecks,
    });
    // Group 4: Profiles & Delegation
    const profileChecks = [];
    profileChecks.push((0, health_1.checkProfiles)(ccsDir));
    profileChecks.push((0, health_1.checkInstances)(ccsDir));
    profileChecks.push((0, health_1.checkDelegation)(ccsDir));
    groups.push({
        id: 'profiles',
        name: 'Profiles & Delegation',
        icon: 'Users',
        checks: profileChecks,
    });
    // Group 5: System Health
    const healthChecks = [];
    healthChecks.push((0, health_1.checkPermissions)(ccsDir));
    healthChecks.push((0, health_1.checkCcsSymlinks)());
    healthChecks.push((0, health_1.checkSettingsSymlinks)(ccsDir, claudeDir));
    groups.push({ id: 'system-health', name: 'System Health', icon: 'Shield', checks: healthChecks });
    // Group 6: CLIProxy
    const cliproxyChecks = [];
    cliproxyChecks.push((0, health_1.checkCliproxyBinary)());
    cliproxyChecks.push((0, health_1.checkCliproxyConfig)());
    cliproxyChecks.push(...(0, health_1.checkOAuthProviders)());
    cliproxyChecks.push(await (0, health_1.checkCliproxyPort)());
    groups.push({ id: 'cliproxy', name: 'CLIProxy (OAuth)', icon: 'Zap', checks: cliproxyChecks });
    // Group 7: OAuth Readiness
    const oauthReadinessChecks = [];
    oauthReadinessChecks.push(...(await (0, health_1.checkOAuthPortsForDashboard)()));
    groups.push({
        id: 'oauth-readiness',
        name: 'OAuth Readiness',
        icon: 'Key',
        checks: oauthReadinessChecks,
    });
    // Group 8: WebSearch CLI Providers
    const websearchChecks = [];
    websearchChecks.push(...(0, health_1.checkWebSearchClis)());
    groups.push({ id: 'websearch', name: 'WebSearch', icon: 'Search', checks: websearchChecks });
    // Flatten all checks for backward compatibility
    const allChecks = groups.flatMap((g) => g.checks);
    // Calculate summary
    const summary = {
        total: allChecks.length,
        passed: allChecks.filter((c) => c.status === 'ok').length,
        warnings: allChecks.filter((c) => c.status === 'warning').length,
        errors: allChecks.filter((c) => c.status === 'error').length,
        info: allChecks.filter((c) => c.status === 'info').length,
    };
    return { timestamp: Date.now(), version, groups, checks: allChecks, summary };
}
exports.runHealthChecks = runHealthChecks;
/**
 * Fix a health issue by its check ID
 */
function fixHealthIssue(checkId) {
    const ccsDir = (0, config_loader_facade_1.getCcsDir)();
    switch (checkId) {
        case 'ccs-dir':
            fs.mkdirSync(ccsDir, { recursive: true });
            return { success: true, message: `Created ${ccsDir} directory` };
        case 'config-file': {
            // Use appropriate config based on unified mode
            const { isUnifiedMode } = require('../config/config-loader-facade');
            if (isUnifiedMode()) {
                const { mutateConfig } = require('../config/config-loader-facade');
                mutateConfig(() => { });
                return { success: true, message: 'Created/updated config.yaml' };
            }
            const configPath = (0, config_manager_1.getConfigPath)();
            fs.mkdirSync(path.dirname(configPath), { recursive: true });
            fs.writeFileSync(configPath, JSON.stringify({ profiles: {} }, null, 2) + '\n');
            return { success: true, message: 'Created config.json' };
        }
        case 'profiles-file': {
            // Use appropriate storage based on unified mode
            const { isUnifiedMode: isUnified } = require('../config/config-loader-facade');
            if (isUnified()) {
                // In unified mode, accounts are stored in config.yaml
                return { success: true, message: 'Accounts stored in config.yaml (unified mode)' };
            }
            const profilesPath = path.join(ccsDir, 'profiles.json');
            fs.mkdirSync(ccsDir, { recursive: true });
            fs.writeFileSync(profilesPath, JSON.stringify({ profiles: {} }, null, 2) + '\n');
            return { success: true, message: 'Created profiles.json' };
        }
        default:
            return { success: false, message: 'Cannot auto-fix this issue' };
    }
}
exports.fixHealthIssue = fixHealthIssue;
//# sourceMappingURL=health-service.js.map