import assert from 'node:assert/strict';
import { ImportError, MAX_INTERVALS, MAX_FILE_BYTES, parseCsv, inspectNem12, parseNem12 } from '../../public/tools/battery-quote-check/importer.mjs';

// Synthetic values in the official record structures from AEMO MDFF v2.7,
// sections 4.2–4.7. These are not customer data or a claimed AEMO test fixture.
// https://www.aemo.com.au/-/media/files/electricity/nem/retail_and_metering/market_settlement_and_transfer_solutions/2025/mdff-specification-nem12-nem13-v27.pdf
const HEAD = 'start,durationMinutes,importKwh,exportKwh';
const csv = (...lines) => [HEAD, ...lines].join('\n');
const HEADER = '100,NEM12,202601031234,MDP1,RETAILER1';
const nmi = 'VABD000163';
function channel(suffix, { site = nmi, configuration = 'E1B1', unit = 'kWh', minutes = 30, meter = 'METSER123' } = {}) {
  return `200,${site},${configuration},${suffix},${suffix},N1,${meter},${unit},${minutes},20260401`;
}
function day({ date = '20260101', minutes = 30, value = '0.1', values, quality = 'A', reason = '', description = '', update = '20260103003000', loaded = '' } = {}) {
  return ['300', date, ...(values || Array(1440 / minutes).fill(value)), quality, reason, description, update, loaded].join(',');
}
const nem = (...records) => [HEADER, ...records, '900'].join('\r\n') + '\r\n';
const fixture = nem(channel('E1'), day(), channel('B1'), day({ value: '0.2' }));
const opts = { importChannel: 'channel-1', exportChannel: 'channel-2', timeZoneOffsetMinutes: 600 };
let checks = 0;
function test(name, run) {
  try { run(); checks++; }
  catch (error) { error.message = `${name}: ${error.message}`; throw error; }
}
function rejects(name, run, code) {
  test(name, () => assert.throws(run, error => error instanceof ImportError && error.code === code));
}

test('CSV exact decimals and simultaneous gross directions survive unchanged', () => {
  const result = parseCsv(csv('2026-01-01T00:00:00+10:00,30,001.2300,2.4000', '2026-01-01T00:30:00+10:00,30,0.000000000000000000000001,0'));
  assert.deepEqual(result.intervals[0], { start: '2025-12-31T14:00:00.000Z', durationMinutes: 30, importKwh: '1.23', exportKwh: '2.4' });
  assert.equal(result.intervals[1].importKwh, '0.000000000000000000000001');
  assert.equal(result.metadata.end, '2025-12-31T15:00:00.000Z');
  assert.deepEqual(result.warnings, []);
});
test('CSV quoted canonical fields, BOM, CRLF, reordered columns and final newline', () => {
  const result = parseCsv('\ufeff"exportKwh","durationMinutes","importKwh","start"\r\n".5","15","+1.","2024-02-29T12:00Z"\r\n');
  assert.deepEqual(result.intervals[0], { start: '2024-02-29T12:00:00.000Z', durationMinutes: 15, importKwh: '1', exportKwh: '0.5' });
});
test('CSV both per-interval rates permit negative prices', () => {
  const result = parseCsv(`${HEAD},buyRate,feedInRate\n2026-01-01T00:00Z,60,1,2,-.40,+.0500`);
  assert.equal(result.intervals[0].buyRate, '-0.4'); assert.equal(result.intervals[0].feedInRate, '0.05');
});
test('CSV explicit fixed offset and signed zero', () => {
  const result = parseCsv(csv('2026-01-01T00:00,5,-0,-0.000'), { timeZoneOffsetMinutes: -210 });
  assert.equal(result.intervals[0].start, '2026-01-01T03:30:00.000Z');
  assert.equal(result.intervals[0].importKwh, '0'); assert.equal(result.metadata.timeZoneOffsetMinutes, -210);
});
test('DST repeated wall clock is accepted only because explicit offsets establish continuity', () => {
  const result = parseCsv(csv('2026-04-05T02:30+11:00,30,1,0', '2026-04-05T02:00+10:00,30,1,0'));
  assert.equal(result.intervals[1].start, '2026-04-04T16:00:00.000Z');
});
test('DST skipped wall hour is accepted with continuous offset-aware time', () => {
  assert.equal(parseCsv(csv('2026-10-04T01:30+10:00,30,1,0', '2026-10-04T03:00+11:00,30,1,0')).intervals.length, 2);
});
test('Mixed supported durations must remain continuous', () => {
  assert.equal(parseCsv(csv('2026-01-01T00:00Z,5,1,0', '2026-01-01T00:05Z,15,1,0', '2026-01-01T00:20Z,60,1,0')).intervals.length, 3);
});

