function split(line) {
  return line.split('|');
}

function extractTestCode(raw) {
  const candidates = (raw || '').split('^').filter(Boolean);
  return candidates[0] || raw || 'UNKNOWN';
}

function buildResult(fields) {
  return {
    test_code: extractTestCode(fields[2]),
    value: fields[3] || '0',
    unit: fields[4] || undefined,
    flag: fields[11] || fields[10] || undefined,
    meta: {
      channel: fields[1]
    }
  };
}

function parseAstm(message) {
  const payload = typeof message === 'string' ? message.trim() : '';
  if (!payload) throw new Error('empty ASTM payload');
  const lines = payload.split(/\r?\n/).filter(Boolean);
  const header = lines.find((line) => line.startsWith('H|')) || '';
  const order = lines.find((line) => line.startsWith('O|')) || '';
  const resultLines = lines.filter((line) => line.startsWith('R|'));

  if (!resultLines.length) {
    throw new Error('no ASTM R segments');
  }

  const headerFields = header ? split(header) : [];
  const orderFields = order ? split(order) : [];
  const instrument_id = headerFields[3] || 'astm-instrument';
  const sample_id = orderFields[2] || `${instrument_id}-sample`;
  const result_time = orderFields[13] || new Date().toISOString();

  const results = resultLines.map((line) => buildResult(split(line)));

  return {
    instrument_id: instrument_id.trim(),
    sample_id: sample_id.trim(),
    result_time,
    results,
    meta: {
      source_protocol: 'ASTM',
      connector: 'astm-serial',
      segments: resultLines.length
    }
  };
}

module.exports = { parse: parseAstm };
