// tools/test-reverse-engineer-handler.ts — Handle reverse_engineer_tests tool calls (SPEC-299)
import { z } from 'zod';
import { parseTestFile } from '../engine/reverse-engineer/test-file-parser.js';
import { handleCreateSpec } from './create-spec.js';
export const ReverseEngineerTestsInputSchema = z.object({
    testFilePath: z
        .string()
        .describe('Absolute path to the test file (e.g. Playwright, Cypress, Jest) to parse'),
    projectPath: z
        .string()
        .optional()
        .describe('Absolute path to the project root. Required when createSpec=true'),
    createSpec: z
        .boolean()
        .optional()
        .describe('If true, automatically create a Planu spec from the generated ACs. Requires projectPath.'),
});
function buildTextReport(result, testFilePath) {
    const lines = [
        `Test Reverse Engineering Report`,
        `================================`,
        `File: ${testFilePath}`,
        `Framework: ${result.detectedFramework}`,
        `Total tests: ${result.totalTests} (${result.skipCount} skipped)`,
        `Suggested title: ${result.suggestedTitle}`,
        `Suggested tags: ${result.suggestedTags.join(', ') || '(none)'}`,
        ``,
        `Generated Acceptance Criteria (${result.generatedAcs.length}):`,
    ];
    const groups = new Map();
    for (const ac of result.generatedAcs) {
        const existing = groups.get(ac.group) ?? [];
        existing.push(ac);
        groups.set(ac.group, existing);
    }
    for (const [group, acs] of groups) {
        lines.push(``, `  [${group}]`);
        for (const ac of acs) {
            const skipMark = ac.skipped ? ' (skipped)' : '';
            lines.push(`  - ${ac.text}${skipMark}`);
        }
    }
    return lines.join('\n');
}
/**
 * Handle the reverse_engineer_tests tool.
 * Parses a test file and extracts acceptance criteria.
 * Optionally creates a Planu spec from the generated ACs.
 */
export async function handleReverseEngineerTests(params) {
    const { testFilePath, projectPath, createSpec } = params;
    let result;
    try {
        result = await parseTestFile(testFilePath);
    }
    catch (err) {
        const message = err instanceof Error ? err.message : String(err);
        return {
            content: [
                {
                    type: 'text',
                    text: `Failed to parse test file: ${message}. Ensure the path is absolute and the file exists.`,
                },
            ],
            isError: true,
        };
    }
    const report = buildTextReport(result, testFilePath);
    if (createSpec === true && projectPath) {
        const acLines = result.generatedAcs
            .filter((ac) => !ac.skipped)
            .map((ac) => `- ${ac.text}`)
            .join('\n');
        const description = `Auto-generated from test file: ${testFilePath}\n\n## Acceptance Criteria\n${acLines || '(no active tests found)'}`;
        const createResult = await handleCreateSpec({
            title: result.suggestedTitle,
            description,
            projectPath,
            tags: result.suggestedTags,
        });
        const specContent = createResult.content[0];
        const specText = specContent?.type === 'text' ? specContent.text : '';
        return {
            content: [
                { type: 'text', text: report },
                { type: 'text', text: `\n---\nSpec created:\n${specText}` },
            ],
        };
    }
    return {
        content: [{ type: 'text', text: report }],
    };
}
//# sourceMappingURL=test-reverse-engineer-handler.js.map