for (const [name, input, code] of [
  ['missing energy column', 'start,durationMinutes,importKwh\n2026-01-01T00:00Z,30,1', 'MISSING_COLUMN'],
  ['duplicate header', `${HEAD},importKwh`, 'DUPLICATE_COLUMN'],
  ['unrecognised header', `${HEAD},netKwh`, 'UNKNOWN_COLUMN'],
  ['escaped quote is parsed then rejected as unknown header', '"sta""rt",durationMinutes,importKwh,exportKwh', 'UNKNOWN_COLUMN'],
  ['embedded quoted newline is parsed then rejected as timestamp', csv('"2026-01-01\nT00:00Z",30,1,0'), 'INVALID_TIMESTAMP'],
  ['quoted comma is one field and cannot become a number', csv('2026-01-01T00:00Z,30,"1,000",0'), 'INVALID_NUMBER'],
  ['unclosed quoted field', csv('"2026-01-01T00:00Z,30,1,0'), 'CSV_QUOTING'],
  ['quote in unquoted field', csv('2026-01-01T00:00Z,30,1"2,0'), 'CSV_QUOTING'],
  ['text after closing quote', csv('"2026-01-01T00:00Z"junk,30,1,0'), 'CSV_QUOTING'],
  ['extra field', csv('2026-01-01T00:00Z,30,1,0,0'), 'COLUMN_COUNT'],
  ['missing field', csv('2026-01-01T00:00Z,30,1'), 'COLUMN_COUNT'],
  ['blank row is not silently skipped', `${HEAD}\n\n`, 'COLUMN_COUNT'],
  ['header only', HEAD, 'NO_INTERVALS'],
  ['empty file', '', 'EMPTY_FILE'],
  ['NUL byte', `${HEAD}\0`, 'INVALID_TEXT'],
  ['negative gross import', csv('2026-01-01T00:00Z,30,-1,0'), 'NEGATIVE_ENERGY'],
  ['negative gross export', csv('2026-01-01T00:00Z,30,1,-2'), 'NEGATIVE_ENERGY'],
  ['blank energy', csv('2026-01-01T00:00Z,30,,0'), 'INVALID_NUMBER'],
  ['NaN', csv('2026-01-01T00:00Z,30,NaN,0'), 'INVALID_NUMBER'],
  ['infinity', csv('2026-01-01T00:00Z,30,Infinity,0'), 'INVALID_NUMBER'],
  ['exponent notation', csv('2026-01-01T00:00Z,30,1e3,0'), 'INVALID_NUMBER'],
  ['huge decimal token', csv(`2026-01-01T00:00Z,30,${'9'.repeat(49)},0`), 'INVALID_NUMBER'],
  ['zero duration', csv('2026-01-01T00:00Z,0,1,0'), 'INVALID_DURATION'],
  ['unsupported duration', csv('2026-01-01T00:00Z,10,1,0'), 'INVALID_DURATION'],
  ['fractional duration', csv('2026-01-01T00:00Z,30.0,1,0'), 'INVALID_DURATION'],
  ['missing timezone', csv('2026-01-01T00:00,30,1,0'), 'TIMEZONE_REQUIRED'],
  ['ambiguous date format', csv('01/02/2026 00:00,30,1,0'), 'INVALID_TIMESTAMP'],
  ['non-leap February', csv('2026-02-29T00:00Z,30,1,0'), 'INVALID_TIMESTAMP'],
  ['impossible April day', csv('2026-04-31T00:00Z,30,1,0'), 'INVALID_TIMESTAMP'],
  ['24:00 date normalisation', csv('2026-01-01T24:00Z,30,1,0'), 'INVALID_TIMESTAMP'],
  ['seconds offset', csv('2026-01-01T00:00:01Z,30,1,0'), 'TIMESTAMP_ALIGNMENT'],
  ['fractional second', csv('2026-01-01T00:00:00.1Z,30,1,0'), 'TIMESTAMP_ALIGNMENT'],
  ['impossible offset minutes', csv('2026-01-01T00:00+10:60,30,1,0'), 'INVALID_TIMEZONE'],
  ['out-of-range offset', csv('2026-01-01T00:00+14:01,30,1,0'), 'INVALID_TIMEZONE'],
  ['unknown RFC3339 offset', csv('2026-01-01T00:00-00:00,30,1,0'), 'INVALID_TIMEZONE'],
  ['missing interval', csv('2026-01-01T00:00Z,30,1,0', '2026-01-01T01:00Z,30,1,0'), 'INTERVAL_GAP'],
  ['duplicate interval', csv('2026-01-01T00:00Z,30,1,0', '2026-01-01T00:00Z,30,1,0'), 'INTERVAL_OVERLAP'],
  ['overlapping interval', csv('2026-01-01T00:00Z,30,1,0', '2026-01-01T00:15Z,30,1,0'), 'INTERVAL_OVERLAP'],
  ['unordered interval', csv('2026-01-01T00:30Z,30,1,0', '2026-01-01T00:00Z,30,1,0'), 'INTERVAL_OVERLAP'],
  ['only one rate column', `${HEAD},buyRate\n2026-01-01T00:00Z,30,1,0,.4`, 'MISSING_TARIFF_COLUMN'],
  ['blank per-interval rate', `${HEAD},buyRate,feedInRate\n2026-01-01T00:00Z,30,1,0,.4,`, 'INVALID_NUMBER'],
]) rejects(name, () => parseCsv(input), code);
for (const bad of [NaN, Infinity, 840.1, 841, -841, '600']) rejects(`invalid fixed offset ${bad}`, () => parseCsv(csv('2026-01-01T00:00,30,1,0'), { timeZoneOffsetMinutes: bad }), 'INVALID_TIMEZONE');

