import { HAPPY_HORSE_UI_MODEL } from "./happyHorseRouting";
import { VIDU_UI_MODEL } from "./viduRouting";
import { PIXVERSE_UI_MODEL } from "./pixverseRouting";

export const ENTERPRISE_KLING_MODEL = "kling-3.0-dashscope";
export const ENTERPRISE_WANXIANG_I2V_MODEL = "wan2.7-i2v";

export const ENTERPRISE_VIDEO_MODEL_OPTIONS = [
  {
    value: HAPPY_HORSE_UI_MODEL,
    label: "HappyHorse 1.0",
    description: "自动匹配文生视频、首帧图生视频或参考图生视频",
  },
  {
    value: VIDU_UI_MODEL,
    label: "Vidu Q3 Turbo",
    description: "自动匹配文生视频或图生视频，支持16秒",
  },
  {
    value: PIXVERSE_UI_MODEL,
    label: "PixVerse V6",
    description: "自动匹配文生视频或图生视频，擅长动作特效",
  },
  {
    value: ENTERPRISE_WANXIANG_I2V_MODEL,
    label: "万相 图生视频",
    description: "图生视频模型，支持首帧图驱动",
  },
  {
    value: ENTERPRISE_KLING_MODEL,
    label: "Kling V3 Omni",
    description: "支持文生视频、图生视频及多模态参考生成",
  },
] as const;

export const ENTERPRISE_VIDEO_RESOLUTION_OPTIONS = [
  { value: "720P", label: "720P" },
  { value: "1080P", label: "1080P" },
] as const;

export const ENTERPRISE_DEFAULT_VIDEO_MODEL = HAPPY_HORSE_UI_MODEL;
export const ENTERPRISE_DEFAULT_VIDEO_RESOLUTION = "1080P";
const CREDITS_PER_CNY = 100;

export interface EnterpriseVideoPricingInput {
  model: string;
  resolution: string;
  durationSeconds: number;
  muted?: boolean;
  hasReferenceVideo?: boolean;
}

export interface EnterpriseVideoPricingRule {
  id: string;
  modelIncludes: string[];
  when?: {
    muted?: boolean;
    hasReferenceVideo?: boolean;
  };
  rates: Record<string, number>;
}

export interface EnterpriseVideoPricingConfig {
  currency?: string;
  creditsPerCny?: number;
  billingUnit?: "per_second" | string;
  defaultResolution?: string;
  resolutions?: string[];
  rules: EnterpriseVideoPricingRule[];
}

export const FALLBACK_ENTERPRISE_VIDEO_PRICING_CONFIG: EnterpriseVideoPricingConfig = {
  currency: "CNY",
  creditsPerCny: CREDITS_PER_CNY,
  billingUnit: "per_second",
  defaultResolution: ENTERPRISE_DEFAULT_VIDEO_RESOLUTION,
  resolutions: ["720P", "1080P"],
  rules: [
    {
      id: "happyhorse",
      modelIncludes: ["happyhorse"],
      rates: { "720P": 0.72, "1080P": 1.28 },
    },
    {
      id: "wanxiang-i2v",
      modelIncludes: ["wan2.7-i2v", "wanxiang"],
      rates: { "720P": 0.6, "1080P": 1 },
    },
    {
      id: "wan-animate-s2v",
      modelIncludes: ["animate-mix", "s2v"],
      rates: { "720P": 0.6, "1080P": 1 },
    },
    {
      id: "kling-muted-reference",
      modelIncludes: ["kling"],
      when: { muted: true, hasReferenceVideo: true },
      rates: { "720P": 0.9, "1080P": 1.2 },
    },
    {
      id: "kling-muted",
      modelIncludes: ["kling"],
      when: { muted: true, hasReferenceVideo: false },
      rates: { "720P": 0.6, "1080P": 0.8 },
    },
    {
      id: "kling-default",
      modelIncludes: ["kling"],
      rates: { "720P": 0.9, "1080P": 1.2 },
    },
    {
      id: "vidu",
      modelIncludes: ["vidu"],
      rates: { "720P": 0.6, "1080P": 1 },
    },
    {
      id: "pixverse",
      modelIncludes: ["pixverse"],
      rates: { "720P": 0.6, "1080P": 1 },
    },
  ],
};

export function normalizeEnterpriseResolution(value: string): "720P" | "1080P" {
  return String(value || "").toUpperCase() === "720P" ? "720P" : "1080P";
}

function enterpriseVideoPricingRuleMatches(
  rule: EnterpriseVideoPricingRule,
  input: EnterpriseVideoPricingInput,
  model: string,
): boolean {
  if (!rule.modelIncludes.some((pattern) => model.includes(String(pattern || "").toLowerCase()))) return false;
  if (!rule.when) return true;
  if ("muted" in rule.when && Boolean(input.muted) !== rule.when.muted) return false;
  if ("hasReferenceVideo" in rule.when && Boolean(input.hasReferenceVideo) !== rule.when.hasReferenceVideo) {
    return false;
  }
  return true;
}

export function getEnterpriseVideoCreditRate(
  input: EnterpriseVideoPricingInput,
  config: EnterpriseVideoPricingConfig = FALLBACK_ENTERPRISE_VIDEO_PRICING_CONFIG,
): number {
  const resolution = normalizeEnterpriseResolution(input.resolution);
  const model = String(input.model || "").toLowerCase();
  const fallbackResolution = normalizeEnterpriseResolution(
    config.defaultResolution || ENTERPRISE_DEFAULT_VIDEO_RESOLUTION,
  );
  const rule = config.rules.find((candidate) => enterpriseVideoPricingRuleMatches(candidate, input, model));

  if (rule) {
    const rate = rule.rates[resolution] ?? rule.rates[fallbackResolution];
    if (Number.isFinite(rate) && rate >= 0) return rate;
  }

  throw new Error(`Unsupported enterprise video model: ${input.model}`);
}

export function calculateEnterpriseVideoCredits(
  input: EnterpriseVideoPricingInput,
  config: EnterpriseVideoPricingConfig = FALLBACK_ENTERPRISE_VIDEO_PRICING_CONFIG,
): number {
  const duration = Math.max(1, Math.ceil(Number(input.durationSeconds) || 1));
  const creditsPerCny = Number(config.creditsPerCny || CREDITS_PER_CNY);
  return Number((getEnterpriseVideoCreditRate(input, config) * duration * creditsPerCny).toFixed(2));
}
