import { NONE_SELECT_VALUE, type SelectOption } from "./types";

export const MD5_PATTERN = /^[a-fA-F0-9]{32}$/;

export function optionOrNone(label: string, options: SelectOption[]) {
  return [{ value: NONE_SELECT_VALUE, label }, ...options];
}

export function optionLabel(options: SelectOption[], value: unknown) {
  const text = String(value ?? "").trim();
  if (!text || text === NONE_SELECT_VALUE) return "—";
  return options.find((option) => option.value === text)?.label || text;
}

export function boolLabel(value: unknown) {
  if (value === true || value === "true") return "是";
  if (value === false || value === "false") return "否";
  return "—";
}

export function truncateText(value: unknown, max = 32) {
  const text = String(value ?? "").trim();
  if (!text) return "—";
  return text.length > max ? `${text.slice(0, max)}…` : text;
}

export function warnMd5Checksum(value: unknown) {
  const normalized = String(value ?? "").trim();
  if (!normalized) return null;
  if (!MD5_PATTERN.test(normalized)) {
    return "MD5 建议为 32 位十六进制，当前格式可能不规范（不阻断保存）";
  }
  return null;
}

export function sumBasesLength(pages: Array<{ bases?: string | null }>) {
  return pages.reduce((total, page) => total + String(page.bases ?? "").length, 0);
}