test('NEM12 direction, midnight start, full day and exact decimal mapping', () => {
  const info = inspectNem12(fixture);
  assert.deepEqual(info.channels.map(c => [c.id, c.direction, c.quality]), [['channel-1', 'import', 'actual'], ['channel-2', 'export', 'actual']]);
  const result = parseNem12(fixture, opts);
  assert.equal(result.intervals.length, 48);
  assert.deepEqual(result.intervals[0], { start: '2025-12-31T14:00:00.000Z', durationMinutes: 30, importKwh: '0.1', exportKwh: '0.2' });
  assert.equal(result.intervals[47].start, '2026-01-01T13:30:00.000Z');
  assert.equal(result.metadata.end, '2026-01-01T14:00:00.000Z');
  for (const privateValue of [nmi, 'METSER123', 'MDP1', 'RETAILER1']) {
    assert.ok(!JSON.stringify(info).includes(privateValue)); assert.ok(!JSON.stringify(result).includes(privateValue));
  }
});
test('NEM12 reversed file channel order still uses explicit selections', () => {
  const reversed = nem(channel('B1'), day({ value: '2' }), channel('E1'), day({ value: '1' }));
  const result = parseNem12(reversed, { ...opts, importChannel: 'channel-2', exportChannel: 'channel-1' });
  assert.equal(result.intervals[0].importKwh, '1'); assert.equal(result.intervals[0].exportKwh, '2');
});
test('NEM12 exactly repeated 200 identities can extend ordered days', () => {
  const result = parseNem12(nem(channel('E1'), day(), channel('B1'), day(), channel('E1'), day({ date: '20260102' }), channel('B1'), day({ date: '20260102' })), opts);
  assert.equal(result.intervals.length, 96);
});
for (const minutes of [5, 15, 30]) test(`NEM12 ${minutes}-minute fields and day edge`, () => {
  const input = nem(channel('E1', { minutes }), day({ minutes }), channel('B1', { minutes }), day({ minutes }));
  const result = parseNem12(input, { ...opts, timeZoneOffsetMinutes: 0 });
  assert.equal(result.intervals.length, 1440 / minutes); assert.equal(result.metadata.end, '2026-01-02T00:00:00.000Z');
});
test('NEM12 400 all-actual segments cover entire day', () => {
  const input = nem(channel('E1'), day({ quality: 'V' }), '400,1,20,A,,', '400,21,48,A,,', channel('B1'), day());
  assert.equal(parseNem12(input, opts).intervals.length, 48);
});
test('NEM12 500 index reads validated and explicitly excluded from interval totals', () => {
  const input = nem(channel('E1'), day(), '500,S,RETNSRVCEORD1,20260101154500,001123.5', channel('B1'), day());
  const result = parseNem12(input, opts);
  assert.equal(result.intervals[0].importKwh, '0.1'); assert.match(result.warnings[0], /index reads are not added/);
});
test('NEM12 non-energy channel is validated and its exclusion reported', () => {
  const ch = suffix => channel(suffix, { configuration: 'E1B1Q1', ...(suffix === 'Q1' ? { unit: 'kVArh' } : {}) });
  const result = parseNem12(nem(ch('E1'), day(), ch('B1'), day(), ch('Q1'), day()), opts);
  assert.match(result.warnings[0], /Q1/);
});
for (const quality of ['S14', 'E52', 'F14']) test(`NEM12 ${quality} is exposed at inspection and refused at comparison`, () => {
  const input = nem(channel('E1'), day({ quality, reason: quality[0] === 'E' ? '' : '32' }), channel('B1'), day());
  assert.equal(inspectNem12(input).channels[0].quality, 'rejected');
  assert.throws(() => parseNem12(input, opts), e => e.code === 'NEM12_NON_ACTUAL');
});

