// tools/schema-generator-handler.ts — Handler for Validation Schema Generator (SPEC-365)
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { dirname } from 'node:path';
import { getSpec } from '../storage/spec-store.js';
import { hashProjectPath } from '../storage/base-store.js';
import { generateSchemas, generateApiClient } from '../engine/schema-generator.js';
async function readSpecText(spec) {
    const parts = [];
    if (spec.description !== undefined) {
        parts.push(spec.description);
    }
    if (spec.specPath !== undefined) {
        try {
            const content = await readFile(spec.specPath, 'utf-8');
            parts.push(content);
        }
        catch {
            // spec file not readable — continue with description only
        }
    }
    return parts.join('\n\n');
}
async function writeOutputFile(outputPath, content) {
    await mkdir(dirname(outputPath), { recursive: true });
    await writeFile(outputPath, content, 'utf-8');
}
export async function handleGenerateValidationSchema(input) {
    const { projectPath, specId, library, outputFormat, outputPath } = input;
    try {
        const projectId = hashProjectPath(projectPath);
        const spec = await getSpec(projectId, specId);
        if (spec === null) {
            return {
                content: [{ type: 'text', text: `Spec "${specId}" not found.` }],
                isError: true,
            };
        }
        const specText = await readSpecText(spec);
        const result = generateSchemas(specId, specText, library, outputFormat, outputPath);
        if (result.entitiesDetected === 0) {
            return {
                content: [
                    {
                        type: 'text',
                        text: `No entities detected in spec "${specId}". ` +
                            'Ensure the spec describes entities using keywords like "model", "schema", "interface", or "type".',
                    },
                ],
            };
        }
        // Write files if outputPath is provided
        if (outputPath !== undefined) {
            for (const schema of result.schemas) {
                const ext = outputFormat === 'typescript' ? '.ts' : '.js';
                const libSuffix = library === 'all' ? `.${schema.library}` : '';
                const filePath = outputPath.replace(/\.(ts|js)$/, '') + libSuffix + ext;
                await writeOutputFile(filePath, schema.code);
            }
        }
        const codeSection = result.schemas
            .map((s) => `### ${s.library}\n\`\`\`${outputFormat}\n${s.code}\`\`\``)
            .join('\n\n');
        return {
            content: [
                {
                    type: 'text',
                    text: `Generated ${library} schema(s) for "${specId}". ` +
                        `Entities detected: ${String(result.entitiesDetected)}.\n\n${codeSection}` +
                        (outputPath !== undefined ? `\n\nWritten to: ${outputPath}` : ''),
                },
            ],
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: `Failed to generate validation schema: ${message}` }],
            isError: true,
        };
    }
}
export async function handleGenerateApiClient(input) {
    const { projectPath, specId, framework, outputPath } = input;
    try {
        const projectId = hashProjectPath(projectPath);
        const spec = await getSpec(projectId, specId);
        if (spec === null) {
            return {
                content: [{ type: 'text', text: `Spec "${specId}" not found.` }],
                isError: true,
            };
        }
        const specText = await readSpecText(spec);
        const result = generateApiClient(specId, specText, framework, outputPath);
        if (result.routesDetected === 0) {
            return {
                content: [
                    {
                        type: 'text',
                        text: `No API routes detected in spec "${specId}". ` +
                            'Ensure the spec describes routes using patterns like "GET /api/...", "POST /api/...".',
                    },
                ],
            };
        }
        if (outputPath !== undefined) {
            await writeOutputFile(outputPath, result.code);
        }
        return {
            content: [
                {
                    type: 'text',
                    text: `Generated ${framework} client for "${specId}". ` +
                        `Routes detected: ${String(result.routesDetected)}.\n\n` +
                        `\`\`\`typescript\n${result.code}\`\`\`` +
                        (outputPath !== undefined ? `\n\nWritten to: ${outputPath}` : ''),
                },
            ],
        };
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
            content: [{ type: 'text', text: `Failed to generate API client: ${message}` }],
            isError: true,
        };
    }
}
//# sourceMappingURL=schema-generator-handler.js.map