import { createHash } from 'node:crypto'
import { existsSync } from 'node:fs'
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { spawnSync } from 'node:child_process'
import { resolve } from 'node:path'
import { isDeepStrictEqual } from 'node:util'
import { unzipSync } from 'fflate'
import { createWebCadFacade } from '../src/facade/mockFacade'
import { decodeFcstdPropertyValue } from '../src/facade/fcstd'
import type { VectorValue } from '../src/facade/types'

const root = resolve(new URL('..', import.meta.url).pathname)
const executable = process.env.FREECAD_CMD || resolve(root, '.cache/freecad/install-desktop/bin/FreeCADCmd')
const sysroot = resolve(root, '.cache/freecad/sysroot')
const scriptPath = resolve(root, 'scripts/freecad-property-direction-roundtrip.py')
const outputDirectory = resolve(root, '.cache/freecad/property-direction-roundtrip')
const nativePath = resolve(outputDirectory, 'native-initial.FCStd')
const webPath = resolve(outputDirectory, 'web-edited.FCStd')
const resavedPath = resolve(outputDirectory, 'native-resaved.FCStd')
const repeatResavedPath = resolve(outputDirectory, 'native-resaved-repeat.FCStd')
const reportPath = resolve(root, 'config/freecad-property-direction-roundtrip.json')
if (!existsSync(executable)) throw new Error(`FreeCAD PropertyDirection roundtrip executable is missing: ${executable}`)
await mkdir(outputDirectory, { recursive: true })

const runNative = (mode: 'create' | 'verify', path: string, resaved = '') => {
  const execution = spawnSync(executable, ['--python-path', resolve(sysroot, 'usr/lib/python3/dist-packages'), scriptPath], {
    cwd: root,
    encoding: 'utf8',
    timeout: 120_000,
    maxBuffer: 32 * 1024 * 1024,
    env: {
      ...process.env,
      FREECAD_PROPERTY_DIRECTION_ROUNDTRIP_MODE: mode,
      FREECAD_PROPERTY_DIRECTION_ROUNDTRIP_PATH: path,
      FREECAD_PROPERTY_DIRECTION_ROUNDTRIP_RESAVED_PATH: resaved,
      PYTHONPATH: `${resolve(sysroot, 'usr/lib/python3/dist-packages')}${process.env.PYTHONPATH ? `:${process.env.PYTHONPATH}` : ''}`,
      LD_LIBRARY_PATH: `${resolve(sysroot, 'usr/lib/x86_64-linux-gnu')}${process.env.LD_LIBRARY_PATH ? `:${process.env.LD_LIBRARY_PATH}` : ''}`,
    },
  })
  const output = `${execution.stdout || ''}\n${execution.stderr || ''}`
  const marker = 'FREECAD_PROPERTY_DIRECTION_ROUNDTRIP_RESULT='
  const line = output.split(/\r?\n/).find((candidate) => candidate.includes(marker))
  if (execution.error || execution.status !== 0 || !line) throw new Error(`FreeCAD PropertyDirection ${mode} probe failed with status ${execution.status}: ${execution.error?.message || output.trim()}`)
  return JSON.parse(line.slice(line.indexOf(marker) + marker.length))
}

const initial: VectorValue = { x: 0, y: 0, z: 1 }
const target: VectorValue = { x: 0.25, y: -0.5, z: 1.5 }
const native = runNative('create', nativePath)
const nativeBytes = new Uint8Array(await readFile(nativePath))
const facade = createWebCadFacade({ runtimeMode: 'mock' })
const inspectedBefore = facade.project.fcstd.inspect(nativeBytes)
const property = (inspection: typeof inspectedBefore) => inspection.objects.find((object) => object.name === 'DirectionMirror')?.properties.find((candidate) => candidate.name === 'Normal')
const editedBytes = facade.project.fcstd.rewriteDirection(nativeBytes, {
  objectName: 'DirectionMirror',
  propertyName: 'Normal',
  value: target,
  expectedValue: initial,
})
const inspectedAfter = facade.project.fcstd.inspect(editedBytes)
await facade.project.dispose()
await writeFile(webPath, editedBytes)