const eventFile = (...events) => nem(channel('E1'), day({ quality: 'V' }), ...events, channel('B1'), day());
for (const [name, input, code] of [
  ['not NEM12', fixture.replace('NEM12', 'NEM13'), 'NEM12_HEADER'],
  ['repeated header', `${HEADER}\n${fixture}`, 'NEM12_HEADER'],
  ['no header', fixture.slice(fixture.indexOf('\n') + 1), 'NEM12_HEADER'],
  ['no final record', fixture.replace('900\r\n', ''), 'NEM12_END'],
  ['data after end', `${fixture}900`, 'NEM12_RECORD_ORDER'],
  ['extra 900 field', fixture.replace('900\r\n', '900,\r\n'), 'NEM12_COLUMN_COUNT'],
  ['unknown record', nem(channel('E1'), day(), '450,1,2', channel('B1'), day()), 'NEM12_UNKNOWN_RECORD'],
  ['300 without channel', nem(day()), 'NEM12_RECORD_ORDER'],
  ['500 without day', nem(channel('E1'), '500,S,,20260101120000,'), 'NEM12_RECORD_ORDER'],
  ['empty 200 block', nem(channel('E1'), channel('B1'), day()), 'NEM12_EMPTY_CHANNEL'],
  ['missing daily energy value', nem(channel('E1'), day({ values: Array(47).fill('1') }), channel('B1'), day()), 'NEM12_COLUMN_COUNT'],
  ['extra daily energy value', nem(channel('E1'), day({ values: Array(49).fill('1') }), channel('B1'), day()), 'NEM12_COLUMN_COUNT'],
  ['blank interval value', nem(channel('E1'), day({ values: ['', ...Array(47).fill('1')] }), channel('B1'), day()), 'INVALID_NUMBER'],
  ['negative interval value', nem(channel('E1'), day({ value: '-0.1' }), channel('B1'), day()), 'NEGATIVE_ENERGY'],
  ['unknown unit', fixture.replaceAll('kWh', 'kWhish'), 'NEM12_UNIT'],
  ['unsupported sixty-minute NEM12', fixture.replaceAll(',kWh,30,', ',kWh,60,'), 'INVALID_DURATION'],
  ['invalid compact date', fixture.replaceAll(',20260101,', ',20260230,'), 'INVALID_TIMESTAMP'],
  ['invalid compact update time', fixture.replaceAll('20260103003000', '20260103253000'), 'INVALID_TIMESTAMP'],
  ['configuration omits suffix', fixture.replaceAll(',E1B1,', ',E1Q1,'), 'NEM12_CONFIGURATION'],
  ['configuration declared channel missing', nem(channel('E1'), day()), 'NEM12_MISSING_CHANNEL'],
  ['duplicate configured suffix', fixture.replaceAll(',E1B1,', ',E1E1B1,'), 'NEM12_CONFIGURATION'],
  ['invalid NMI', fixture.replaceAll(nmi, '12345678901'), 'NEM12_SITE'],
  ['surrounding NEM whitespace', fixture.replace(',kWh,', ', kWh,'), 'NEM12_FIELD'],
  ['quoted comma in NEM field', fixture.replace('METSER123', '"METER,123"'), 'NEM12_FIELD'],
  ['missing quality', nem(channel('E1'), day({ quality: '' }), channel('B1'), day()), 'NEM12_QUALITY'],
  ['unknown quality', nem(channel('E1'), day({ quality: 'M' }), channel('B1'), day()), 'NEM12_QUALITY'],
  ['missing estimate method', nem(channel('E1'), day({ quality: 'E' }), channel('B1'), day()), 'NEM12_QUALITY'],
  ['substitute has no reason', nem(channel('E1'), day({ quality: 'S14' }), channel('B1'), day()), 'NEM12_REASON'],
  ['zero reason has no description', nem(channel('E1'), day({ reason: '0' }), channel('B1'), day()), 'NEM12_REASON'],
  ['event records missing', eventFile(), 'NEM12_EVENT_COVERAGE'],
  ['event interval gap', eventFile('400,1,20,A,,', '400,22,48,A,,'), 'NEM12_EVENT_COVERAGE'],
  ['event interval overlap', eventFile('400,1,20,A,,', '400,20,48,A,,'), 'NEM12_EVENT_COVERAGE'],
  ['event incomplete day', eventFile('400,1,47,A,,'), 'NEM12_EVENT_COVERAGE'],
  ['event range past day', eventFile('400,1,49,A,,'), 'NEM12_EVENT_COVERAGE'],
  ['event reversed range', eventFile('400,1,0,A,,'), 'NEM12_EVENT_COVERAGE'],
  ['event cannot be variable', eventFile('400,1,48,V,,'), 'NEM12_QUALITY'],
  ['400 cannot follow actual day', nem(channel('E1'), day(), '400,1,48,A,,', channel('B1'), day()), 'NEM12_RECORD_ORDER'],
  ['event after 500 forbidden', eventFile('400,1,48,A,,', '500,S,,20260101120000,', '400,1,48,A,,'), 'NEM12_RECORD_ORDER'],
  ['unknown B2B transaction', nem(channel('E1'), day(), '500,X,,20260101120000,', channel('B1'), day()), 'NEM12_TRANSACTION'],
  ['invalid B2B index', nem(channel('E1'), day(), '500,S,,20260101120000,NaN', channel('B1'), day()), 'INVALID_NUMBER'],
  ['gapped daily readings', nem(channel('E1'), day(), day({ date: '20260103' }), channel('B1'), day()), 'INTERVAL_GAP'],
  ['duplicate daily readings', nem(channel('E1'), day(), day(), channel('B1'), day()), 'INTERVAL_OVERLAP'],
  ['unordered daily readings', nem(channel('E1'), day({ date: '20260102' }), day(), channel('B1'), day()), 'INTERVAL_OVERLAP'],
  ['meter changes within channel', nem(channel('E1'), day(), channel('E1', { meter: 'NEWMETER' }), day({ date: '20260102' }), channel('B1'), day()), 'NEM12_CHANNEL_CHANGE'],
]) rejects(name, () => inspectNem12(input), code);

