/**
 * Decode a DXF buffer to text.
 *
 * Modern CAD exports are UTF-8 but often keep a legacy $DWGCODEPAGE
 * (e.g. ANSI_949) that no longer matches the bytes — so the header is
 * unreliable. Strategy: try UTF-8 strictly (self-validating); on failure
 * fall back to the header's single-byte codepage. The DXF group/value
 * structure is ASCII regardless, so this only affects TEXT/MTEXT strings.
 */
export function decodeDxf(buf: ArrayBuffer): string {
  try {
    return new TextDecoder('utf-8', { fatal: true }).decode(buf);
  } catch {
    /* not valid UTF-8 → legacy single-byte codepage */
  }
  const head = new TextDecoder('latin1').decode(
    new Uint8Array(buf, 0, Math.min(buf.byteLength, 4096)),
  );
  const cp = head
    .match(/\$DWGCODEPAGE[\s\S]*?\n\s*3\s*\n\s*([^\r\n]+)/i)?.[1]
    ?.trim()
    .toLowerCase();
  let label = 'windows-1252';
  if (cp) {
    if (/949/.test(cp)) label = 'euc-kr';
    else if (/932/.test(cp)) label = 'shift_jis';
    else if (/936/.test(cp)) label = 'gbk';
    else if (/950/.test(cp)) label = 'big5';
  }
  try {
    return new TextDecoder(label).decode(buf);
  } catch {
    return new TextDecoder('utf-8').decode(buf);
  }
}
