import { auditStack } from '../engine/stack-auditor/index.js';
import { saveStackAudit, getLastStackAudit } from '../storage/stack-audit-store.js';
import { hashProjectPath } from '../storage/base-store.js';
import { calculateDXScore, detectTeamScale } from '../engine/platform-engineering/idp-detector.js';
import { analyzeDXGaps } from '../engine/platform-engineering/dx-analyzer.js';
import { detectBuildToolAntiPatterns } from '../engine/stack-auditor/build-tool-auditor.js';
// ---------------------------------------------------------------------------
// Formatters
// ---------------------------------------------------------------------------
function formatSummary(result) {
    const { healthScore, ecosystem, dependencies, runtimeVersions, deltaFromLast } = result;
    const lines = [
        `## Stack Audit — ${ecosystem}`,
        `**Health Score**: ${healthScore.score}/100`,
        `**Total Dependencies**: ${healthScore.totalDeps}`,
        '',
        '### Status Breakdown',
        `- Up to date: ${healthScore.byStatus.up_to_date}`,
        `- Outdated (patch): ${healthScore.byStatus.outdated_patch}`,
        `- Outdated (minor): ${healthScore.byStatus.outdated_minor}`,
        `- Outdated (major): ${healthScore.byStatus.outdated_major}`,
        `- Vulnerable: ${healthScore.byStatus.vulnerable}`,
        `- Unmaintained: ${healthScore.byStatus.unmaintained}`,
    ];
    if (healthScore.topActions.length > 0) {
        lines.push('', '### Top Actions');
        healthScore.topActions.forEach((a, i) => lines.push(`${i + 1}. ${a}`));
    }
    const vulnerable = dependencies.filter((d) => d.statusCode === 'vulnerable');
    if (vulnerable.length > 0) {
        lines.push('', '### Vulnerable Packages');
        vulnerable.forEach((d) => lines.push(`- **${d.name}** ${d.currentVersion} — CVEs: ${d.cves.join(', ')}`));
    }
    if (runtimeVersions.length > 0) {
        lines.push('', '### Runtime Versions');
        runtimeVersions.forEach((r) => lines.push(`- ${r.runtime} ${r.currentVersion} (source: ${r.source})`));
    }
    if (deltaFromLast) {
        lines.push('', '### Delta Since Last Audit');
        lines.push(`- New vulnerabilities: ${deltaFromLast.newVulnerabilities.length}`);
        lines.push(`- Resolved: ${deltaFromLast.resolved.join(', ') || 'none'}`);
        lines.push(`- Worsened: ${deltaFromLast.worsened.length}`);
    }
    return lines.join('\n');
}
function formatDXSection(dxScore) {
    const { score, breakdown, gaps } = dxScore;
    const lines = [
        '',
        '## Developer Experience (DX) Score',
        '',
        `**Score: ${score}/10**${dxScore.platformEngineeringCandidate ? ' — Platform Engineering Candidate' : ''}`,
        '',
        '| Check | Status |',
        '|-------|--------|',
        `| README Getting Started | ${breakdown.readmeGettingStarted ? 'PASS' : 'FAIL'} |`,
        `| Standard Scripts (Makefile/scripts/) | ${breakdown.standardScripts ? 'PASS' : 'FAIL'} |`,
        `| Docker Compose (dev environment) | ${breakdown.devCompose ? 'PASS' : 'FAIL'} |`,
        `| CI/CD Configured | ${breakdown.ciConfigured ? 'PASS' : 'FAIL'} |`,
        `| Observability Basics | ${breakdown.observabilityBasic ? 'PASS' : 'FAIL'} |`,
    ];
    if (gaps.length > 0) {
        lines.push('', '### DX Gaps');
        for (const gap of gaps) {
            lines.push(`- **[${gap.severity.toUpperCase()}]** \`${gap.area}\`: ${gap.message}`);
            lines.push(`  Fix: ${gap.fix}`);
        }
    }
    return lines.join('\n');
}
// ---------------------------------------------------------------------------
// SPEC-050 S6: Build-tool anti-pattern section formatter
// ---------------------------------------------------------------------------
function formatBuildToolAntiPatterns(findings) {
    if (findings.length === 0) {
        return '';
    }
    const lines = ['', '## Build Tool Anti-Patterns', ''];
    for (const finding of findings) {
        lines.push(`- **[${finding.severity.toUpperCase()}]** ${finding.title}`);
        lines.push(`  ${finding.description}`);
        lines.push(`  Fix: ${finding.fix}`);
        lines.push('');
    }
    return lines.join('\n');
}
// ---------------------------------------------------------------------------
// Handler
// ---------------------------------------------------------------------------
export async function handleAuditStack(args) {
    const projectId = hashProjectPath(args.projectPath);
    const lastAudit = await getLastStackAudit(args.projectPath);
    const result = await auditStack(args.projectPath, projectId, {
        deltaMode: !!lastAudit,
        lastAudit: lastAudit ?? undefined,
    });
    await saveStackAudit(args.projectPath, result);
    const format = args.format ?? 'summary';
    if (format === 'json') {
        return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
    }
    const summaryText = formatSummary(result);
    // SPEC-048: Calculate DX score and platform engineering gaps
    // SPEC-050 S6: Build-tool anti-pattern detection
    const [dxScore, teamScale, buildToolFindings] = await Promise.all([
        calculateDXScore(args.projectPath),
        detectTeamScale(args.projectPath),
        detectBuildToolAntiPatterns(args.projectPath),
    ]);
    const platformGapFindings = await analyzeDXGaps(args.projectPath, teamScale);
    const dxSection = formatDXSection(dxScore);
    const buildToolAntiPatternSection = formatBuildToolAntiPatterns(buildToolFindings);
    let platformGapSection = '';
    if (platformGapFindings.length > 0) {
        const gapLines = [
            '',
            '## Platform Engineering Gaps',
            '',
            ...platformGapFindings.map((f) => `- **[${f.severity.toUpperCase()}]** ${f.message}\n  Suggestion: ${f.suggestion}`),
        ];
        platformGapSection = gapLines.join('\n');
    }
    // SPEC-042: Suggest check_config_health for multi-language projects
    const multiLangHint = result.runtimeVersions.length > 1
        ? '\n\n> **Tip**: Multiple runtimes detected. Run `check_config_health` to find cross-language config mismatches (tsconfig coverage, go.mod version, Cargo.toml features, CI version inconsistencies).'
        : '';
    const text = summaryText + dxSection + platformGapSection + buildToolAntiPatternSection + multiLangHint;
    const isError = args.failOn === 'critical'
        ? result.healthScore.byStatus.vulnerable > 0
        : args.failOn === 'warning'
            ? result.healthScore.score < 80
            : false;
    return { content: [{ type: 'text', text }], isError };
}
//# sourceMappingURL=audit-stack.js.map