import assert from 'node:assert/strict'
import test from 'node:test'
import { createPlot } from '../src/facade/plot'

test('Plot updates bound Spreadsheet series and exports deterministic SVG/CSV', () => {
  const plot = createPlot('plot', 'Length history')
  plot.setAxes({ x: { label: 'Revision', scale: 'linear', minimum: 0, maximum: 2 }, y: { label: 'Length (mm)', scale: 'linear', minimum: 0, maximum: 20 } })
  plot.setSeries({ id: 'length', label: 'Length', points: [{ x: 0, y: 6 }, { x: 1, y: 12 }], style: { color: '#007f86', lineWidth: 2 } })
  plot.bindSeries('length', { sourceId: 'Spreadsheet', xRange: 'A1:A3', yRange: 'B1:B3' })
  plot.updateBoundSeries('length', [{ x: 0, y: 6 }, { x: 1, y: 12 }, { x: 2, y: 16 }])
  assert.equal(plot.snapshot().series[0].points[2].y, 16)
  assert.match(plot.exportSvg(), /data-series="length"/)
  assert.match(plot.exportSvg(), /Length \(mm\)/)
  assert.equal(plot.exportCsv().split('\n').length, 4)
})

test('Plot validates series, axes, bindings and output dimensions', () => {
  const plot = createPlot()
  assert.throws(() => plot.setAxes({ x: { label: 'X', scale: 'linear', minimum: 2, maximum: 1 }, y: { label: 'Y', scale: 'linear' } }), /less than maximum/)
  assert.throws(() => plot.setSeries({ id: 'bad', label: 'Bad', points: [{ x: 0, y: 0 }], style: { color: '#000000', lineWidth: 1 } }), /at least two/)
  plot.setSeries({ id: 'good', label: 'Good', points: [{ x: 0, y: 0 }, { x: 1, y: 1 }], style: { color: '#007f86', lineWidth: 1, dash: [4, 2] } })
  assert.throws(() => plot.updateBoundSeries('good', [{ x: 0, y: 0 }, { x: 1, y: 1 }]), /not bound/)
  assert.throws(() => plot.exportSvg(100, 100), /outside the supported range/)
})

test('Plot supports positive logarithmic axes with deterministic log-space SVG mapping', () => {
  const plot = createPlot('log-plot', 'Log history')
  plot.setAxes({ x: { label: 'X', scale: 'log', minimum: 1, maximum: 100 }, y: { label: 'Y', scale: 'log', minimum: 1, maximum: 1000 } })
  plot.setSeries({ id: 'log', label: 'Log', points: [{ x: 1, y: 1 }, { x: 10, y: 10 }, { x: 100, y: 1000 }], style: { color: '#007f86', lineWidth: 1 } })
  const svg = plot.exportSvg()
  assert.match(svg, /data-x-scale="log" data-y-scale="log"/)
  assert.match(svg, /M56\.000 312\.000/)
  assert.throws(() => plot.setSeries({ id: 'bad-log', label: 'Bad', points: [{ x: 0, y: 1 }, { x: 1, y: 2 }], style: { color: '#000000', lineWidth: 1 } }), /positive series values/)
  assert.throws(() => plot.setAxes({ x: { label: 'X', scale: 'log', minimum: 0, maximum: 10 }, y: { label: 'Y', scale: 'linear' } }), /bounds must be greater than zero/)
})
