import { test } from 'node:test'
import assert from 'node:assert/strict'
import { unzipSync } from 'fflate'
import { createWebCadFacade } from '../src/facade/mockFacade'
import { decodeFcstdPropertyValue, serializeFcstdMetadataArchive } from '../src/facade/fcstd'
import type { DocumentSnapshot, FacadeEvent, ObjectPropertySnapshot, VectorValue } from '../src/facade/types'

const hosts: Array<{ id: string; typeId: string; propertyName: string; group: string }> = [
  { id: 'DirectionMirror', typeId: 'Part::Mirroring', propertyName: 'Normal', group: 'Plane' },
  { id: 'DirectionProjection', typeId: 'Part::ProjectOnSurface', propertyName: 'Direction', group: 'Projection' },
]

const directionProperty = (name: string, group: string, value: VectorValue): ObjectPropertySnapshot => ({
  name,
  label: name,
  group,
  scope: 'data',
  type: 'App::PropertyDirection',
  value: { ...value },
  unit: 'mm',
  recompute: true,
})

const fixture = (): DocumentSnapshot => ({
  id: 'property-direction-facade',
  label: 'PropertyDirection Facade',
  version: 1,
  dirty: false,
  readOnly: false,
  units: 'mm',
  tree: hosts.map(({ id }) => ({ id, label: id, type: 'feature', state: 'valid' })),
  objects: hosts.map(({ id, typeId, propertyName, group }) => ({ id, typeId, properties: [directionProperty(propertyName, group, { x: 0, y: 0, z: 1 })] })),
  dependencies: [],
  recompute: { generation: 0, status: 'idle', objectStates: Object.fromEntries(hosts.map(({ id }) => [id, 'up-to-date'])), dirtyObjects: [], order: [], errors: [] },
})

const valueOf = (facade: ReturnType<typeof createWebCadFacade>, objectId = 'DirectionMirror') => facade.app.document.getObject(objectId)?.properties[0].value as VectorValue

test('App::PropertyDirection keeps finite non-normalized vectors isolated in Facade snapshots', () => {
  const facade = createWebCadFacade({ initialDocument: fixture(), initialSelectedObjectIds: ['DirectionMirror'], runtimeMode: 'mock' })
  const events: FacadeEvent[] = []
  facade.subscribe((event) => {
    if (event.type === 'property.before-change' || event.type === 'property.changed' || event.type === 'transaction.committed') events.push(event)
  })
  const target = { x: 0.25, y: -0.5, z: 1.5 }
  facade.app.document.setProperty({ objectId: 'DirectionMirror', propertyName: 'Normal', value: target })
  target.x = 99
  assert.deepEqual(valueOf(facade), { x: 0.25, y: -0.5, z: 1.5 })
  const exposed = valueOf(facade)
  exposed.y = 99
  assert.deepEqual(valueOf(facade), { x: 0.25, y: -0.5, z: 1.5 })
  assert.equal(facade.app.document.getActive().version, 2)
  assert.equal(facade.app.document.getActive().dirty, true)
  assert.equal(facade.app.document.getActive().recompute?.objectStates.DirectionMirror, 'touched')
  assert.deepEqual(events.map((event) => event.type), ['property.before-change', 'property.changed', 'transaction.committed'])

  facade.app.document.setProperty({ objectId: 'DirectionMirror', propertyName: 'Normal', value: { x: 0, y: 0, z: 0 } })
  assert.deepEqual(valueOf(facade), { x: 0, y: 0, z: 0 })
  const stable = JSON.stringify(facade.app.document.getActive())
  const eventCount = events.length
  assert.throws(() => facade.app.document.setProperty({ objectId: 'DirectionMirror', propertyName: 'Normal', value: { x: Number.NaN, y: 0, z: 1 } }), /components must be finite/)
  assert.throws(() => facade.app.document.setProperty({ objectId: 'DirectionMirror', propertyName: 'Normal', value: [0, 0, 1] as unknown as VectorValue }), /requires a Vector value/)
  assert.throws(() => facade.app.document.setProperty({ objectId: 'DirectionMirror', propertyName: 'Normal', value: { x: 0, y: 1 } as unknown as VectorValue }), /components must be finite/)
  assert.equal(JSON.stringify(facade.app.document.getActive()), stable)
  assert.equal(events.length, eventCount)
})

