import type { UsageEvent, UsageKeyMode, UsageMeter } from "./usageMeter";

type TFn = (key: string, params?: Record<string, string | number>) => string;

/** 後端 source 穩定鍵 → i18n */
const SOURCE_I18N: Record<string, string> = {
  "personas.analyzeFromText": "usage.event.source.personaAnalyzeText",
  "personas.analyzeFromAccount": "usage.event.source.personaAnalyzeAccount",
  "compose.mimic": "usage.event.source.composeMimic",
  "compose.analyzeViral": "usage.event.source.composeViral",
  "ownPosts.analyze": "usage.event.source.ownPostAnalyze",
  "compose.personaPreview": "usage.event.source.personaPreview",
  "ownPosts.generateReply": "usage.event.source.ownPostReply",
  "mentions.generateReply": "usage.event.source.mentionReply",
  "inspire.chat": "usage.event.source.inspireChat",
  "research.search": "usage.event.source.researchSearch",
  "media.generateImage": "usage.event.source.generateImage",
  "proxy.search": "usage.event.source.proxySearch",
  "proxy.ai": "usage.event.source.proxyAi",
};

/** 後端 label（歷史英文／混用）→ i18n */
const LABEL_I18N: Record<string, string> = {
  "persona analyze text": "usage.event.label.personaAnalyzeText",
  "persona analyze account": "usage.event.label.personaAnalyzeAccount",
  "compose mimic": "usage.event.label.composeMimic",
  "compose analyze viral": "usage.event.label.composeViral",
  "persona preview": "usage.event.label.personaPreview",
  "own post reply draft": "usage.event.label.ownPostReply",
  "mention reply draft": "usage.event.label.mentionReply",
  "inspire chat": "usage.event.label.inspireChat",
  "research search": "usage.event.label.researchSearch",
  "generate image": "usage.event.label.generateImage",
  search: "usage.event.label.search",
  "AI complete": "usage.event.label.aiComplete",
  // 舊測試／簡寫
  copy: "usage.event.label.genericAi",
  byok: "usage.event.label.genericAi",
  ai: "usage.event.label.genericAi",
};

function tryT(t: TFn, key: string): string | null {
  const v = t(key);
  if (!v || v === key) return null;
  return v;
}

/** 使用紀錄主標（優先 source 映射，再 label） */
export function usageEventTitle(e: Pick<UsageEvent, "label" | "source">, t: TFn): string {
  const src = (e.source || "").trim();
  if (src && SOURCE_I18N[src]) {
    const tr = tryT(t, SOURCE_I18N[src]);
    if (tr) return tr;
  }
  const lab = (e.label || "").trim();
  const labKey = LABEL_I18N[lab] || LABEL_I18N[lab.toLowerCase()];
  if (labKey) {
    const tr = tryT(t, labKey);
    if (tr) return tr;
  }
  // 已是中文或未知：原樣顯示
  return lab || src || t("usage.event.label.unknown");
}

/** 副標：計費維度 · 平台／自備 key */
export function usageEventSubtitle(
  e: Pick<UsageEvent, "meter" | "key_mode" | "source">,
  t: TFn,
): string {
  const parts: string[] = [];
  const meterKey = `usage.meter.${e.meter as UsageMeter}`;
  const meter = tryT(t, meterKey) || e.meter;
  parts.push(meter);
  parts.push(usageKeyModeLabel(e.key_mode, t));
  return parts.join(" · ");
}

export function usageKeyModeLabel(mode: UsageKeyMode | string, t: TFn): string {
  if (mode === "byok") return t("usage.event.keyMode.byok");
  if (mode === "platform") return t("usage.event.keyMode.platform");
  return mode || t("usage.event.keyMode.platform");
}

/** 點數顯示：BYOK 不扣平台點 */
export function usageEventCostText(e: Pick<UsageEvent, "credits" | "key_mode">, t: TFn): string {
  if (e.key_mode === "byok" || e.credits === 0) {
    return t("usage.event.cost.byok");
  }
  return t("usage.event.cost.credits", { n: e.credits });
}
