import ExcelJS from "exceljs";
import { dmy } from "../../shared/dates.js";
import { DomainError } from "../http/errors.js";

export type Cell = string | number | null;
const DATE = /^\d{4}-\d{2}-\d{2}$/, TIME = /^\d{4}-\d{2}-\d{2}T[\d:.]+Z$/;
/** Dates leave the system as DD/MM/YYYY (with Addis Ababa time where there is one), in every file. */
export const showCell = (v: Cell): Cell => (typeof v !== "string" ? v : DATE.test(v) ? dmy(v) : TIME.test(v) ? dmy(new Date(Date.parse(v) + 3 * 3_600_000).toISOString().slice(0, 16).replace("T", " ")) : v);
/** A cell that starts with = + - @ could run as a formula in Excel; it is written as text. */
const csvCell = (raw: Cell) => { const v = showCell(raw), s = v === null ? "" : typeof v === "string" && /^[=+\-@\t\r]/.test(v) ? `'${v}` : String(v); return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; };
export const toCsv = (header: string[], rows: Cell[][]): string => `﻿${[header, ...rows].map((r) => r.map(csvCell).join(",")).join("\r\n")}\r\n`;
export async function toXlsx(sheet: string, header: string[], rows: Cell[][], textColumns: string[] = []): Promise<Buffer> {
  header = header.map((h) => String(showCell(h)));
  rows = rows.map((r) => r.map(showCell));
  const wb = new ExcelJS.Workbook(), ws = wb.addWorksheet(sheet.slice(0, 31), { views: [{ state: "frozen", ySplit: 1 }] });
  ws.columns = header.map((h, i) => ({ header: h, width: Math.min(40, Math.max(10, h.length + 2, ...rows.slice(0, 200).map((r) => String(r[i] ?? "").length + 2))), ...(textColumns.includes(h) ? { style: { numFmt: "@" } } : {}) }));
  ws.getRow(1).font = { bold: true };
  for (const r of rows) ws.addRow(r);
  return Buffer.from(await wb.xlsx.writeBuffer());
}
export function parseCsv(text: string): string[][] {
  const rows: string[][] = [];
  let row: string[] = [], cell = "", quoted = false;
  const s = text.replace(/^﻿/, "");
  for (let i = 0; i < s.length; i++) {
    const c = s[i]!;
    if (quoted) { if (c === '"' && s[i + 1] === '"') { cell += '"'; i++; } else if (c === '"') quoted = false; else cell += c; }
    else if (c === '"') quoted = true;
    else if (c === ",") { row.push(cell); cell = ""; }
    else if (c === "\n") { row.push(cell.replace(/\r$/, "")); rows.push(row); row = []; cell = ""; }
    else cell += c;
  }
  if (cell || row.length) { row.push(cell.replace(/\r$/, "")); rows.push(row); }
  return rows.filter((r) => r.some((x) => x.trim()));
}
const DAY = 86_400_000;
const cellText = (v: ExcelJS.CellValue): string => {
  if (v === null || v === undefined) return "";
  if (v instanceof Date) return new Date(Math.round(v.getTime() / DAY) * DAY).toISOString().slice(0, 10);
  if (typeof v === "object") return "richText" in v ? v.richText.map((t) => t.text).join("") : "result" in v ? cellText(v.result as ExcelJS.CellValue) : "text" in v ? String(v.text) : "";
  return String(v);
};
/** Reads CSV or XLSX into records. Header names are lower-cased with underscores. */
export async function readTable(name: string, data: Buffer, maxRows = 10_000): Promise<{ header: string[]; rows: Record<string, string>[] }> {
  let grid: string[][] = [];
  if (/\.xlsx$/i.test(name)) {
    const wb = new ExcelJS.Workbook();
    try { await wb.xlsx.load(data as unknown as ArrayBuffer); } catch { throw new DomainError(422, "FILE_UNREADABLE", "The Excel file could not be read."); }
    const ws = wb.worksheets[0];
    ws?.eachRow((r) => { const cells: string[] = []; for (let i = 1; i <= ws.columnCount; i++) cells.push(cellText(r.getCell(i).value)); grid.push(cells); });
  } else if (/\.csv$/i.test(name)) grid = parseCsv(data.toString("utf8"));
  else throw new DomainError(422, "FILE_TYPE", "Use the CSV or Excel (.xlsx) template.");
  grid = grid.filter((r) => r.some((c) => c.trim()));
  if (!grid.length) throw new DomainError(422, "FILE_EMPTY", "The file has no rows.");
  if (grid.length - 1 > maxRows) throw new DomainError(422, "FILE_TOO_LONG", `The file has more than ${maxRows} rows. Split it and upload the parts.`);
  const header = grid[0]!.map((h) => h.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_|_$/g, ""));
  return { header, rows: grid.slice(1).map((r) => Object.fromEntries(header.map((h, i) => [h, (r[i] ?? "").trim().replace(/^'(?=[=+\-@])/, "").replace(/^="(.*)"$/, "$1")]))) };
}