for (const [name, input, options, code] of [
  ['explicit channel selection required', fixture, { timeZoneOffsetMinutes: 600 }, 'CHANNEL_SELECTION_REQUIRED'],
  ['fixed NEM12 offset required', fixture, { importChannel: 'channel-1', exportChannel: 'channel-2' }, 'TIMEZONE_REQUIRED'],
  ['unknown selection', fixture, { ...opts, importChannel: 'channel-999' }, 'NEM12_CHANNEL_SELECTION'],
  ['channel reversal refused', fixture, { ...opts, importChannel: 'channel-2', exportChannel: 'channel-1' }, 'NEM12_CHANNEL_DIRECTION'],
  ['mixed units refused', fixture.replaceAll('kWh', 'Wh'), opts, 'NEM12_ENERGY_UNIT'],
  ['different periods refused', nem(channel('E1'), day(), channel('B1'), day({ date: '20260102' })), opts, 'NEM12_SERIES_MISMATCH'],
  ['different durations refused', nem(channel('E1'), day(), channel('B1', { minutes: 15 }), day({ minutes: 15 })), opts, 'NEM12_SERIES_MISMATCH'],
  ['actual outage event refused', nem(channel('E1'), day({ reason: '79' }), channel('B1'), day()), opts, 'NEM12_NON_ACTUAL'],
  ['actual time-reset event refused', eventFile('400,1,20,A,,', '400,21,48,A,89,'), opts, 'NEM12_NON_ACTUAL'],
  ['part-day substitution refused', eventFile('400,1,20,A,,', '400,21,48,S14,32,'), opts, 'NEM12_NON_ACTUAL'],
  ['B2B estimate refused', nem(channel('E1'), day(), '500,E,,,', channel('B1'), day()), opts, 'NEM12_NON_ACTUAL'],
  ['extra energy register cannot be silently omitted', nem(channel('E1', { configuration: 'E1B1E2' }), day(), channel('B1', { configuration: 'E1B1E2' }), day(), channel('E2', { configuration: 'E1B1E2' }), day()), opts, 'NEM12_MULTIPLE_ENERGY_CHANNELS'],
  ['two sites cannot be mixed', nem(channel('E1'), day(), channel('B1'), day(), channel('E1', { site: 'VABD000164' }), day(), channel('B1', { site: 'VABD000164' }), day()), opts, 'NEM12_MULTIPLE_SITES'],
]) rejects(name, () => parseNem12(input, options), code);

