// engine/self-healing/strategies/test-fix.ts — SPEC-474: Test fix strategy
import { execSync } from 'node:child_process';
/**
 * Parses failing test entries from vitest output.
 * Looks for:
 *   FAIL tests/path/file.test.ts
 *   × test name
 *   AssertionError: expected X to equal Y
 */
function parseFailingTests(output) {
    const results = [];
    const failFilePattern = /^(?:FAIL|×)\s+(tests\/[^\s]+\.test\.ts)/gm;
    const failedFiles = new Set();
    for (const match of output.matchAll(failFilePattern)) {
        if (match[1] !== undefined) {
            failedFiles.add(match[1]);
        }
    }
    const testPattern = /^\s+[×✗]\s+(.+)$/gm;
    const failingTestNames = [];
    for (const match of output.matchAll(testPattern)) {
        if (match[1] !== undefined) {
            failingTestNames.push(match[1].trim());
        }
    }
    const errorPattern = /AssertionError[:\s]+(.+?)(?:\n|$)/g;
    const errors = [];
    for (const match of output.matchAll(errorPattern)) {
        if (match[1] !== undefined) {
            errors.push(match[1].trim());
        }
    }
    for (const filePath of failedFiles) {
        if (failingTestNames.length === 0) {
            results.push({ filePath, testName: '(unknown test)', error: errors[0] ?? 'Unknown error' });
        }
        else {
            failingTestNames.forEach((testName, i) => {
                results.push({ filePath, testName, error: errors[i] ?? errors[0] ?? 'Unknown error' });
            });
        }
    }
    return results;
}
/**
 * Identifies failing tests from `pnpm test` output and reports what needs manual review.
 * Does NOT modify test files — test logic changes require human judgment.
 */
export function applyTestFix(projectPath, _details) {
    return Promise.resolve(runTestDiagnostic(projectPath));
}
function captureTestOutput(projectPath) {
    try {
        execSync('pnpm test', { cwd: projectPath, stdio: 'pipe', encoding: 'utf-8' });
        return null;
    }
    catch (err) {
        const errObj = err;
        return errObj.stdout ?? errObj.stderr ?? errObj.message ?? '';
    }
}
function runTestDiagnostic(projectPath) {
    const output = captureTestOutput(projectPath);
    if (output === null) {
        return { fixed: true, reason: 'All tests pass — no failures detected', fixedIssues: [] };
    }
    const failingTests = parseFailingTests(output);
    if (failingTests.length === 0) {
        const excerpt = output.slice(0, 300).replace(/\n/g, ' ');
        return {
            fixed: false,
            reason: `Tests failed but could not parse individual failures. Raw output: ${excerpt}`,
        };
    }
    const unique = failingTests.filter((t, i, arr) => arr.findIndex((x) => x.filePath === t.filePath && x.testName === t.testName) === i);
    const summary = unique
        .map((t) => `${t.filePath} › "${t.testName}" — ${t.error.slice(0, 100)}`)
        .join('; ');
    return {
        fixed: false,
        reason: `${unique.length.toString()} failing test(s) require manual review: ${summary}`,
        fixedIssues: [],
    };
}
//# sourceMappingURL=test-fix.js.map