/** OpenCode Go 模型特性與呼叫設定（對照 https://opencode.ai/docs/go/） */

export const OPENCODE_GO_MESSAGES_MODELS = new Set([
  "minimax-m3",
  "minimax-m2.7",
  "minimax-m2.5",
  "qwen3.7-max",
  "qwen3.7-plus",
  "qwen3.6-plus",
  "qwen3.5-plus",
]);

/** Kimi 只接受 temperature = 1 */
export const OPENCODE_GO_KIMI_MODELS = new Set(["kimi-k2.7-code", "kimi-k2.6", "kimi-k2.5"]);

/** structured output（generateObject）不穩，優先走 JSON 文字解析 */
export const OPENCODE_GO_TEXT_FIRST_MODELS = new Set([
  "deepseek-v4-flash",
  "deepseek-v4-pro",
  "glm-5.1",
  "glm-5",
  "kimi-k2.7-code",
  "kimi-k2.6",
  "kimi-k2.5",
  "mimo-v2.5",
  "mimo-v2.5-pro",
  "minimax-m3",
  "minimax-m2.7",
  "minimax-m2.5",
  "qwen3.7-max",
  "qwen3.7-plus",
  "qwen3.6-plus",
  "qwen3.5-plus",
]);

export function isOpenCodeGoProvider(provider: string): boolean {
  return provider === "opencode-go";
}

export function getOpenCodeGenerationSettings(provider: string, modelId: string) {
  if (!isOpenCodeGoProvider(provider)) return {};
  if (OPENCODE_GO_KIMI_MODELS.has(modelId)) {
    return { temperature: 1 as const };
  }
  return {};
}

export function prefersOpenCodeTextFirst(provider: string, modelId: string): boolean {
  return isOpenCodeGoProvider(provider) && OPENCODE_GO_TEXT_FIRST_MODELS.has(modelId);
}

/** 將 OpenCode Go / provider 常見 API 錯誤轉成可讀訊息 */
export function explainProviderApiError(message: string, responseBody?: string): string | null {
  const combined = `${message} ${responseBody ?? ""}`.toLowerCase();

  if (
    combined.includes("temperature") &&
    (combined.includes("kimi") || combined.includes("only support"))
  ) {
    return "Kimi 模型只接受 temperature=1。請重新整理頁面後再試，或暫時改用 DeepSeek / GLM。";
  }
  if (
    combined.includes("invalid api key") ||
    combined.includes("incorrect api key") ||
    combined.includes("unauthorized") ||
    combined.includes("authentication")
  ) {
    return "OpenCode Go API key 無效或未設定，請到設定頁填入從 opencode.ai/auth 取得的 key。";
  }
  if (combined.includes("rate limit") || combined.includes("quota") || combined.includes("usage limit")) {
    return "OpenCode Go 用量已達上限，請到 opencode.ai/auth 查看配額或更換模型。";
  }
  if (combined.includes("model") && (combined.includes("not found") || combined.includes("does not exist"))) {
    return "選用的模型不存在或已下架，請到設定頁更換 OpenCode Go 模型。";
  }

  return null;
}