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 type { DocumentSnapshot, FacadeEvent, ObjectPropertySnapshot } from '../src/facade/types'

const hosts = [
  { id: 'FontAnnotation', typeId: 'TechDraw::DrawViewAnnotation', group: 'Annotation' },
  { id: 'FontSpreadsheet', typeId: 'TechDraw::DrawViewSpreadsheet', group: 'Spreadsheet' },
] as const

const property = (group: string): ObjectPropertySnapshot => ({ name: 'Font', label: 'Font', group, scope: 'data', type: 'App::PropertyFont', value: 'osifont', recompute: true })
const fixture = (): DocumentSnapshot => ({
  id: 'property-font-facade',
  label: 'PropertyFont 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, group }) => ({ id, typeId, properties: [property(group)] })),
  dependencies: [],
  recompute: { generation: 0, status: 'idle', objectStates: Object.fromEntries(hosts.map(({ id }) => [id, 'up-to-date'])), dirtyObjects: [], order: [], errors: [] },
})

test('App::PropertyFont preserves arbitrary UTF-8 family names through the Facade', () => {
  const facade = createWebCadFacade({ initialDocument: fixture(), initialSelectedObjectIds: ['FontAnnotation'], 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)
  })
  facade.app.document.setProperty({ objectId: 'FontAnnotation', propertyName: 'Font', value: 'Noto Sans CJK SC' })
  assert.equal(facade.app.document.getObject('FontAnnotation')?.properties[0].value, 'Noto Sans CJK SC')
  assert.equal(facade.app.document.getActive().version, 2)
  assert.equal(facade.app.document.getActive().dirty, true)
  assert.equal(facade.app.document.getActive().recompute?.objectStates.FontAnnotation, 'touched')
  assert.deepEqual(events.map(({ type }) => type), ['property.before-change', 'property.changed', 'transaction.committed'])

  facade.app.document.setProperty({ objectId: 'FontAnnotation', propertyName: 'Font', value: '' })
  assert.equal(facade.app.document.getObject('FontAnnotation')?.properties[0].value, '')
  const stable = JSON.stringify(facade.app.document.getActive())
  const eventCount = events.length
  assert.throws(() => facade.app.document.setProperty({ objectId: 'FontAnnotation', propertyName: 'Font', value: 42 as unknown as string }), /requires a string value/)
  assert.throws(() => facade.app.document.setProperty({ objectId: 'FontAnnotation', propertyName: 'Font', value: `Bad\0Font` }), /unsupported control characters/)
  assert.throws(() => facade.app.document.setProperty({ objectId: 'FontAnnotation', propertyName: 'Font', value: 'a'.repeat(1025) }), /font family name is too long/)
  assert.equal(JSON.stringify(facade.app.document.getActive()), stable)
  assert.equal(events.length, eventCount)
})

test('App::PropertyFont keeps its TypeId around native String FCStd payloads', async () => {
  const document = fixture()
  document.objects[0].properties[0].value = 'DejaVu Sans'
  document.objects[1].properties[0].value = 'Liberation Serif'
  const facade = createWebCadFacade({ initialDocument: document, runtimeMode: 'mock' })
  const archive = facade.project.fcstd.serializeMetadata(document)
  const documentXml = new TextDecoder().decode(unzipSync(archive)['Document.xml'])
  assert.match(documentXml, /<Property name="Font" type="App::PropertyFont"><String value="DejaVu Sans"\/><\/Property>/)
  assert.match(documentXml, /<Property name="Font" type="App::PropertyFont"><String value="Liberation Serif"\/><\/Property>/)
  assert.doesNotMatch(documentXml, /<Property name="Font"[^>]+(?:group|doc|attr|ro|hide)=/)

  const inspection = facade.project.fcstd.inspect(archive)
  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 === 'Font')
    assert.deepEqual({ typeId: summary?.typeId, element: summary?.element }, { typeId: 'App::PropertyFont', element: 'String' })
    assert.deepEqual(decodeFcstdPropertyValue(summary!), { value: document.objects[index].properties[0].value, decoded: true })
  }
  assert.equal(decodeFcstdPropertyValue({ name: 'Font', typeId: 'App::PropertyFont', element: 'PropertyFont', value: 'osifont' }).decoded, false)

  const rewritten = facade.project.fcstd.rewriteFont(archive, { objectName: 'FontAnnotation', propertyName: 'Font', value: 'Noto Sans', expectedValue: 'DejaVu Sans' })
  const rewrittenProperty = facade.project.fcstd.inspect(rewritten).objects.find(({ name }) => name === 'FontAnnotation')?.properties.find(({ name }) => name === 'Font')
  assert.deepEqual(decodeFcstdPropertyValue(rewrittenProperty!), { value: 'Noto Sans', decoded: true })
  assert.match(new TextDecoder().decode(unzipSync(rewritten)['Document.xml']), /<Object(?=[^>]*name="FontAnnotation")(?=[^>]*Touched="1")[^>]*\/>/)
  assert.throws(() => facade.project.fcstd.rewriteFont(archive, { objectName: 'FontAnnotation', propertyName: 'Font', value: 'Noto Sans', expectedValue: 'Wrong' }), /does not match expectedValue/)
  assert.throws(() => facade.project.fcstd.rewriteFont(archive, { objectName: 'FontAnnotation', propertyName: 'Font', value: `Bad\0Font` }), /unsupported control characters/)
  assert.throws(() => facade.project.fcstd.rewriteFont(archive, { objectName: 'FontAnnotation', propertyName: 'Missing', value: 'Noto Sans' }), /property does not exist/)
  await facade.project.dispose()
})
