import { NextResponse } from 'next/server';
import { spawnSync } from 'child_process';
import path from 'path';

export async function POST(request: Request) {
  try {
    const { markdown } = await request.json();
    if (typeof markdown !== 'string') {
      return NextResponse.json({ error: 'Invalid markdown' }, { status: 400 });
    }
    // Call Rust backend with 'render' command, pass markdown via stdin
    const rustPath = path.resolve(process.cwd(), 'markdown_backend/target/release/markdown_backend');
    const rustResult = spawnSync(rustPath, ['render'], {
      input: markdown,
      encoding: 'utf-8',
    });
    if (rustResult.status === 0 && rustResult.stdout) {
      return NextResponse.json({ html: rustResult.stdout });
    } else {
      const rustError = rustResult.stderr || rustResult.error?.toString() || 'Unknown error';
      return NextResponse.json({ error: 'Rust parser error', details: rustError }, { status: 500 });
    }
  } catch (error) {
    return NextResponse.json({ error: 'Error rendering markdown', details: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 });
  }
} 