import { mintOpenAIRealtimeSession, realtimeConfigured } from '../../../../../lib/realtime-openai.js';
import { checkLimit, recordCall } from '../../../../../lib/tool-rate-limits.js';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

const ROUTE_RATE_LIMIT = { window_seconds: 3600, max: 20 };

export async function GET() {
  return Response.json({ configured: realtimeConfigured(), provider: 'openai' });
}

export async function POST(request) {
  const limit = checkLimit('openai_realtime_session', null, { rate_limit: ROUTE_RATE_LIMIT });
  if (!limit.ok) {
    return Response.json(
      { error: 'rate_limited', retry_after_seconds: limit.retry_after_seconds },
      { status: 429, headers: { 'Retry-After': String(limit.retry_after_seconds) } },
    );
  }

  let body;
  try {
    body = await request.json();
  } catch {
    return Response.json({ error: 'invalid JSON body' }, { status: 400 });
  }

  try {
    const session = await mintOpenAIRealtimeSession({
      voice: body?.voice,
      model: body?.model,
      // Callers can override instructions/tools, but by default the session
      // mint pulls the durable Madarx context (project, recent artifacts,
      // memory) and the curated voice tool catalog.
      instructions: typeof body?.instructions === 'string' && body.instructions.trim()
        ? body.instructions
        : undefined,
      tools: Array.isArray(body?.tools) ? body.tools : undefined,
      project_id: body?.project_id || null,
      agent_id: body?.agent_id || 'main',
      active_space: body?.active_space || null,
      all_spaces: Array.isArray(body?.all_spaces) ? body.all_spaces : null,
      speaking_style: typeof body?.speaking_style === 'string' ? body.speaking_style : null,
    });
    recordCall('openai_realtime_session', null, { rate_limit: ROUTE_RATE_LIMIT });
    return Response.json(session, { headers: { 'Cache-Control': 'no-store' } });
  } catch (err) {
    return Response.json({ error: String(err?.message || err) }, { status: 502 });
  }
}
