export const HAPPY_HORSE_UI_MODEL = "happyhorse-1.0";
export const HAPPY_HORSE_UI_LABEL = "HappyHorse 1.0";
export const HAPPY_HORSE_T2V_MODEL = "happyhorse-1.0-t2v";
export const HAPPY_HORSE_I2V_MODEL = "happyhorse-1.0-i2v";
export const HAPPY_HORSE_R2V_MODEL = "happyhorse-1.0-r2v";

export interface HappyHorseModelOption {
  value: string;
  label: string;
  description?: string;
  badge?: string;
}

export function isHappyHorseModel(model: string | undefined | null): boolean {
  return String(model || "").toLowerCase().includes("happyhorse");
}

export function toHappyHorseDisplayModel(model: string): string {
  return isHappyHorseModel(model) ? HAPPY_HORSE_UI_MODEL : model;
}

export function normalizeHappyHorseModelOptions<T extends HappyHorseModelOption>(options: T[]): T[] {
  let hasHappyHorse = false;

  return options.reduce<T[]>((result, option) => {
    if (!isHappyHorseModel(option.value)) {
      result.push(option);
      return result;
    }

    if (hasHappyHorse) return result;
    hasHappyHorse = true;
    result.push({
      ...option,
      value: HAPPY_HORSE_UI_MODEL,
      label: HAPPY_HORSE_UI_LABEL,
      description: "自动匹配文生、首帧图生或参考图生视频",
    });
    return result;
  }, []);
}

export function resolveHappyHorseRequestModel(input: {
  model: string;
  referenceUrls?: string[];
  imageReferenceCount?: number;
}): string {
  if (!isHappyHorseModel(input.model)) return input.model;

  const imageReferenceCount =
    typeof input.imageReferenceCount === "number"
      ? input.imageReferenceCount
      : (input.referenceUrls || []).filter((url) => String(url || "").trim()).length;

  if (imageReferenceCount <= 0) return HAPPY_HORSE_T2V_MODEL;
  if (imageReferenceCount === 1) return HAPPY_HORSE_I2V_MODEL;
  return HAPPY_HORSE_R2V_MODEL;
}
