import type { CreativeModel, CreativePrice } from "@/api/creative";

function priceValue(price: CreativePrice | undefined) {
  if (!price) return "价格未配置";
  const amount = Number(price.price);
  return Number.isFinite(amount) ? `${Number(amount.toFixed(4))} 积分/${price.unit || "次"}` : "价格未配置";
}

export function isTokenBilling(model: CreativeModel | undefined) {
  return model?.model_type === "text" && model.text_billing_mode === "per_token";
}

export function modelPriceLabel(model: CreativeModel | undefined, prices: CreativePrice[], key = "default") {
  if (!model) return "价格未配置";
  if (isTokenBilling(model)) {
    const input = prices.find((item) => item.model_id === model.id && item.price_key.toLowerCase() === "input");
    const output = prices.find((item) => item.model_id === model.id && item.price_key.toLowerCase() === "output");
    return `输入 ${priceValue(input)} · 输出 ${priceValue(output)}`;
  }
  return priceValue(
    prices.find((item) => item.model_id === model.id && item.price_key.toLowerCase() === key.toLowerCase()),
  );
}

export function hasModelPrice(model: CreativeModel | undefined, prices: CreativePrice[], key = "default") {
  if (!model) return false;
  if (isTokenBilling(model)) {
    return ["input", "output"].every((priceKey) =>
      prices.some((item) => item.model_id === model.id && item.price_key.toLowerCase() === priceKey),
    );
  }
  return prices.some((item) => item.model_id === model.id && item.price_key.toLowerCase() === key.toLowerCase());
}
