import { apiFetch } from "@/lib/apiFetch";
import { config } from "@config/config";

import type { AgentModel } from "./chatStream";

export type AgentModelIcon = "bolt" | "sparkle";

export type AgentModelOption = {
  id: AgentModel;
  label: string;
  description?: string;
  icon?: AgentModelIcon;
};

export type AgentModelConfig = {
  defaultModel?: AgentModel;
  models: AgentModelOption[];
};

const isObjectRecord = (value: unknown): value is Record<string, unknown> =>
  typeof value === "object" && value !== null && !Array.isArray(value);

const normalizeModelOption = (value: unknown): AgentModelOption | null => {
  if (!isObjectRecord(value) || typeof value.id !== "string") {
    return null;
  }
  const id = value.id.trim();
  if (!id) {
    return null;
  }
  const label =
    typeof value.label === "string" && value.label.trim()
      ? value.label.trim()
      : id;
  const description =
    typeof value.description === "string" && value.description.trim()
      ? value.description.trim()
      : undefined;
  const icon =
    value.icon === "bolt" || value.icon === "sparkle" ? value.icon : undefined;
  return {
    id,
    label,
    description,
    icon,
  };
};

export const fetchAgentModels = async (): Promise<AgentModelConfig> => {
  const response = await apiFetch(`${config.AGENT_URL}/api/v1/agent/models`, {
    method: "GET",
    projectHeaderMode: "include",
    skipAuthRedirect: true,
  });
  if (!response.ok) {
    throw new Error(await response.text());
  }
  const payload = (await response.json()) as {
    default_model?: unknown;
    models?: unknown[];
  };
  const models = (payload.models ?? [])
    .map(normalizeModelOption)
    .filter((model): model is AgentModelOption => Boolean(model));
  const defaultModel =
    typeof payload.default_model === "string" && payload.default_model.trim()
      ? payload.default_model.trim()
      : models[0]?.id;
  return {
    defaultModel,
    models,
  };
};
