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

const outputStatus = encodeFreecadPropertyStatus(['PropReadOnly', 'PropOutput'])
const faceEntry = (persistentId: string, area: number, index: number) => ({
  ref: { shapeId: 'AreaBox-shape', kind: 'face' as const, persistentId, topologyVersion: 1, status: 'stable' as const },
  signature: { kind: 'face' as const, canonical: persistentId, hash: persistentId, centroid: [index, 0, 0] as [number, number, number], bounds: { min: [index, 0, 0] as [number, number, number], max: [index + 1, 1, 0] as [number, number, number] }, area, normal: [0, 0, 1] as [number, number, number] },
})

const fixture = (): DocumentSnapshot => ({
  id: 'property-area-facade',
  label: 'PropertyArea Facade',
  version: 1,
  dirty: false,
  readOnly: false,
  units: 'mm',
  tree: [
    { id: 'AreaBox', label: 'Area box', type: 'feature', state: 'valid' },
    { id: 'AreaProbe', label: 'Area probe', type: 'feature', state: 'valid' },
  ],
  objects: [
    {
      id: 'AreaBox',
      typeId: 'Part::Box',
      properties: [
        { name: 'Length', label: 'Length', group: 'Box', scope: 'data', type: 'App::PropertyLength', value: 10, unit: 'mm', recompute: true },
        { name: 'Width', label: 'Width', group: 'Box', scope: 'data', type: 'App::PropertyLength', value: 5, unit: 'mm', recompute: true },
        { name: 'Height', label: 'Height', group: 'Box', scope: 'data', type: 'App::PropertyLength', value: 2, unit: 'mm', recompute: true },
      ],
      topology: {
        shapeId: 'AreaBox-shape',
        documentVersion: 1,
        generation: 1,
        entries: [faceEntry('box-face-1', 10, 0), faceEntry('box-face-2', 10, 1)],
        migration: { previousGeneration: null, matches: [] },
        history: { operationId: 'AreaBox:1', provider: 'occt-native', relations: [], counts: { preserved: 0, modified: 0, generated: 0, deleted: 0, ambiguous: 0 } },
      },
    },
    {
      id: 'AreaProbe',
      typeId: 'Measure::MeasureArea',
      properties: [
        { name: 'Area', label: 'Area', group: 'Measurement', scope: 'data', type: 'App::PropertyArea', value: 10, unit: 'mm^2', nativeStatus: outputStatus, readOnly: true, recompute: false },
        { name: 'Elements', label: 'Elements', group: 'Measurement', scope: 'data', type: 'App::PropertyLinkSubList', value: { schemaVersion: 1, entries: [{ objectId: 'AreaBox', subElement: 'Face1' }] }, recompute: true },
      ],
    },
  ],
  dependencies: [{ sourceId: 'AreaProbe', targetId: 'AreaBox', relation: 'topo-ref', propertyName: 'Elements', reference: 'Face1' }],
  recompute: { generation: 0, status: 'idle', objectStates: { AreaBox: 'up-to-date', AreaProbe: 'up-to-date' }, dirtyObjects: [], order: [], errors: [] },
})

test('App::PropertyArea is a typed read-only Facade value with native FCStd codecs', () => {
  const facade = createWebCadFacade({ initialDocument: fixture(), initialSelectedObjectIds: ['AreaProbe'], runtimeMode: 'mock' })
  const events: FacadeEvent[] = []
  facade.subscribe((event) => events.push(event))
  const before = facade.app.document.getActive()
  const area = facade.app.document.getObject('AreaProbe')?.properties.find((property) => property.name === 'Area')
  assert.deepEqual({ type: area?.type, value: area?.value, unit: area?.unit, nativeStatus: area?.nativeStatus, readOnly: area?.readOnly }, { type: 'App::PropertyArea', value: 10, unit: 'mm^2', nativeStatus: outputStatus, readOnly: true })
  assert.throws(() => facade.app.document.setProperty({ objectId: 'AreaProbe', propertyName: 'Area', value: 20 }), /Area is read-only/)
  assert.deepEqual(facade.app.document.getActive(), before)
  assert.equal(events.length, 0)

  facade.app.document.setProperty({ objectId: 'AreaProbe', propertyName: 'Elements', value: { schemaVersion: 1, entries: [{ objectId: 'AreaBox', subElement: 'Face1' }, { objectId: 'AreaBox', subElement: 'Face2' }] } })
  const edited = facade.app.document.getActive()
  assert.equal(edited.objects.find((candidate) => candidate.id === 'AreaProbe')?.properties.find((property) => property.name === 'Area')?.value, 20)
  assert.equal(edited.recompute?.objectStates.AreaProbe, 'touched')
  assert.deepEqual(events.map((event) => event.type), ['property.before-change', 'state.changed', 'property.changed', 'transaction.committed', 'notice', 'state.changed'])
  const stableEvents = events.length
  assert.throws(() => facade.app.document.setProperty({ objectId: 'AreaProbe', propertyName: 'Elements', value: { schemaVersion: 1, entries: [{ objectId: 'AreaBox', subElement: 'Edge1' }] } }), /Cannot calculate area/)
  assert.deepEqual(facade.app.document.getActive(), edited)
  assert.equal(events.length, stableEvents)

  const archive = facade.project.fcstd.serializeMetadata(before)
  const documentXml = new TextDecoder().decode(unzipSync(archive)['Document.xml'])
  assert.match(documentXml, /<Object name="AreaProbe" type="Measure::MeasureArea"/)
  assert.match(documentXml, new RegExp(`<Property name="Area" type="App::PropertyArea" status="${outputStatus}"><Float value="10"/></Property>`))
  assert.match(documentXml, /<Property name="Elements" type="App::PropertyLinkSubList"><LinkSubList count="1"><Link obj="AreaBox" sub="Face1"\/><\/LinkSubList><\/Property>/)
  assert.doesNotMatch(documentXml, /<Property name="(?:Area|Elements)"[^>]+group=/)

  const inspection = facade.project.fcstd.inspect(archive)
  const object = inspection.objects.find((candidate) => candidate.name === 'AreaProbe')
  assert.equal(object?.typeId, 'Measure::MeasureArea')
  assert.equal(object?.support, 'recognized')
  const areaSummary = object?.properties.find((property) => property.name === 'Area')
  const elementsSummary = object?.properties.find((property) => property.name === 'Elements')
  assert.deepEqual({ typeId: areaSummary?.typeId, element: areaSummary?.element, nativeStatus: areaSummary?.nativeStatus, statusNames: areaSummary?.statusNames }, { typeId: 'App::PropertyArea', element: 'Float', nativeStatus: outputStatus, statusNames: ['PropReadOnly', 'PropOutput'] })
  assert.deepEqual(decodeFcstdPropertyValue(areaSummary!), { value: 10, decoded: true })
  assert.deepEqual(decodeFcstdPropertyValue(elementsSummary!), { value: { schemaVersion: 1, entries: [{ objectId: 'AreaBox', subElement: 'Face1' }] }, decoded: true })
})
