/**
 * 统一 AI Chat Completions 调用入口
 *
 * 行为：
 *  - 配置了 AI_HUB_API_KEY + AI_HUB_BASE_URL 时，所有原本走 Lovable Gateway 的请求改走中台
 *  - 未配置时回退到 Lovable Gateway（保持向后兼容）
 *  - Lovable 风格的模型名（google/openai/anthropic 前缀）映射为中台默认 agent
 *
 * 用法：
 *   const r = await lovableChat({ model: 'google/gemini-2.5-flash', messages, response_format: ... });
 *   const j = await r.json();
 */

const HUB_KEY = Deno.env.get("AI_HUB_API_KEY") || "";
const HUB_BASE = (Deno.env.get("AI_HUB_BASE_URL") || "").replace(/\/+$/, "");
const HUB_DEFAULT_MODEL = Deno.env.get("AI_HUB_DEFAULT_CHAT_MODEL") || "agent-default";

export function aiHubEnabled(): boolean {
  return !!(HUB_KEY && HUB_BASE);
}

function mapModel(model: string): string {
  if (!model) return HUB_DEFAULT_MODEL;
  if (/^(google|openai|anthropic)\//i.test(model)) return HUB_DEFAULT_MODEL;
  return model;
}

export interface ChatBody {
  model: string;
  messages: any[];
  // 任意其他 OpenAI 风格字段
  [k: string]: unknown;
}

/** 统一返回 fetch Response，调用方自行 .ok / .json() / 流式处理 */
export async function lovableChat(body: ChatBody, init?: { signal?: AbortSignal }): Promise<Response> {
  if (aiHubEnabled()) {
    const finalBody = { ...body, model: mapModel(body.model) };
    return await fetch(`${HUB_BASE}/chat/completions`, {
      method: "POST",
      headers: { Authorization: `Bearer ${HUB_KEY}`, "Content-Type": "application/json" },
      body: JSON.stringify(finalBody),
      signal: init?.signal,
    });
  }
  const key = Deno.env.get("LOVABLE_API_KEY") || "";
  return await fetch("https://ai.gateway.lovable.dev/v1/chat/completions", {
    method: "POST",
    headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
    body: JSON.stringify(body),
    signal: init?.signal,
  });
}

/** 快捷：JSON 形态返回 message.content（非流式） */
export async function lovableChatText(body: ChatBody): Promise<string> {
  const r = await lovableChat(body);
  if (!r.ok) {
    const t = await r.text().catch(() => "");
    throw new Error(`AI chat upstream ${r.status}: ${t.slice(0, 200)}`);
  }
  const j = await r.json();
  return j?.choices?.[0]?.message?.content?.trim() ?? "";
}
