import { inflateRawSync } from 'node:zlib';

/**
 * Every sheet of an .xlsx workbook, its cells as text, row by row — with no
 * library. The server's counterpart of the back office's read-xlsx, which
 * leans on the browser's DOMParser and DecompressionStream: here the zip is
 * walked by hand, its parts inflated with zlib, and the XML read with patterns,
 * which is all the regular XML a spreadsheet writes needs.
 *
 * Text is as stored: a number reads as Excel wrote it ("65000", "46843" for a
 * date cell), a formula as its last computed value.
 */
export interface XlsxReadSheet {
  name: string;
  rows: string[][];
}

export function readXlsxSheets(bytes: Uint8Array): XlsxReadSheet[] {
  const parts = zipEntries(bytes);
  const text = (name: string): string | null => {
    const entry = parts.get(name);
    return entry ? new TextDecoder().decode(unpack(bytes, entry)) : null;
  };

  const shared = [...(text('xl/sharedStrings.xml') ?? '').matchAll(/<si>([\s\S]*?)<\/si>/g)].map((m) =>
    // Rich text is split into runs; phonetic guides (rPh) are not the text.
    [...m[1].replace(/<rPh[\s\S]*?<\/rPh>/g, '').matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g)].map((t) => xmlText(t[1])).join(''),
  );

  const workbook = text('xl/workbook.xml');
  const rels = text('xl/_rels/workbook.xml.rels');
  if (!workbook || !rels) throw new Error('Not an Excel workbook');
  const targets = new Map(
    [...rels.matchAll(/<Relationship\b[^>]*>/g)].map((m) => [attr(m[0], 'Id'), attr(m[0], 'Target')] as const),
  );

  return [...workbook.matchAll(/<sheet\b[^>]*>/g)].map((m) => {
    const target = targets.get(attr(m[0], 'r:id')) ?? '';
    const xml = text(target.startsWith('/') ? target.slice(1) : `xl/${target}`) ?? '';
    return { name: xmlText(attr(m[0], 'name')), rows: sheetRows(xml, shared) };
  });
}

function sheetRows(xml: string, shared: readonly string[]): string[][] {
  const rows: string[][] = [];
  for (const row of xml.matchAll(/<row\b([^>]*?)(?:\/>|>([\s\S]*?)<\/row>)/g)) {
    // A row says which it is; rows Excel had nothing in are simply not there.
    const at = Number(attr(row[1], 'r')) - 1;
    const index = Number.isInteger(at) && at >= 0 ? at : rows.length;
    const cells: string[] = [];
    for (const c of (row[2] ?? '').matchAll(/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)) {
      const head = c[1];
      const body = c[2] ?? '';
      const type = attr(head, 't');
      const v = /<v>([\s\S]*?)<\/v>/.exec(body)?.[1];
      const value =
        type === 's' ? shared[Number(v)] ?? ''
        : type === 'inlineStr' ? [...body.matchAll(/<t(?:\s[^>]*)?>([\s\S]*?)<\/t>/g)].map((t) => xmlText(t[1])).join('')
        : v === undefined ? ''
        : xmlText(v);
      cells[columnIndex(attr(head, 'r'), cells.length)] = value;
    }
    rows[index] = Array.from(cells, (x) => x ?? '');
  }
  return Array.from(rows, (r) => r ?? []);
}

/** An attribute's raw value from a start tag, or ''. */
function attr(tag: string, name: string): string {
  return new RegExp(`\\s${name.replace(':', '\\:')}="([^"]*)"`).exec(tag)?.[1] ?? '';
}

function xmlText(s: string): string {
  return s.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g, (_, e: string) =>
    e === 'amp' ? '&'
    : e === 'lt' ? '<'
    : e === 'gt' ? '>'
    : e === 'quot' ? '"'
    : e === 'apos' ? "'"
    : String.fromCodePoint(e[1] === 'x' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10)),
  );
}

/** "C12" → 2; a cell without a reference is the next one along. */
function columnIndex(ref: string, next: number): number {
  const letters = /^[A-Z]+/.exec(ref)?.[0];
  if (!letters) return next;
  return [...letters].reduce((n, ch) => n * 26 + ch.charCodeAt(0) - 64, 0) - 1;
}

// ── zip ────────────────────────────────────────────────────────────────────

interface ZipEntry {
  method: number;
  size: number;
  offset: number;
}

/** The archive's entries, from its central directory. */
function zipEntries(zip: Uint8Array): Map<string, ZipEntry> {
  const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
  let end = -1;
  for (let i = zip.length - 22; i >= Math.max(0, zip.length - 22 - 0xffff); i--) {
    if (view.getUint32(i, true) === 0x06054b50) {
      end = i;
      break;
    }
  }
  if (end < 0) throw new Error('Not an Excel workbook');
  const count = view.getUint16(end + 10, true);
  let at = view.getUint32(end + 16, true);
  const out = new Map<string, ZipEntry>();
  for (let i = 0; i < count; i++) {
    if (view.getUint32(at, true) !== 0x02014b50) throw new Error('Not an Excel workbook');
    const method = view.getUint16(at + 10, true);
    const size = view.getUint32(at + 20, true);
    const nameLen = view.getUint16(at + 28, true);
    const extraLen = view.getUint16(at + 30, true);
    const commentLen = view.getUint16(at + 32, true);
    const offset = view.getUint32(at + 42, true);
    const name = new TextDecoder().decode(zip.subarray(at + 46, at + 46 + nameLen));
    out.set(name, { method, size, offset });
    at += 46 + nameLen + extraLen + commentLen;
  }
  return out;
}

function unpack(zip: Uint8Array, entry: ZipEntry): Uint8Array {
  const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
  const start = entry.offset + 30 + view.getUint16(entry.offset + 26, true) + view.getUint16(entry.offset + 28, true);
  const data = zip.subarray(start, start + entry.size);
  if (entry.method === 0) return data;
  if (entry.method === 8) return inflateRawSync(data);
  throw new Error('Unsupported compression in the workbook');
}
