/**
 * src/lib/nlu/client.ts
 *
 * 调用 intelligent_cabin /api/v1/agent/chat 的 HTTP 客户端。
 * 报错直接抛出，不降级，不 Mock 兜底。
 */

import type { ChatResponse } from "./types";

const NLU_BASE_URL = process.env.NEXT_PUBLIC_NLU_BASE_URL ?? "http://localhost:8000";

export type ChatRequest = {
  session_id: string;
  user_id: string;
  channel?: string;
  input_text: string;
  input_type?: "text" | "voice";
};

export type FillSlotsRequest = {
  session_id: string;
  user_id: string;
  input_text: string;
};

/**
 * 发送文本到 intelligent_cabin 进行 NLU 处理。
 * 报错直接抛出（TypeError、HTTP 4xx/5xx）。
 */
export async function chatWithNlu(request: ChatRequest): Promise<ChatResponse> {
  const res = await fetch(`${NLU_BASE_URL}/api/v1/agent/chat`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      channel: "canvas",
      input_type: "text",
      ...request,
    }),
  });

  if (!res.ok) {
    const body = await res.text().catch(() => "(empty)");
    throw new Error(`NLU service error ${res.status}: ${body}`);
  }

  return (await res.json()) as ChatResponse;
}

/**
 * 填写 slot 值（在 waiting_slot 状态下调用）。
 * 报错直接抛出。
 */
export async function fillSlotsWithNlu(request: FillSlotsRequest): Promise<ChatResponse> {
  const res = await fetch(`${NLU_BASE_URL}/api/v1/agent/fill-slots`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(request),
  });

  if (!res.ok) {
    const body = await res.text().catch(() => "(empty)");
    throw new Error(`NLU fill-slots error ${res.status}: ${body}`);
  }

  return (await res.json()) as ChatResponse;
}