test('App::PropertyDirection uses its native TypeId around PropertyVector FCStd payloads', () => {
  const document = fixture()
  document.objects[0].properties[0].value = { x: 0.25, y: -0.5, z: 1.5 }
  document.objects[1].properties[0].value = { x: 1, y: 2, z: 3 }
  const archive = serializeFcstdMetadataArchive(document)
  const documentXml = new TextDecoder().decode(unzipSync(archive)['Document.xml'])
  assert.match(documentXml, /<Object name="DirectionMirror" type="Part::Mirroring"/)
  assert.match(documentXml, /<Property name="Normal" type="App::PropertyDirection"><PropertyVector valueX="0.25" valueY="-0.5" valueZ="1.5"\/><\/Property>/)
  assert.match(documentXml, /<Object name="DirectionProjection" type="Part::ProjectOnSurface"/)
  assert.match(documentXml, /<Property name="Direction" type="App::PropertyDirection"><PropertyVector valueX="1" valueY="2" valueZ="3"\/><\/Property>/)
  assert.doesNotMatch(documentXml, /<Property name="(?:Normal|Direction)"[^>]+(?:group|doc|attr|ro|hide)=/)

  const inspection = createWebCadFacade({ initialDocument: document, runtimeMode: 'mock' }).project.fcstd.inspect(archive)
  assert.equal(inspection.objects.filter(({ support }) => support === 'recognized').length, 2)
  for (const [index, host] of hosts.entries()) {
    const object = inspection.objects.find(({ name }) => name === host.id)
    assert.equal(object?.support, 'recognized')
    const summary = object?.properties.find(({ name }) => name === host.propertyName)
    assert.deepEqual({ typeId: summary?.typeId, element: summary?.element }, { typeId: 'App::PropertyDirection', element: 'PropertyVector' })
    assert.deepEqual(decodeFcstdPropertyValue(summary!), { value: document.objects[index].properties[0].value, decoded: true })
  }
  assert.equal(decodeFcstdPropertyValue({ name: 'Normal', typeId: 'App::PropertyDirection', element: 'String', value: '{"x":0,"y":0,"z":1}' }).decoded, false)

  const rewritten = createWebCadFacade({ runtimeMode: 'mock' }).project.fcstd.rewriteDirection(archive, {
    objectName: 'DirectionMirror',
    propertyName: 'Normal',
    value: { x: 3, y: -2, z: 0.5 },
    expectedValue: { x: 0.25, y: -0.5, z: 1.5 },
  })
  const rewrittenProperty = createWebCadFacade({ runtimeMode: 'mock' }).project.fcstd.inspect(rewritten).objects[0].properties.find(({ name }) => name === 'Normal')
  assert.deepEqual(decodeFcstdPropertyValue(rewrittenProperty!), { value: { x: 3, y: -2, z: 0.5 }, decoded: true })
  assert.throws(() => createWebCadFacade({ runtimeMode: 'mock' }).project.fcstd.rewriteDirection(archive, { objectName: 'DirectionMirror', propertyName: 'Normal', value: { x: 1, y: 0, z: 0 }, expectedValue: { x: 0, y: 0, z: 1 } }), /does not match expectedValue/)
  assert.throws(() => createWebCadFacade({ runtimeMode: 'mock' }).project.fcstd.rewriteDirection(archive, { objectName: 'DirectionMirror', propertyName: 'Normal', value: { x: Number.NaN, y: 0, z: 1 } }), /value.x must be finite/)
})
