// ExcelJS → G60Workbook bridge (KAR-840 G60 stage G2). Server-only: ExcelJS
// is imported dynamically (kept out of client bundles), matching the existing
// workbook-adapter. Read-only; formula cells resolve to their cached result.

import type { Workbook } from 'exceljs'
import { resolveCell } from '../workbook-adapter'
import type { CellGetter, G60Workbook } from './parser'

function sheetGetter(wb: Workbook, name: string): CellGetter | null {
  const ws = wb.getWorksheet(name)
  if (!ws) return null
  return (addr: string) => resolveCell(ws.getCell(addr))
}

/** Wrap a loaded ExcelJS workbook as the pure G60Workbook interface. */
export function g60WorkbookFromExcelJs(wb: Workbook): G60Workbook {
  return {
    sheetNames: wb.worksheets.map((ws) => ws.name),
    sheet: (name) => sheetGetter(wb, name),
  }
}

/** Load an .xlsx buffer and expose it as a G60Workbook. */
export async function g60WorkbookFromBuffer(buffer: Buffer | ArrayBuffer): Promise<G60Workbook> {
  const ExcelJS = (await import('exceljs')).default
  const wb = new ExcelJS.Workbook()
  await wb.xlsx.load(buffer as unknown as ArrayBuffer)
  return g60WorkbookFromExcelJs(wb)
}
