import fs from 'fs';
import path from 'path';
import { execSync } from 'child_process';
import { getAssetsDir } from '../utils/config.js';
export async function doctorCommand() {
    const cwd = process.cwd();
    const checks = [];
    // Node.js version
    const nodeVersion = process.version;
    const major = parseInt(nodeVersion.slice(1));
    checks.push({
        name: 'Node.js',
        status: major >= 20 ? 'ok' : 'fail',
        message: `${nodeVersion} ${major >= 20 ? '(meets >=20)' : '(requires >=20)'}`,
    });
    // Claude Code CLI
    try {
        const claudeVersion = execSync('claude --version', { encoding: 'utf-8' }).trim();
        checks.push({ name: 'Claude Code CLI', status: 'ok', message: claudeVersion });
    }
    catch {
        checks.push({ name: 'Claude Code CLI', status: 'fail', message: 'Not found — install from https://claude.ai/code' });
    }
    // MCP integrations check
    const { getConfiguredMcpIds } = await import('../mcp/validate.js');
    const { loadMcpDefinition } = await import('../mcp/catalog.js');
    const { detectMcp } = await import('../mcp/detect.js');
    const configured = getConfiguredMcpIds(process.cwd());
    const mcpsDir = path.resolve('mcps');
    if (configured.length > 0) {
        for (const id of configured) {
            const def = loadMcpDefinition(mcpsDir, id);
            if (def) {
                const result = detectMcp(def);
                checks.push({
                    name: `MCP: ${def.name}`,
                    status: result.status !== 'unavailable' ? 'ok' : 'warn',
                    message: result.detail,
                });
            }
        }
    }
    else {
        checks.push({
            name: 'MCP integrations',
            status: 'warn',
            message: 'No MCPs configured. Run: expxagents mcp setup <id>',
        });
    }
    // Project structure
    const requiredDirs = ['squads', '_expxagents/_memory'];
    for (const dir of requiredDirs) {
        const exists = fs.existsSync(path.join(cwd, dir));
        checks.push({
            name: `Directory: ${dir}`,
            status: exists ? 'ok' : 'warn',
            message: exists ? 'exists' : 'missing — run `expxagents init`',
        });
    }
    // .env file
    const envExists = fs.existsSync(path.join(cwd, '.env'));
    checks.push({
        name: '.env file',
        status: envExists ? 'ok' : 'warn',
        message: envExists ? 'exists' : 'missing — run `expxagents init`',
    });
    // Company profile
    const companyPath = path.join(cwd, '_expxagents', '_memory', 'company.md');
    if (fs.existsSync(companyPath)) {
        const content = fs.readFileSync(companyPath, 'utf-8');
        const configured = !content.includes('NOT CONFIGURED');
        checks.push({
            name: 'Company profile',
            status: configured ? 'ok' : 'warn',
            message: configured ? 'configured' : 'not configured — run `expxagents onboarding`',
        });
    }
    // Squads count
    const squadsDir = path.join(cwd, 'squads');
    if (fs.existsSync(squadsDir)) {
        const squads = fs.readdirSync(squadsDir, { withFileTypes: true })
            .filter(d => d.isDirectory() && !d.name.startsWith('.') && d.name !== '_memory')
            .length;
        checks.push({ name: 'Squads', status: 'ok', message: `${squads} found` });
    }
    // Package assets (check in package directory, not user project)
    const assetsDir = getAssetsDir();
    const coreFiles = [
        { label: 'solution-architect.agent.md', path: path.join(assetsDir, 'core', 'solution-architect.agent.md') },
        { label: 'runner.pipeline.md', path: path.join(assetsDir, 'core', 'runner.pipeline.md') },
        { label: 'agents catalog', path: path.join(assetsDir, 'agents', '_catalog.yaml') },
        { label: 'best-practices', path: path.join(assetsDir, 'core', 'best-practices', '_catalog.yaml') },
    ];
    for (const file of coreFiles) {
        const exists = fs.existsSync(file.path);
        checks.push({
            name: `Package: ${file.label}`,
            status: exists ? 'ok' : 'warn',
            message: exists ? 'present' : 'missing — reinstall expxagents',
        });
    }
    // Display results
    console.log('\n  ExpxAgents System Diagnostics\n');
    const symbols = { ok: '  OK', warn: 'WARN', fail: 'FAIL' };
    let hasFailures = false;
    for (const check of checks) {
        if (check.status === 'fail')
            hasFailures = true;
        console.log(`  [${symbols[check.status]}] ${check.name}: ${check.message}`);
    }
    console.log(hasFailures ? '\n  Some checks failed. See above.\n' : '\n  All checks passed!\n');
}
