import { createHash } from "crypto";

export type Msg = { ts: string; sender: string; text: string; role: "customer" | "cs" };

// Mendukung format ekspor Android ("12/05/2026 14.32 - Nama: pesan")
// dan iOS ("[12/05/26 14.32.05] Nama: pesan"), termasuk jam 12 jam (AM/PM).
const LINE = /^\[?(\d{1,2})[/.-](\d{1,2})[/.-](\d{2,4}),?\s+(\d{1,2})[.:](\d{2})(?:[.:](\d{2}))?\s*([APap]\.?[Mm]\.?)?\]?\s*(?:-\s*)?(.*)$/;

const MEDIA = /(media|gambar|image|video|audio|sticker|stiker|dokumen|document|file).*(omitted|tidak disertakan|attached|terlampir)|^<media/i;

function toIso(m: RegExpExecArray): string | null {
  const [, d, mo, y, h, mi, s, ap] = m;
  let year = Number(y);
  if (year < 100) year += 2000;
  let hour = Number(h);
  if (ap) {
    const pm = /p/i.test(ap);
    if (pm && hour < 12) hour += 12;
    if (!pm && hour === 12) hour = 0;
  }
  // Asumsi tanggal dd/mm dan zona waktu WIB (+07:00)
  const iso = `${year}-${mo.padStart(2, "0")}-${d.padStart(2, "0")}T${String(hour).padStart(2, "0")}:${mi}:${(s ?? "00").padStart(2, "0")}+07:00`;
  const t = new Date(iso);
  return isNaN(t.getTime()) ? null : t.toISOString();
}

export function parseChat(raw: string): Msg[] {
  const out: Omit<Msg, "role">[] = [];
  for (const line0 of raw.replace(/\r/g, "").split("\n")) {
    const line = line0.replace(/[\u200e\u200f\u202a-\u202e]/g, "");
    const m = LINE.exec(line);
    if (m) {
      const rest = m[8];
      const i = rest.indexOf(": ");
      if (i < 1 || i > 80) continue; // pesan sistem (enkripsi, bergabung, dll)
      const ts = toIso(m);
      if (!ts) continue;
      out.push({ ts, sender: rest.slice(0, i).trim(), text: rest.slice(i + 2) });
    } else if (out.length && line.trim()) {
      out[out.length - 1].text += "\n" + line; // lanjutan pesan multi-baris
    }
  }
  // Pengirim pertama dianggap customer (customer yang mengirim prefilled message lebih dulu)
  const customer = out[0]?.sender;
  return out
    .map((x) => {
      const t = x.text.trim();
      return { ...x, text: t.length < 60 && MEDIA.test(t) ? "[media]" : t, role: (x.sender === customer ? "customer" : "cs") as Msg["role"] };
    })
    .filter((x) => x.text);
}

// Kode Ref dari prefilled message, mis. "Ref: A7K2X"
export function extractRef(msgs: Msg[]): string | null {
  for (const m of msgs.slice(0, 5)) {
    if (m.role !== "customer") continue;
    const r = /ref\s*[:=]?\s*([A-Za-z2-9]{5})\b/i.exec(m.text);
    if (r) return r[1].toUpperCase();
  }
  return null;
}

// Hasil: 62812xxxx (tanpa +), atau null kalau bukan nomor telepon
export function normalizePhone(raw: string): string | null {
  let d = raw.replace(/\D/g, "");
  if (d.startsWith("0")) d = "62" + d.slice(1);
  else if (d.startsWith("8")) d = "62" + d;
  return d.length >= 9 && d.length <= 15 ? d : null;
}

export const sha256 = (v: string) => createHash("sha256").update(v).digest("hex");