rejects('byte limit checks UTF-8 bytes rather than only string length', () => parseCsv('é'.repeat(MAX_FILE_BYTES / 2 + 1)), 'FILE_TOO_LARGE');
rejects('ASCII byte limit', () => parseCsv('a'.repeat(MAX_FILE_BYTES + 1)), 'FILE_TOO_LARGE');
test('110000 rows accepted; the 110001st is refused without truncation', () => {
  const start = Date.UTC(2025, 0, 1);
  const lines = Array.from({ length: MAX_INTERVALS }, (_, i) => `${new Date(start + i * 5 * 60000).toISOString()},5,0.1,0.2`);
  const text = [HEAD, ...lines].join('\n');
  assert.equal(parseCsv(text).intervals.length, MAX_INTERVALS);
  const next = `${new Date(start + MAX_INTERVALS * 5 * 60000).toISOString()},5,0.1,0.2`;
  assert.throws(() => parseCsv(`${text}\n${next}`), e => e.code === 'TOO_MANY_INTERVALS');
});
test('Full year of five-minute NEM12 remains contiguous and below local limit', () => {
  const dates = Array.from({ length: 365 }, (_, i) => new Date(Date.UTC(2025, 0, 1) + i * 86400000).toISOString().slice(0, 10).replaceAll('-', ''));
  const input = nem(channel('E1', { minutes: 5 }), ...dates.map(date => day({ date, minutes: 5, value: '0.0123' })), channel('B1', { minutes: 5 }), ...dates.map(date => day({ date, minutes: 5, value: '0.0234' })));
  const result = parseNem12(input, { ...opts, timeZoneOffsetMinutes: 0 });
  assert.equal(result.intervals.length, 105120); assert.equal(result.metadata.start, '2025-01-01T00:00:00.000Z'); assert.equal(result.metadata.end, '2026-01-01T00:00:00.000Z');
  assert.equal(result.intervals.at(-1).exportKwh, '0.0234');
});

console.log(`Battery Quote Check importer: ${checks} checks passed, including 110000-row CSV and full-year five-minute NEM12.`);
