import { z } from 'zod'

import { apiRoute } from '@/lib/api/handler'
import { parseScenarioText } from '@/lib/engine/scenario-language'

export const dynamic = 'force-dynamic'

const schema = z.object({ text: z.string().trim().min(3).max(400) })

/**
 * Turn a sentence into a runnable scenario (§58).
 *
 * Returns a *preview*, never a run. The operator sees what the parser understood, what
 * it could not place, and how confident it is — and then decides whether to run it. A
 * natural-language interface that executed on its own reading of an ambiguous sentence
 * would be the wrong kind of clever.
 */
export const POST = apiRoute<Record<string, string>, z.infer<typeof schema>>(
  { permission: 'copilot.use', bodySchema: schema, limit: 60 },
  async ({ body }) => {
    const parsed = parseScenarioText(body.text)
    return {
      ...parsed,
      runnable: parsed.events.length > 0,
      source: 'parsed',
    }
  },
)
