// tools/diagram-handler.ts — SPEC-311: generate_diagram tool handler
import { generateExcalidrawDiagram, toExcalidrawUrl, } from '../engine/diagram/excalidraw-generator.js';
/** Handle the generate_diagram tool request. */
export function handleGenerateDiagram(args) {
    const { description, diagramType, format } = args;
    if (format === 'mermaid') {
        const mermaid = buildMermaid(description, diagramType);
        return Promise.resolve({
            content: [
                {
                    type: 'text',
                    text: [`## Mermaid Diagram — ${diagramType}`, '', '```mermaid', mermaid, '```'].join('\n'),
                },
            ],
        });
    }
    // format === 'excalidraw'
    const diagram = generateExcalidrawDiagram(description, diagramType);
    const url = toExcalidrawUrl(diagram);
    return Promise.resolve({
        content: [
            {
                type: 'text',
                text: [
                    `## Excalidraw Diagram — ${diagramType}`,
                    '',
                    `**Open in Excalidraw:** ${url}`,
                    '',
                    '**JSON:**',
                    '```json',
                    JSON.stringify(diagram, null, 2),
                    '```',
                ].join('\n'),
            },
        ],
    });
}
// ---------------------------------------------------------------------------
// Minimal mermaid fallback for 'mermaid' format
// ---------------------------------------------------------------------------
function buildMermaid(description, diagramType) {
    const separators = /->|→|--|,|\n/;
    const nodes = description
        .split(separators)
        .map((s) => s.trim())
        .filter((s) => s.length > 0);
    if (diagramType === 'sequence') {
        const lines = ['sequenceDiagram'];
        for (let i = 0; i < nodes.length - 1; i++) {
            const a = nodes[i] ?? 'A';
            const b = nodes[i + 1] ?? 'B';
            lines.push(`  ${sanitize(a)}->>+${sanitize(b)}: call`);
        }
        return lines.join('\n');
    }
    if (diagramType === 'er') {
        const lines = ['erDiagram'];
        for (let i = 0; i < nodes.length - 1; i++) {
            const a = nodes[i] ?? 'A';
            const b = nodes[i + 1] ?? 'B';
            lines.push(`  ${sanitize(a)} ||--o{ ${sanitize(b)} : has`);
        }
        return lines.join('\n');
    }
    // Default: flowchart LR
    const lines = ['flowchart LR'];
    for (let i = 0; i < nodes.length - 1; i++) {
        const a = nodes[i] ?? 'A';
        const b = nodes[i + 1] ?? 'B';
        lines.push(`  ${sanitize(a)} --> ${sanitize(b)}`);
    }
    return lines.join('\n');
}
function sanitize(label) {
    return label.replace(/\s+/g, '_').replace(/[^a-zA-Z0-9_]/g, '');
}
//# sourceMappingURL=diagram-handler.js.map