// audit-claude-config.ts — Tool handler for audit_claude_config (SPEC-092)
// SPEC-724: Added gate='core-rules' to assert per-host rule files exist.
import { compactResult } from './output-formatter.js';
import { auditClaudeMd, auditRules, auditMemory, auditSettings, calculateScore, pickQuickWins, } from '../engine/claude-config-auditor/index.js';
import { detectHost } from '../engine/host-detection/detect-host.js';
import { access } from 'node:fs/promises';
import { join } from 'node:path';
import { homedir } from 'node:os';
// ---------------------------------------------------------------------------
// SPEC-724: Core-rules gate — assert 3 rule files per detected host
// ---------------------------------------------------------------------------
const CORE_RULES_FILES = [
    'asking-questions.md',
    'parallelism.md',
    'token-optimization.md',
];
async function fileExists(filePath) {
    try {
        await access(filePath);
        return true;
    }
    catch {
        return false;
    }
}
async function checkCoreRulesGate(projectPath) {
    const host = detectHost();
    const blockers = [];
    if (host === 'claude-code' || host === 'universal') {
        const rulesDir = join(homedir(), '.claude', 'rules');
        for (const ruleFile of CORE_RULES_FILES) {
            const filePath = join(rulesDir, ruleFile);
            if (!(await fileExists(filePath))) {
                blockers.push({ code: 'MISSING_CORE_RULE_FILE', host: 'claude-code', file: ruleFile });
            }
        }
    }
    if (host === 'codex') {
        const agentsMdPath = join(projectPath, 'AGENTS.md');
        if (!(await fileExists(agentsMdPath))) {
            blockers.push({ code: 'MISSING_CORE_RULE_FILE', host: 'codex', file: 'AGENTS.md' });
        }
    }
    if (host === 'gemini') {
        const geminiMdPath = join(projectPath, 'GEMINI.md');
        if (!(await fileExists(geminiMdPath))) {
            blockers.push({ code: 'MISSING_CORE_RULE_FILE', host: 'gemini', file: 'GEMINI.md' });
        }
    }
    return { blockers, passed: blockers.length === 0 };
}
export async function handleAuditClaudeConfig(params) {
    const { projectPath, includeGlobal = true, gate } = params;
    // SPEC-724: core-rules gate — runs independently of the standard audit
    if (gate === 'core-rules') {
        const { blockers, passed } = await checkCoreRulesGate(projectPath);
        const text = passed
            ? 'Core rules gate passed: all required host rule files are present.'
            : `Core rules gate failed: ${String(blockers.length)} missing file(s).\n${blockers.map((b) => `- [${b.host}] ${b.file}`).join('\n')}`;
        return {
            content: [{ type: 'text', text }],
            isError: !passed,
            structuredContent: { passed, blockers, score: passed ? 100 : 0 },
        };
    }
    const [claudeMdFindings, rulesFindings, memoryFindings, settingsFindings] = await Promise.all([
        auditClaudeMd(projectPath, includeGlobal),
        auditRules(projectPath, includeGlobal),
        auditMemory(projectPath),
        auditSettings(projectPath),
    ]);
    const allFindings = [
        ...claudeMdFindings,
        ...rulesFindings,
        ...memoryFindings,
        ...settingsFindings,
    ];
    const { score, grade } = calculateScore(allFindings);
    const quickWins = pickQuickWins(allFindings);
    const criticalCount = allFindings.filter((f) => f.severity === 'critical').length;
    const warnCount = allFindings.filter((f) => f.severity === 'warn').length;
    const infoCount = allFindings.filter((f) => f.severity === 'info').length;
    const topQuickWin = quickWins[0]?.suggestion ?? 'none';
    const summary = allFindings.length === 0
        ? `Your Claude Code workspace configuration is excellent! Score: ${String(score)}/100 (${grade}).`
        : `Claude Code workspace audit: ${String(score)}/100 (${grade}). Found ${String(criticalCount)} critical, ${String(warnCount)} warnings, ${String(infoCount)} info items.${quickWins.length > 0 ? ` Top quick win: ${topQuickWin}` : ''}`;
    const criticalItems = allFindings.filter((f) => f.severity === 'critical');
    const warnItems = allFindings.filter((f) => f.severity === 'warn');
    const lines = [
        summary,
        `**score**: ${score}`,
        `**grade**: ${grade}`,
        `**findings**: ${allFindings.length} (${criticalCount} critical, ${warnCount} warn, ${infoCount} info)`,
    ];
    if (criticalItems.length > 0) {
        lines.push('', '## Critical Findings');
        for (const f of criticalItems.slice(0, 10)) {
            lines.push(`- [${f.area}] ${f.message}`);
        }
    }
    if (warnItems.length > 0) {
        lines.push('', '## Warnings');
        for (const f of warnItems.slice(0, 10)) {
            lines.push(`- [${f.area}] ${f.message}`);
        }
    }
    if (quickWins.length > 0) {
        lines.push('', '## Quick Wins');
        for (const q of quickWins.slice(0, 5)) {
            lines.push(`- ${q.suggestion}`);
        }
    }
    return compactResult(lines.join('\n'));
}
//# sourceMappingURL=audit-claude-config.js.map