"use strict";
/**
 * CCS Health Check and Diagnostics - Main Orchestrator
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const ui_1 = require("../utils/ui");
const package_json_1 = __importDefault(require("../../package.json"));
const checks_1 = require("./checks");
const repair_1 = require("./repair");
const docker_key_rotation_1 = require("../docker/docker-key-rotation");
/**
 * Doctor Class - Orchestrates health checks
 */
class Doctor {
    constructor() {
        this.results = new checks_1.HealthCheck();
        this.ccsVersion = package_json_1.default.version;
    }
    /**
     * Run all health checks
     */
    async runAllChecks() {
        await (0, ui_1.initUI)();
        // Hero header box
        console.log((0, ui_1.box)(`CCS Health Check v${this.ccsVersion}`, { borderStyle: 'round', padding: 0 }));
        console.log('');
        // Store CCS version in details
        this.results.details['CCS Version'] = { status: 'OK', info: `v${this.ccsVersion}` };
        // Group 1: System
        console.log((0, ui_1.header)('SYSTEM'));
        await (0, checks_1.runSystemChecks)(this.results);
        console.log('');
        // Group 2: Environment (OAuth readiness diagnostics)
        console.log((0, ui_1.header)('ENVIRONMENT'));
        (0, checks_1.runEnvironmentCheck)(this.results);
        console.log('');
        // Group 3: Configuration
        console.log((0, ui_1.header)('CONFIGURATION'));
        (0, checks_1.runConfigChecks)(this.results);
        this.runDockerKeyRotationCheck();
        console.log('');
        // Group 4: Profiles & Delegation
        console.log((0, ui_1.header)('PROFILES & DELEGATION'));
        (0, checks_1.runProfileChecks)(this.results);
        console.log('');
        // Group 5: System Health
        console.log((0, ui_1.header)('SYSTEM HEALTH'));
        (0, checks_1.runSymlinkChecks)(this.results);
        console.log('');
        // Group 6: CLIProxy Plus (OAuth profiles)
        console.log((0, ui_1.header)('CLIPROXY PLUS (OAUTH PROFILES)'));
        await (0, checks_1.runCLIProxyChecks)(this.results);
        console.log('');
        // Group 7: OAuth Readiness (port availability)
        console.log((0, ui_1.header)('OAUTH READINESS'));
        await (0, checks_1.runOAuthChecks)(this.results);
        console.log('');
        // Group 8: Image Analysis Config
        console.log((0, ui_1.header)('IMAGE ANALYSIS'));
        await (0, checks_1.runImageAnalysisCheck)(this.results);
        console.log('');
        this.showReport();
        return this.results;
    }
    /**
     * Show health check report
     */
    showReport() {
        console.log('');
        console.log((0, ui_1.header)('HEALTH CHECK SUMMARY'));
        console.log('');
        // Build summary table rows
        const rows = Object.entries(this.results.details).map(([component, detail]) => {
            const statusIndicator = detail.status === 'OK'
                ? (0, ui_1.color)('[OK]', 'success')
                : detail.status === 'ERROR'
                    ? (0, ui_1.color)('[X]', 'error')
                    : (0, ui_1.color)('[!]', 'warning');
            return [component, statusIndicator, detail.info || ''];
        });
        console.log((0, ui_1.table)(rows, {
            head: ['Component', 'Status', 'Details'],
            colWidths: [20, 12, 35],
        }));
        console.log('');
        // Show errors if present
        if (this.results.hasErrors()) {
            console.log((0, ui_1.header)('ERRORS'));
            this.results.errors.forEach((err) => {
                console.log(`  ${(0, ui_1.fail)(err.name)}: ${err.message}`);
                if (err.fix) {
                    console.log(`    Fix: ${(0, ui_1.color)(err.fix, 'command')}`);
                }
            });
            console.log('');
        }
        // Show warnings if present
        if (this.results.hasWarnings()) {
            console.log((0, ui_1.header)('WARNINGS'));
            this.results.warnings.forEach((w) => {
                console.log(`  ${(0, ui_1.warn)(w.name)}: ${w.message}`);
                if (w.fix) {
                    console.log(`    Fix: ${(0, ui_1.color)(w.fix, 'command')}`);
                }
            });
            console.log('');
        }
        // Final status
        if (this.results.isHealthy() && !this.results.hasWarnings()) {
            console.log((0, ui_1.ok)('All checks passed! Installation is healthy.'));
            console.log('');
            console.log((0, ui_1.info)(`Tip: Use ${(0, ui_1.color)('ccs config', 'command')} for web-based configuration`));
        }
        else if (this.results.hasErrors()) {
            console.log((0, ui_1.fail)('Installation has errors. Run suggested fixes above.'));
        }
        else {
            console.log((0, ui_1.ok)(`Installation healthy (${this.results.warnings.length} warning${this.results.warnings.length !== 1 ? 's' : ''})`));
            console.log('');
            console.log((0, ui_1.info)(`Tip: Use ${(0, ui_1.color)('ccs config', 'command')} for web-based configuration`));
        }
        console.log('');
    }
    runDockerKeyRotationCheck() {
        const status = (0, docker_key_rotation_1.getDockerKeyRotationStatus)();
        if (status.legacyGraceActive && status.legacyGrace) {
            this.results.addCheck('Docker Key Rotation', 'warning', `Legacy API key remains valid until ${status.legacyGrace.expiresAt}`, 'Run `ccs docker show-key --full`, update clients, then run `ccs docker finalize-key-rotation`.', {
                status: 'WARN',
                info: `legacy key grace active until ${status.legacyGrace.expiresAt}`,
            });
            return;
        }
        if (status.stateCorrupted) {
            this.results.addCheck('Docker Key Rotation', 'warning', 'Docker bootstrap state marker is unreadable', 'Run `ccs docker up` to recreate the marker.', {
                status: 'WARN',
                info: 'state marker unreadable',
            });
            return;
        }
        this.results.addCheck('Docker Key Rotation', 'success', 'No active legacy API key grace', undefined, {
            status: 'OK',
            info: 'no active grace',
        });
    }
    /**
     * Generate JSON report
     */
    generateJsonReport() {
        return JSON.stringify({
            timestamp: new Date().toISOString(),
            platform: process.platform,
            nodeVersion: process.version,
            ccsVersion: package_json_1.default.version,
            checks: this.results.checks,
            errors: this.results.errors,
            warnings: this.results.warnings,
            healthy: this.results.isHealthy(),
        }, null, 2);
    }
    /**
     * Fix detected issues (--fix flag)
     */
    async fixIssues() {
        await (0, repair_1.runAutoRepair)();
    }
    /**
     * Check if the health check results are healthy
     */
    isHealthy() {
        return this.results.isHealthy();
    }
}
exports.default = Doctor;
//# sourceMappingURL=doctor.js.map