/**
 * Shared model option utilities.
 *
 * Single source of truth for image/video quality option lookups and defaults,
 * consumed by both the canvas and workbench feature modules.
 */

import type { CanvasOption } from "../features/canvas/canvasTypes";
import {
  fallbackVideoQualityOptions,
  image4kCapableModels,
  imageQualityOptions,
  videoDefaultQualityByModel,
  videoResolutionByModel,
} from "../features/canvas/canvasConstants";
import { toHappyHorseDisplayModel } from "./happyHorseRouting";
import { toPixverseDisplayModel } from "./pixverseRouting";
import { toViduDisplayModel } from "./viduRouting";

// ─── Image quality ────────────────────────────────────────────────────────────

export function getImageQualityOptions(model: string): CanvasOption[] {
  return image4kCapableModels.has(String(model || "").toLowerCase())
    ? imageQualityOptions
    : imageQualityOptions.filter((option) => option.value !== "4K");
}

export function getImageQualityOptionsForContext(
  model: string,
  context?: { hasReferenceImages?: boolean; isGridMode?: boolean },
): CanvasOption[] {
  const options = getImageQualityOptions(model);
  const shouldLimitTo2K =
    String(model || "").toLowerCase() === "wan2.7-image-pro" &&
    (context?.hasReferenceImages || context?.isGridMode);
  return shouldLimitTo2K ? options.filter((option) => option.value !== "4K") : options;
}

export function getDefaultImageQuality(model: string): string {
  const options = getImageQualityOptions(model);
  return options.some((option) => option.value === "2K") ? "2K" : options[0]?.value || "1K";
}

export function getDefaultImageQualityForContext(
  model: string,
  context?: { hasReferenceImages?: boolean; isGridMode?: boolean },
): string {
  const options = getImageQualityOptionsForContext(model, context);
  return options.some((option) => option.value === "2K") ? "2K" : options[0]?.value || "1K";
}

// ─── Video quality ────────────────────────────────────────────────────────────

function normalizeVideoModel(model: string): string {
  return toPixverseDisplayModel(toViduDisplayModel(toHappyHorseDisplayModel(model)));
}

export function getVideoQualityOptions(model: string): CanvasOption[] {
  const normalized = normalizeVideoModel(model);
  return videoResolutionByModel[normalized] || fallbackVideoQualityOptions;
}

export function getDefaultVideoQuality(model: string): string {
  const options = getVideoQualityOptions(model);
  const normalized = normalizeVideoModel(model);
  const preferred = videoDefaultQualityByModel[normalized] || "pro";
  return options.some((option) => option.value === preferred) ? preferred : options[0]?.value || preferred;
}

export function getVideoQualityLabel(model: string, value: string): string {
  return getVideoQualityOptions(model).find((item) => item.value === value)?.label || value;
}
