import type { DnsRecord } from "../types";

export function recordContentPreview(rec: DnsRecord): string {
  if (rec.data && typeof rec.data === "object") {
    return JSON.stringify(rec.data);
  }
  return rec.content ?? "—";
}

export function proxiedLabel(rec: DnsRecord): string {
  if (rec.proxiable) {
    return rec.proxied ? "已代理" : "仅 DNS";
  }
  return "—";
}

/** DNS 类型 pill 的配色类名（如 pill-dns-CNAME） */
export function dnsRecordTypeClass(type: string): string {
  const key = type.toUpperCase().replace(/[^A-Z0-9]/g, "") || "UNKNOWN";
  return `pill-dns-${key}`;
}

function isIpv4(s: string): boolean {
  const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(s.trim());
  if (!m) return false;
  return [m[1], m[2], m[3], m[4]].every((oct) => {
    const n = Number(oct);
    return n >= 0 && n <= 255 && oct === String(n);
  });
}

function looksLikeIpv6(s: string): boolean {
  const t = s.trim();
  if (!t.includes(":") || /\s/.test(t)) return false;
  return /^[0-9a-fA-F:.]+$/.test(t) && t.split(":").length >= 2;
}

/** 记录内容展示用的语义色（IP / 域名 / JSON 等） */
export function recordContentToneClass(rec: DnsRecord): string {
  if (rec.data && typeof rec.data === "object") return "record-content--json";
  const c = (rec.content ?? "").trim();
  if (!c) return "record-content--empty";
  if (isIpv4(c)) return "record-content--ipv4";
  if (looksLikeIpv6(c)) return "record-content--ipv6";
  return "record-content--host";
}

export function proxiedBadgeClass(rec: DnsRecord): string {
  if (rec.proxiable) {
    return rec.proxied ? "proxy-badge proxy-on" : "proxy-badge proxy-off";
  }
  return "proxy-badge proxy-na";
}

export function ttlTagClass(rec: DnsRecord): string {
  return rec.ttl === 1 ? "ttl-tag ttl-auto" : "ttl-tag ttl-num";
}
