// tools/generate-tests.ts — Generate test scaffold from spec
// Uses project knowledge + spec to create test definitions
import { t, ti } from '../i18n/index.js';
import { knowledgeStore, specStore } from '../storage/index.js';
import { generateUnitTestContent, generateIntegrationTestContent, generateE2eTestContent, buildTestCommands, } from './generate-tests-content.js';
import { buildContractMockSummaryLines } from './generate-tests/adapters/contract-testing-adapter.js';
import { handlePlanMode } from './generate-tests/plan-mode-handler.js';
import { runSpecializedGenerators } from './generate-tests/spec-dispatcher.js';
import { inferTestFramework, inferTestDir, getTestExt, generateUnitTestDefs, generateIntegrationTestDefs, generateE2eTestDefs, } from './generate-tests/test-helpers.js';
export async function handleGenerateTests(args) {
    const { specId, projectId, autoGenerate = false } = args;
    const knowledge = await knowledgeStore.getKnowledge(projectId);
    if (!knowledge) {
        return {
            content: [
                {
                    type: 'text',
                    text: ti('errors.projectNotFound', { projectId }),
                },
            ],
            isError: true,
        };
    }
    // SPEC-058a: Plan mode — generate full layered test plan for the project
    if (specId === '_plan') {
        return handlePlanMode(projectId, knowledge);
    }
    const spec = await specStore.getSpec(projectId, specId);
    if (!spec) {
        return {
            content: [
                {
                    type: 'text',
                    text: ti('errors.specNotFound', { specId }),
                },
            ],
            isError: true,
        };
    }
    // Determine test framework from project knowledge
    const testFramework = inferTestFramework(knowledge.language, knowledge.stack);
    const testDir = inferTestDir(knowledge.language);
    const testExt = getTestExt(knowledge.language);
    // Generate test definitions based on spec
    const unitTests = generateUnitTestDefs(spec.title, spec.target, testDir);
    const integrationTests = generateIntegrationTestDefs(spec.title, spec.target, testDir);
    const e2eTests = generateE2eTestDefs(spec.title, spec.target, testDir);
    // Generate test files with scaffolding
    const testFiles = [];
    const slug = spec.id.toLowerCase().replace(/[^a-z0-9]/g, '-');
    // Unit test file
    testFiles.push({
        path: `${testDir}/unit/${slug}.test.${testExt}`,
        framework: testFramework,
        content: generateUnitTestContent(spec.title, spec.target, testFramework, knowledge.language),
        ready: autoGenerate,
    });
    // Integration test file
    if (spec.target === 'backend' || spec.target === 'fullstack') {
        testFiles.push({
            path: `${testDir}/integration/${slug}.integration.test.${testExt}`,
            framework: testFramework,
            content: generateIntegrationTestContent(spec.title, testFramework, knowledge.language),
            ready: autoGenerate,
        });
    }
    // E2E test file
    if (spec.target === 'frontend' || spec.target === 'fullstack') {
        const e2eFramework = knowledge.stack.includes('playwright')
            ? 'playwright'
            : knowledge.stack.includes('cypress')
                ? 'cypress'
                : 'playwright';
        testFiles.push({
            path: `${testDir}/e2e/${slug}.e2e.test.${testExt}`,
            framework: e2eFramework,
            content: generateE2eTestContent(spec.title, e2eFramework),
            ready: autoGenerate,
        });
    }
    // Dispatch spec-specific generators (agents, smart contracts, ML, games, MCP, events, etc.)
    const { isApiSpec } = runSpecializedGenerators({ spec, knowledge, testDir, testFramework, slug, autoGenerate, testExt }, unitTests, integrationTests, testFiles);
    const commands = buildTestCommands(knowledge.testCommand, testFramework);
    const result = {
        unitTests,
        integrationTests,
        e2eTests,
        manualTests: [
            `Manually verify ${spec.title} in development environment`,
            'Check edge cases not covered by automated tests',
            'Verify visual appearance matches design',
        ],
        coverageTarget: 80,
        testFiles,
        commands,
    };
    // Format output
    const lines = [
        `## ${t('tools.generate_tests.description')}`,
        '',
        `**Spec:** ${spec.title} (\`${spec.id}\`)`,
        `**Framework:** ${testFramework}`,
        `**Coverage target:** ${result.coverageTarget}%`,
        '',
    ];
    if (result.unitTests.length > 0) {
        lines.push('### Unit Tests');
        lines.push('');
        for (const test of result.unitTests) {
            lines.push(`- **${test.name}** (${test.priority}) — ${test.description}`);
            lines.push(`  File: \`${test.file}\``);
        }
        lines.push('');
    }
    if (result.integrationTests.length > 0) {
        lines.push('### Integration Tests');
        lines.push('');
        for (const test of result.integrationTests) {
            lines.push(`- **${test.name}** (${test.priority}) — ${test.description}`);
            lines.push(`  File: \`${test.file}\``);
        }
        lines.push('');
    }
    if (result.e2eTests.length > 0) {
        lines.push('### E2E Tests');
        lines.push('');
        for (const test of result.e2eTests) {
            lines.push(`- **${test.name}** (${test.priority}) — ${test.description}`);
            lines.push(`  File: \`${test.file}\``);
        }
        lines.push('');
    }
    if (result.manualTests.length > 0) {
        lines.push('### Manual Tests');
        lines.push('');
        for (const test of result.manualTests) {
            lines.push(`- [ ] ${test}`);
        }
        lines.push('');
    }
    // SPEC-018: Contract + mock summary (API specs only)
    if (isApiSpec) {
        lines.push(...buildContractMockSummaryLines(spec.title, knowledge));
    }
    // Show generated files
    if (result.testFiles.length > 0) {
        lines.push('### Generated Test Files');
        lines.push('');
        for (const file of result.testFiles) {
            lines.push(`#### \`${file.path}\``);
            lines.push('');
            const ext = file.path.endsWith('.py') ? 'python' : 'typescript';
            lines.push(`\`\`\`${ext}`);
            lines.push(file.content);
            lines.push('```');
            lines.push('');
        }
    }
    // Commands
    if (result.commands.length > 0) {
        lines.push('### Commands');
        lines.push('');
        lines.push('```bash');
        for (const cmd of result.commands) {
            lines.push(cmd);
        }
        lines.push('```');
    }
    return {
        content: [{ type: 'text', text: lines.join('\n') }],
    };
}
//# sourceMappingURL=generate-tests.js.map