// tools/living-spec-coverage.ts — living_spec_coverage handler
import { readFile } from 'node:fs/promises';
import { compactResult, compactError } from './output-formatter.js';
import { parseVitestJson, parseJUnitXml, groupByAnnotation, buildCoverageReport, } from '../engine/living-spec/index.js';
export async function handleLivingSpecCoverage(args) {
    const { projectId, coverageJsonPath, junitXmlPath } = args;
    if (!coverageJsonPath && !junitXmlPath) {
        return {
            ...compactError('Provide at least one of coverageJsonPath (Vitest JSON) or junitXmlPath (JUnit XML)'),
        };
    }
    const allTests = [];
    let totalTests = 0;
    let passedTests = 0;
    let failedTests = 0;
    // Parse Vitest JSON if provided
    if (coverageJsonPath) {
        try {
            const raw = await readFile(coverageJsonPath, 'utf-8');
            const fileResults = parseVitestJson(raw);
            for (const file of fileResults) {
                for (const test of file.tests) {
                    totalTests++;
                    const passed = test.status === 'passed';
                    if (passed) {
                        passedTests++;
                    }
                    else {
                        failedTests++;
                    }
                    allTests.push({ name: test.name, file: file.filepath, passed });
                }
            }
        }
        catch (err) {
            return compactError(`Failed to read Vitest JSON at ${coverageJsonPath}: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    // Parse JUnit XML if provided
    if (junitXmlPath) {
        try {
            const raw = await readFile(junitXmlPath, 'utf-8');
            const cases = parseJUnitXml(raw);
            for (const tc of cases) {
                totalTests++;
                if (tc.passed) {
                    passedTests++;
                }
                else {
                    failedTests++;
                }
                allTests.push({ name: tc.name, file: tc.file, passed: tc.passed });
            }
        }
        catch (err) {
            return compactError(`Failed to read JUnit XML at ${junitXmlPath}: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    const groups = groupByAnnotation(allTests, []);
    const report = buildCoverageReport(projectId, groups, totalTests, passedTests, failedTests);
    const message = `Processed ${totalTests} test(s): ${passedTests} passed, ${failedTests} failed. Coverage: ${report.coveragePercentage}%`;
    const lines = [
        message,
        `**coveragePercentage**: ${report.coveragePercentage}%`,
        `**totalTests**: ${totalTests}`,
        `**passedTests**: ${passedTests}`,
        `**failedTests**: ${failedTests}`,
    ];
    return compactResult(lines.join('\n'));
}
//# sourceMappingURL=living-spec-coverage.js.map