import { buildVoiceContext } from '../../../../../lib/voice/context.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: 60, max: 60 };

export async function GET(request) {
  const limit = checkLimit('voice_context', 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) } },
    );
  }

  const url = new URL(request.url);
  const projectId = url.searchParams.get('project_id') || null;
  const agentId = url.searchParams.get('agent_id') || 'main';

  try {
    const context = buildVoiceContext({ project_id: projectId, agent_id: agentId });
    recordCall('voice_context', null, { rate_limit: ROUTE_RATE_LIMIT });
    return Response.json(context, { headers: { 'Cache-Control': 'no-store' } });
  } catch (err) {
    return Response.json({ error: String(err?.message || err) }, { status: 500 });
  }
}