const initialFiles = unzipSync(nativeBytes)
const editedFiles = unzipSync(editedBytes)
const opaquePaths = Object.keys(initialFiles).filter((path) => path.toLowerCase() !== 'document.xml')
const opaqueEntriesPreserved = opaquePaths.every((path) => Buffer.from(initialFiles[path]).equals(Buffer.from(editedFiles[path] ?? new Uint8Array())))
const withoutEditedProperty = (inspection: typeof inspectedBefore) => inspection.objects.map((object) => ({ ...object, properties: object.name === 'DirectionMirror' ? object.properties.filter((candidate) => candidate.name !== 'Normal') : object.properties }))
const semanticObjectsPreserved = isDeepStrictEqual(withoutEditedProperty(inspectedBefore), withoutEditedProperty(inspectedAfter))
const editedDocumentXml = new TextDecoder().decode(editedFiles['Document.xml'])
const targetMarkedTouched = /<Object(?=[^>]*name="DirectionMirror")(?=[^>]*Touched="1")[^>]*\/>/.test(editedDocumentXml)
const nativeAfter = runNative('verify', webPath, resavedPath)
const nativeRepeat = runNative('verify', webPath, repeatResavedPath)
const resavedBytes = new Uint8Array(await readFile(resavedPath))
const repeatResavedBytes = new Uint8Array(await readFile(repeatResavedPath))
const nativeSnapshots = [nativeAfter.result.reopened, nativeAfter.result.resaved, nativeRepeat.result.reopened, nativeRepeat.result.resaved]
const nativeOutputMatches = nativeSnapshots.every((snapshot: any) => isDeepStrictEqual(snapshot.object.value, target))
const shapeStructure = ({ brepSha256: _brepSha256, ...shape }: Record<string, unknown>) => shape
const nativeShapeStructureStable = nativeSnapshots.every((snapshot: any) => isDeepStrictEqual(shapeStructure(snapshot.object.shape), shapeStructure(nativeAfter.result.reopened.object.shape)))
const nativeBrepReserialized = nativeAfter.result.reopened.object.shape.brepSha256 !== nativeAfter.result.resaved.object.shape.brepSha256
const nativeBrepEvolutionReproduced = nativeAfter.result.reopened.object.shape.brepSha256 === nativeRepeat.result.reopened.object.shape.brepSha256 && nativeAfter.result.resaved.object.shape.brepSha256 === nativeRepeat.result.resaved.object.shape.brepSha256
const nativeShapeChanged = native.result.object.shape.brepSha256 !== nativeAfter.result.reopened.object.shape.brepSha256 && !isDeepStrictEqual(native.result.object.shape.bounds, nativeAfter.result.reopened.object.shape.bounds)
const objectSetPreserved = nativeSnapshots.every((snapshot: any) => isDeepStrictEqual(native.result.objectSet, snapshot.objectSet))
const decodedAfter = property(inspectedAfter) ? decodeFcstdPropertyValue(property(inspectedAfter)!) : undefined
const webOutputMatches = decodedAfter?.decoded === true && isDeepStrictEqual(decodedAfter.value, target)
const nativeAllowedEvolution = nativeShapeStructureStable && nativeBrepReserialized && nativeBrepEvolutionReproduced
const zeroUnknownDrift = opaqueEntriesPreserved && semanticObjectsPreserved && targetMarkedTouched && webOutputMatches && nativeOutputMatches && nativeAllowedEvolution && nativeShapeChanged && objectSetPreserved
const report = {
  schemaVersion: 1,
  status: zeroUnknownDrift ? 'pass' : 'fail',
  baselineId: 'freecad-1.1.1-property-direction-roundtrip',
  freecadVersion: native.freecadVersion,
  gitCommit: native.gitCommit,
  propertyType: 'App::PropertyDirection',
  archives: {
    nativeInitial: { path: '.cache/freecad/property-direction-roundtrip/native-initial.FCStd', bytes: nativeBytes.byteLength, sha256: createHash('sha256').update(nativeBytes).digest('hex') },
    webEdited: { path: '.cache/freecad/property-direction-roundtrip/web-edited.FCStd', bytes: editedBytes.byteLength, sha256: createHash('sha256').update(editedBytes).digest('hex') },
    nativeResaved: { path: '.cache/freecad/property-direction-roundtrip/native-resaved.FCStd', bytes: resavedBytes.byteLength, sha256: createHash('sha256').update(resavedBytes).digest('hex') },
    nativeRepeatResaved: { path: '.cache/freecad/property-direction-roundtrip/native-resaved-repeat.FCStd', bytes: repeatResavedBytes.byteLength, sha256: createHash('sha256').update(repeatResavedBytes).digest('hex') },
  },
  nativeInitial: native.result,
  web: {
    before: property(inspectedBefore),
    after: property(inspectedAfter),
    targetMarkedTouched,
    webOutputMatches,
    objectSetPreserved,
    semanticObjectsPreserved,
    opaquePathsPreserved: opaquePaths.length,
    opaqueEntriesPreserved,
  },
  nativeAfter: nativeAfter.result,
  nativeRepeat: nativeRepeat.result,
  classification: {
    requestedValue: target,
    webValue: decodedAfter?.value,
    reopenedValue: nativeAfter.result.reopened.object.value,
    resavedValue: nativeAfter.result.resaved.object.value,
    nativeOutputMatches,
    nativeShapeChanged,
    nativeShapeStructureStable,
    nativeBrepReserialized,
    nativeBrepEvolutionReproduced,
    nativeAllowedEvolution: {
      classification: nativeAllowedEvolution ? 'native-allowed-evolution' : 'unknown',
      dimension: 'brep-serialization',
      reason: 'FreeCAD save/reopen reserializes the recomputed Shape while direction, bounds, topology, mass properties and validity remain stable.',
    },
    unknownSemanticDrift: !zeroUnknownDrift,
    zeroUnknownDrift,
  },
}
await writeFile(reportPath, `${JSON.stringify(report, null, 2)}\n`)
console.log(JSON.stringify({ status: report.status, output: 'config/freecad-property-direction-roundtrip.json', values: report.classification, opaqueEntriesPreserved, semanticObjectsPreserved, targetMarkedTouched }, null, 2))
