import { BitbybitGeometryRuntime } from './facade/geometryRuntime'
import { instantiateFcstdShapeResource, serializeFcstdMetadataArchive } from './facade/fcstd'
import type { DocumentSnapshot } from './facade/types'

type FeatureResult = { name: string; shapeId: string; meshVertices: number; meshTriangles: number; topology?: { faces: number; edges: number; vertices: number }; volume?: number }
type PerformanceEvidence = { durationMs: number; operationCount: number; averageOperationMs: number; peakShapeCount: number; stressObjectCount: number; stressDurationMs: number; stressPeakShapeCount: number; triangleStress: { radius: number; precision: number; triangles: number; vertices: number; durationMs: number } }
type HarnessReport = {
  schemaVersion: 1
  status: 'pass' | 'failed'
  browserId: 'chrome'
  geometryProvider: string
  operations: FeatureResult[]
  beforeRelease: { shapeCount: number; kernelReferenceCount: number }
  afterRelease: { shapeCount: number; kernelReferenceCount: number }
  fcstdBrep?: { resourcePath: string; references: number; sourceBytes: number; topology: { faces: number; edges: number; vertices: number }; massProperties: { source: { volume: number; surfaceArea: number; centerOfMass: [number, number, number] }; imported: { volume: number; surfaceArea: number; centerOfMass: [number, number, number] } }; emptyRejected: boolean; cancelledBeforeImport: boolean; cancelledResultReleased: boolean }
  exchangeFormats?: { iges: { sourceBytes: number; sourceVolume: number; importedVolume: number; importedFaces: number; importedEdges: number; importedVertices: number } }
  performance: PerformanceEvidence
  error?: string
}

const square = (size: number, z: number) => ({ outer: [[-size, -size, z], [size, -size, z], [size, size, z], [-size, size, z]] as [number, number, number][] })
const pipeProfile = (size: number) => ({ outer: [[0, -size, -size], [0, size, -size], [0, size, size], [0, -size, size]] as [number, number, number][] })
const revolutionProfile = () => ({ outer: [[3, 0, -1], [5, 0, -1], [5, 0, 1], [3, 0, 1]] as [number, number, number][] })
const holeProfile = (radius: number, z: number) => ({ outer: Array.from({ length: 32 }, (_, index): [number, number, number] => { const angle = 2 * Math.PI * index / 32; return [radius * Math.cos(angle), radius * Math.sin(angle), z] }) })
const setStatus = (message: string) => { document.querySelector('#status')!.textContent = message }
const fcstdShapeDocument = (resourcePath: string): DocumentSnapshot => ({
  id: 'chrome-fcstd-brep',
  label: 'Chrome FCStd BRep',
  version: 1,
  dirty: false,
  readOnly: false,
  units: 'mm',
  tree: [{ id: 'Box', label: 'Box', type: 'feature', state: 'valid' }],
  objects: [{ id: 'Box', typeId: 'Part::Feature', properties: [{ name: 'Shape', label: 'Shape', group: 'Base', scope: 'data', type: 'Part::PropertyPartShape', value: { path: resourcePath, format: 'brep', elementMap: '1' } }] }],
  dependencies: [],
  recompute: { generation: 0, status: 'idle', objectStates: { Box: 'up-to-date' }, dirtyObjects: [], order: [], errors: [] },
})

const run = async (): Promise<HarnessReport> => {
  const runtime = new BitbybitGeometryRuntime()
  const documentContext = { documentId: 'chrome-feature-harness', documentVersion: 1 }
  const owned: Array<{ id: string; kernel: 'bitbybit-occt'; kind: 'solid'; documentId: string; documentVersion: number }> = []
  const operations: FeatureResult[] = []
  const startedAt = performance.now()
  let peakShapeCount = 0
  const capture = async (name: string, shape: (typeof owned)[number], topology?: { faces: number; edges: number; vertices: number }, includeMass = false) => {
    const mesh = await runtime.mesh(shape)
    const mass = includeMass ? await runtime.massProperties(shape) : undefined
    const result = { name, shapeId: shape.id, meshVertices: mesh.positions.length / 3, meshTriangles: mesh.indices.length / 3, ...(topology ? { topology } : {}), ...(mass ? { volume: mass.volume } : {}) }
    if (result.meshVertices < 3 || result.meshTriangles < 1) throw new Error(`${name} returned an empty mesh.`)
    operations.push(result)
    peakShapeCount = Math.max(peakShapeCount, runtime.capabilities().shapeCount)
  }
  try {
    const capabilities = await runtime.initialize()
    if (capabilities.status !== 'ready') throw new Error(capabilities.reason || `Bitbybit runtime status is ${capabilities.status}.`)
    const fcstdSource = await runtime.createBox({ ...documentContext, width: 2, length: 3, height: 4 })
    owned.push(fcstdSource)
    const brepExport = await runtime.exportBrep(fcstdSource, 'Box.Shape.brp')
    const igesExport = await runtime.exportIges(fcstdSource, 'Box.Shape.iges')
    const igesImported = await runtime.importShape({ ...documentContext, format: 'iges', text: igesExport.text })
    owned.push(igesImported)
    const igesTopology = await runtime.topology(igesImported)
    const igesSourceMass = await runtime.massProperties(fcstdSource)
    const igesImportedMass = await runtime.massProperties(igesImported)
    if (Math.abs(igesSourceMass.volume - igesImportedMass.volume) > 1e-7 || igesTopology.faces.length !== 6 || igesTopology.edges.length < 1 || igesTopology.vertices.length < 1) throw new Error(`IGES round-trip mismatch: ${JSON.stringify({ source: igesSourceMass, imported: igesImportedMass, topology: igesTopology })}`)
    const resourcePath = 'Part/Box.Shape.brp'
    const fcstdArchive = serializeFcstdMetadataArchive(fcstdShapeDocument(resourcePath), { opaqueEntries: { [resourcePath]: new TextEncoder().encode(brepExport.text) } })
    const importedFcstd = await instantiateFcstdShapeResource(fcstdArchive, resourcePath, ({ format, text }) => runtime.importShape({ ...documentContext, format, text }), { release: (shape) => runtime.release(shape) })
    owned.push(importedFcstd.shape)
    const importedTopology = await runtime.topology(importedFcstd.shape)
    const importedTopologyCounts = { faces: importedTopology.faces.length, edges: importedTopology.edges.length, vertices: importedTopology.vertices.length }
    if (importedTopologyCounts.faces !== 6 || importedTopologyCounts.edges !== 12 || importedTopologyCounts.vertices !== 8) throw new Error(`FCStd BRep topology mismatch: ${JSON.stringify(importedTopologyCounts)}`)
    const sourceMassProperties = await runtime.massProperties(fcstdSource)
    const importedMassProperties = await runtime.massProperties(importedFcstd.shape)
    const massDelta = Math.max(Math.abs(sourceMassProperties.volume - importedMassProperties.volume), Math.abs(sourceMassProperties.surfaceArea - importedMassProperties.surfaceArea), ...sourceMassProperties.centerOfMass.map((value, index) => Math.abs(value - importedMassProperties.centerOfMass[index])))
    if (Math.abs(sourceMassProperties.volume - 24) > 1e-7 || massDelta > 1e-7) throw new Error(`FCStd BRep mass properties mismatch: ${JSON.stringify({ source: sourceMassProperties, imported: importedMassProperties, massDelta })}`)
    await capture('fcstd-brep-import', importedFcstd.shape, importedTopologyCounts)
    const cancelledBeforeImportController = new AbortController()
    cancelledBeforeImportController.abort()
    const shapeCountBeforeCancel = runtime.capabilities().shapeCount
    let cancelledBeforeImport = false
    try {
      await instantiateFcstdShapeResource(fcstdArchive, resourcePath, ({ format, text }) => runtime.importShape({ ...documentContext, format, text }), { signal: cancelledBeforeImportController.signal, release: (shape) => runtime.release(shape) })
    } catch (error) {
      cancelledBeforeImport = error instanceof DOMException && error.name === 'AbortError'
    }
    if (!cancelledBeforeImport || runtime.capabilities().shapeCount !== shapeCountBeforeCancel) throw new Error('FCStd BRep cancellation imported an unexpected ShapeHandle.')
    const emptyArchive = serializeFcstdMetadataArchive(fcstdShapeDocument(resourcePath), { opaqueEntries: { [resourcePath]: new Uint8Array() } })
    let emptyRejected = false
    try {
      await instantiateFcstdShapeResource(emptyArchive, resourcePath, ({ format, text }) => runtime.importShape({ ...documentContext, format, text }), { release: (shape) => runtime.release(shape) })
    } catch (error) {
      emptyRejected = /empty/i.test(error instanceof Error ? error.message : String(error))
    }
    if (!emptyRejected) throw new Error('FCStd empty BRep resource was not rejected.')
    const lateCancelController = new AbortController()
    let cancelledResultReleased = false
    try {
      await instantiateFcstdShapeResource(fcstdArchive, resourcePath, ({ format, text }) => runtime.importShape({ ...documentContext, format, text }).then((shape) => { lateCancelController.abort(); return shape }), { signal: lateCancelController.signal, release: async (shape) => { cancelledResultReleased = true; await runtime.release(shape) } })
    } catch (error) {
      if (!(error instanceof DOMException && error.name === 'AbortError')) throw error
    }
    if (!cancelledResultReleased || runtime.capabilities().shapeCount !== shapeCountBeforeCancel) throw new Error('FCStd late cancellation did not release the imported ShapeHandle.')
    const fcstdBrep = { resourcePath, references: importedFcstd.references.length, sourceBytes: new TextEncoder().encode(brepExport.text).byteLength, topology: importedTopologyCounts, massProperties: { source: sourceMassProperties, imported: importedMassProperties }, emptyRejected, cancelledBeforeImport, cancelledResultReleased }
    const exchangeFormats = { iges: { sourceBytes: new TextEncoder().encode(igesExport.text).byteLength, sourceVolume: igesSourceMass.volume, importedVolume: igesImportedMass.volume, importedFaces: igesTopology.faces.length, importedEdges: igesTopology.edges.length, importedVertices: igesTopology.vertices.length } }
    const extrude = await runtime.extrude({ ...documentContext, profile: square(1, 0), length: 2, direction: [0, 0, 1] })
    owned.push(extrude)
    await capture('extrude', extrude)
    const revolution = await runtime.revolution({ ...documentContext, profile: revolutionProfile(), angle: 270, axisOrigin: [0, 0, 0], axisDirection: [0, 0, 1] })
    owned.push(revolution)
    await capture('revolution', revolution)
    const filletBase = await runtime.createBox({ ...documentContext, width: 4, length: 4, height: 4 })
    owned.push(filletBase)
    const fillet = await runtime.fillet({ ...documentContext, base: filletBase, radius: 0.4, indexes: [0] })
    owned.push(fillet)
    await capture('fillet-selected-edge', fillet)
    const chamferBase = await runtime.createBox({ ...documentContext, width: 4, length: 4, height: 4 })
    owned.push(chamferBase)
    const chamfer = await runtime.chamfer({ ...documentContext, base: chamferBase, distance: 0.4, indexes: [0] })
    owned.push(chamfer)
    await capture('chamfer-selected-edge', chamfer)
    const draftBase = await runtime.createBox({ ...documentContext, width: 4, length: 4, height: 4 })
    owned.push(draftBase)
    const draft = await runtime.draft({ ...documentContext, base: draftBase, angle: 5, direction: [0, 0, 1], neutralPlaneOrigin: [0, 0, 0], neutralPlaneDirection: [0, 0, 1], indexes: [1] })
    owned.push(draft)
    await capture('draft-selected-face', draft)
    const thicknessBase = await runtime.createBox({ ...documentContext, width: 6, length: 6, height: 6 })
    owned.push(thicknessBase)
    const thickness = await runtime.thickness({ ...documentContext, base: thicknessBase, offset: -0.4, removeFaceIndexes: [1], joinType: 'Arc' })
    owned.push(thickness)
    await capture('thickness', thickness)
    const holeBase = await runtime.createBox({ ...documentContext, width: 6, length: 6, height: 6, center: [0, 0, 0], originOnCenter: true })
    owned.push(holeBase)
    const primaryHole = await runtime.pocket({ ...documentContext, base: holeBase, profile: holeProfile(0.7, -3), length: 8, direction: [0, 0, 1] })
    owned.push(primaryHole)
    const counterboreTool = await runtime.createCylinder({ ...documentContext, radius: 1.1, height: 1.5, center: [0, 0, -3], direction: [0, 0, 1] })
    owned.push(counterboreTool)
    const counterbore = await runtime.cut({ ...documentContext, base: primaryHole, tools: [counterboreTool] })
    owned.push(counterbore)
    await capture('hole-counterbore', counterbore)
    const countersinkBase = await runtime.createBox({ ...documentContext, width: 6, length: 6, height: 6, center: [0, 0, 0], originOnCenter: true })
    owned.push(countersinkBase)
    const countersinkPrimary = await runtime.pocket({ ...documentContext, base: countersinkBase, profile: holeProfile(0.7, -3), length: 8, direction: [0, 0, 1] })
    owned.push(countersinkPrimary)
    const countersinkTool = await runtime.createCone({ ...documentContext, radius1: 1.1, radius2: 0.7, height: 0.4, center: [0, 0, -3], direction: [0, 0, 1] })
    owned.push(countersinkTool)
    const countersink = await runtime.cut({ ...documentContext, base: countersinkPrimary, tools: [countersinkTool] })
    owned.push(countersink)
    await capture('hole-countersink', countersink)
    const counterdrillBase = await runtime.createBox({ ...documentContext, width: 6, length: 6, height: 6, center: [0, 0, 0], originOnCenter: true })
    owned.push(counterdrillBase)
    const counterdrillPrimary = await runtime.pocket({ ...documentContext, base: counterdrillBase, profile: holeProfile(0.7, -3), length: 8, direction: [0, 0, 1] })
    owned.push(counterdrillPrimary)
    const counterdrillCylinder = await runtime.createCylinder({ ...documentContext, radius: 1.1, height: 1.5, center: [0, 0, -3], direction: [0, 0, 1] })
    owned.push(counterdrillCylinder)
    const counterdrillCone = await runtime.createCone({ ...documentContext, radius1: 1.1, radius2: 0.7, height: 0.4, center: [0, 0, -1.5], direction: [0, 0, 1] })
    owned.push(counterdrillCone)
    const counterdrill = await runtime.cut({ ...documentContext, base: counterdrillPrimary, tools: [counterdrillCylinder, counterdrillCone] })
    owned.push(counterdrill)
    await capture('hole-counterdrill', counterdrill)
    const angledBase = await runtime.createBox({ ...documentContext, width: 6, length: 6, height: 6, center: [0, 0, 0], originOnCenter: true })
    owned.push(angledBase)
    const angledPrimary = await runtime.pocket({ ...documentContext, base: angledBase, profile: holeProfile(0.7, -3), length: 3, direction: [0, 0, 1] })
    owned.push(angledPrimary)
    const angledHeight = 0.7 / Math.tan((180 - 118) * Math.PI / 360)
    const angledTool = await runtime.createCone({ ...documentContext, radius1: 0.7, radius2: 0, height: angledHeight, center: [0, 0, 0], direction: [0, 0, 1] })
    owned.push(angledTool)
    const angled = await runtime.cut({ ...documentContext, base: angledPrimary, tools: [angledTool] })
    owned.push(angled)
    await capture('hole-angled-drill-point', angled)
    const includedDepthBase = await runtime.createBox({ ...documentContext, width: 6, length: 6, height: 6, center: [0, 0, 0], originOnCenter: true })
    owned.push(includedDepthBase)
    const includedDepth = 3
    const includedTipHeight = 0.7 / Math.tan((180 - 118) * Math.PI / 360)
    const includedCylinderDepth = includedDepth - includedTipHeight
    const includedPrimary = await runtime.pocket({ ...documentContext, base: includedDepthBase, profile: holeProfile(0.7, -3), length: includedCylinderDepth, direction: [0, 0, 1] })
    owned.push(includedPrimary)
    const includedTip = await runtime.createCone({ ...documentContext, radius1: 0.7, radius2: 0, height: includedTipHeight, center: [0, 0, -3 + includedCylinderDepth], direction: [0, 0, 1] })
    owned.push(includedTip)
    const includedDepthHole = await runtime.cut({ ...documentContext, base: includedPrimary, tools: [includedTip] })
    owned.push(includedDepthHole)
    await capture('hole-angled-included-depth', includedDepthHole)
    const taperedBase = await runtime.createBox({ ...documentContext, width: 6, length: 6, height: 6, center: [0, 0, 0], originOnCenter: true })
    owned.push(taperedBase)
    const taperedRadius = 0.7 + Math.tan((95 - 90) * Math.PI / 180) * 4
    const taperedTool = await runtime.createCone({ ...documentContext, radius1: 0.7, radius2: taperedRadius, height: 4, center: [0, 0, -3], direction: [0, 0, 1] })
    owned.push(taperedTool)
    const tapered = await runtime.cut({ ...documentContext, base: taperedBase, tools: [taperedTool] })
    owned.push(tapered)
    await capture('hole-tapered', tapered)
    const sections = [square(1, 0), square(0.7, 3)]
    const loft = await runtime.loft({ ...documentContext, sections })
    owned.push(loft)
    await capture('loft', loft)
    const ruled = await runtime.loft({ ...documentContext, sections, ruled: true })
    owned.push(ruled)
    await capture('loft-ruled', ruled)
    const additiveBase = await runtime.createBox({ ...documentContext, width: 5, length: 5, height: 5, center: [0, 0, 0], originOnCenter: true })
    owned.push(additiveBase)
    const additive = await runtime.loft({ ...documentContext, sections, mode: 'additive', base: additiveBase })
    owned.push(additive)
    await capture('loft-additive', additive)
    const subtractiveBase = await runtime.createBox({ ...documentContext, width: 5, length: 5, height: 6, center: [0, 0, 1.5], originOnCenter: true })
    owned.push(subtractiveBase)
    const subtractive = await runtime.loft({ ...documentContext, sections: [square(1, 0.5), square(0.7, 2.5)], mode: 'subtractive', base: subtractiveBase })
    owned.push(subtractive)
    await capture('loft-subtractive', subtractive)
    const pipe = await runtime.pipe({ ...documentContext, profile: pipeProfile(0.35), path: [[0, 0, 0], [3, 0, 0]] })
    owned.push(pipe)
    await capture('pipe', pipe)
    const twoSidedExtrudeForward = await runtime.extrude({ ...documentContext, profile: square(0.8, 0), length: 2, direction: [0, 0, 1] })
    owned.push(twoSidedExtrudeForward)
    const twoSidedExtrudeReverse = await runtime.extrude({ ...documentContext, profile: square(0.8, 0), length: 1, direction: [0, 0, 1], reversed: true })
    owned.push(twoSidedExtrudeReverse)
    const twoSidedExtrude = await runtime.union({ ...documentContext, shapes: [twoSidedExtrudeForward, twoSidedExtrudeReverse] })
    owned.push(twoSidedExtrude)
    await capture('extrude-two-sided', twoSidedExtrude)
    const symmetricRevolutionPositive = await runtime.revolution({ ...documentContext, profile: revolutionProfile(), angle: 90, axisOrigin: [0, 0, 0], axisDirection: [0, 0, 1] })
    owned.push(symmetricRevolutionPositive)
    const symmetricRevolutionNegative = await runtime.revolution({ ...documentContext, profile: revolutionProfile(), angle: 90, axisOrigin: [0, 0, 0], axisDirection: [0, 0, -1] })
    owned.push(symmetricRevolutionNegative)
    const symmetricRevolution = await runtime.union({ ...documentContext, shapes: [symmetricRevolutionPositive, symmetricRevolutionNegative] })
    owned.push(symmetricRevolution)
    await capture('revolution-symmetric', symmetricRevolution)
    const twoAngleRevolutionPositive = await runtime.revolution({ ...documentContext, profile: revolutionProfile(), angle: 120, axisOrigin: [0, 0, 0], axisDirection: [0, 1, 0] })
    owned.push(twoAngleRevolutionPositive)
    const twoAngleRevolutionNegative = await runtime.revolution({ ...documentContext, profile: revolutionProfile(), angle: 60, axisOrigin: [0, 0, 0], axisDirection: [0, -1, 0] })
    owned.push(twoAngleRevolutionNegative)
    const twoAngleRevolution = await runtime.union({ ...documentContext, shapes: [twoAngleRevolutionPositive, twoAngleRevolutionNegative] })
    owned.push(twoAngleRevolution)
    await capture('revolution-two-angles', twoAngleRevolution)
    const twoSidedPadForward = await runtime.pad({ ...documentContext, profile: square(0.7, 0), length: 2, direction: [0, 0, 1] })
    owned.push(twoSidedPadForward)
    const twoSidedPadReverse = await runtime.pad({ ...documentContext, profile: square(0.7, 0), length: 1, direction: [0, 0, 1], reversed: true })
    owned.push(twoSidedPadReverse)
    const twoSidedPad = await runtime.union({ ...documentContext, shapes: [twoSidedPadForward, twoSidedPadReverse] })
    owned.push(twoSidedPad)
    await capture('pad-two-sided', twoSidedPad)
    const twoSidedPocketBase = await runtime.createBox({ ...documentContext, width: 5, length: 5, height: 5, center: [0, 0, 0], originOnCenter: true })
    owned.push(twoSidedPocketBase)
    const twoSidedPocketForward = await runtime.pocket({ ...documentContext, base: twoSidedPocketBase, profile: holeProfile(0.8, 0), length: 4, direction: [0, 0, 1] })
    owned.push(twoSidedPocketForward)
    const twoSidedPocket = await runtime.pocket({ ...documentContext, base: twoSidedPocketForward, profile: holeProfile(0.8, 0), length: 4, direction: [0, 0, 1], reversed: true })
    owned.push(twoSidedPocket)
    await capture('pocket-two-sided', twoSidedPocket)
    const taperedPad = await runtime.pad({ ...documentContext, profile: square(2, 0), length: 5, direction: [0, 0, 1], taperAngle: 5 })
    owned.push(taperedPad)
    await capture('pad-tapered', taperedPad, undefined, true)
    const taperedPocketBase = await runtime.createBox({ ...documentContext, width: 10, length: 10, height: 10, center: [0, 0, 0], originOnCenter: true })
    owned.push(taperedPocketBase)
    const taperedPocket = await runtime.pocket({ ...documentContext, base: taperedPocketBase, profile: square(2, 5), length: 10, direction: [0, 0, 1], reversed: true, taperAngle: 2 })
    owned.push(taperedPocket)
    await capture('pocket-tapered', taperedPocket, undefined, true)
    const throughAllPocketBase = await runtime.createBox({ ...documentContext, width: 10, length: 10, height: 10, center: [0, 0, 0], originOnCenter: true })
    owned.push(throughAllPocketBase)
    const throughAllPocket = await runtime.pocket({ ...documentContext, base: throughAllPocketBase, profile: square(1, 5), length: 1, direction: [0, 0, 1], throughAll: true })
    owned.push(throughAllPocket)
    await capture('pocket-through-all', throughAllPocket, undefined, true)
    const upToFacePocketBase = await runtime.createBox({ ...documentContext, width: 10, length: 10, height: 10, center: [0, 0, 0], originOnCenter: true })
    owned.push(upToFacePocketBase)
    const upToFacePocket = await runtime.pocket({ ...documentContext, base: upToFacePocketBase, profile: square(1, 5), length: 10, direction: [0, 0, 1], reversed: true })
    owned.push(upToFacePocket)
    await capture('pocket-up-to-face', upToFacePocket, undefined, true)
    const midplanePad = await runtime.pad({ ...documentContext, profile: square(2, 0), length: 6, direction: [0, 0, 1], symmetricToPlane: true })
    owned.push(midplanePad)
    await capture('pad-midplane', midplanePad, undefined, true)
    const linearPatternBase = await runtime.createBox({ ...documentContext, width: 0.8, length: 0.8, height: 0.8, center: [0, 0, 0], originOnCenter: true })
    owned.push(linearPatternBase)
    const linearPatternCopy1 = await runtime.applyPlacement({ ...documentContext, shape: linearPatternBase, placement: { translation: [0, 2, 0], rotationAxis: [0, 0, 1], rotationAngle: 0 } })
    owned.push(linearPatternCopy1)
    const linearPatternCopy2 = await runtime.applyPlacement({ ...documentContext, shape: linearPatternBase, placement: { translation: [0, 7, 0], rotationAxis: [0, 0, 1], rotationAngle: 0 } })
    owned.push(linearPatternCopy2)
    const linearPattern = await runtime.union({ ...documentContext, shapes: [linearPatternBase, linearPatternCopy1, linearPatternCopy2] })
    owned.push(linearPattern)
    await capture('linear-pattern-spacing', linearPattern)
    const polarPatternBase = await runtime.createBox({ ...documentContext, width: 0.8, length: 0.8, height: 0.8, center: [2, 0, 0], originOnCenter: true })
    owned.push(polarPatternBase)
    const polarPatternCopy1 = await runtime.applyPlacement({ ...documentContext, shape: polarPatternBase, placement: { translation: [0, 0, 0], rotationAxis: [0, 0, 1], rotationAngle: 30 } })
    owned.push(polarPatternCopy1)
    const polarPatternCopy2 = await runtime.applyPlacement({ ...documentContext, shape: polarPatternBase, placement: { translation: [0, 0, 0], rotationAxis: [0, 0, 1], rotationAngle: 75 } })
    owned.push(polarPatternCopy2)
    const polarPattern = await runtime.union({ ...documentContext, shapes: [polarPatternBase, polarPatternCopy1, polarPatternCopy2] })
    owned.push(polarPattern)
    await capture('polar-pattern-spacing', polarPattern)
    const stressStart = performance.now()
    let stressPeakShapeCount = runtime.capabilities().shapeCount
    for (let index = 0; index < 1000; index += 1) {
      const stressShape = await runtime.createBox({ ...documentContext, width: 0.1, length: 0.1, height: 0.1, center: [index * 0.2, 0, 0] })
      owned.push(stressShape)
      stressPeakShapeCount = Math.max(stressPeakShapeCount, runtime.capabilities().shapeCount)
    }
    const stressDurationMs = performance.now() - stressStart
    const triangleStressShape = await runtime.createSphere({ ...documentContext, radius: 100 })
    owned.push(triangleStressShape)
    const triangleStressPrecision = 0.01
    const triangleStart = performance.now()
    const triangleStressMesh = await runtime.mesh(triangleStressShape, triangleStressPrecision)
    const triangleStress = { radius: 100, precision: triangleStressPrecision, triangles: triangleStressMesh.indices.length / 3, vertices: triangleStressMesh.positions.length / 3, durationMs: performance.now() - triangleStart }
    if (triangleStress.triangles < 100_000 || triangleStress.vertices < 3 || !Number.isFinite(triangleStress.durationMs) || triangleStress.durationMs <= 0) throw new Error(`High-tessellation mesh budget was not reached: ${JSON.stringify(triangleStress)}`)
    const beforeRelease = { shapeCount: runtime.capabilities().shapeCount, kernelReferenceCount: runtime.capabilities().kernelReferenceCount }
    const durationMs = performance.now() - startedAt
    const performanceEvidence = { durationMs, operationCount: operations.length, averageOperationMs: durationMs / operations.length, peakShapeCount, stressObjectCount: 1000, stressDurationMs, stressPeakShapeCount, triangleStress }
    await Promise.all(owned.map((shape) => runtime.release(shape)))
    const afterRelease = { shapeCount: runtime.capabilities().shapeCount, kernelReferenceCount: runtime.capabilities().kernelReferenceCount }
    if (afterRelease.shapeCount !== 0 || afterRelease.kernelReferenceCount !== 0) throw new Error(`Shape ownership gate failed after release: ${JSON.stringify(afterRelease)}`)
    runtime.dispose()
    return { schemaVersion: 1, status: 'pass', browserId: 'chrome', geometryProvider: capabilities.provider, operations, beforeRelease, afterRelease, fcstdBrep, exchangeFormats, performance: performanceEvidence }
  } catch (error) {
    runtime.dispose()
    const durationMs = performance.now() - startedAt
    return { schemaVersion: 1, status: 'failed', browserId: 'chrome', geometryProvider: 'Bitbybit OCCT', operations, beforeRelease: { shapeCount: runtime.capabilities().shapeCount, kernelReferenceCount: runtime.capabilities().kernelReferenceCount }, afterRelease: { shapeCount: runtime.capabilities().shapeCount, kernelReferenceCount: runtime.capabilities().kernelReferenceCount }, performance: { durationMs, operationCount: operations.length, averageOperationMs: operations.length ? durationMs / operations.length : 0, peakShapeCount, stressObjectCount: 0, stressDurationMs: 0, stressPeakShapeCount: runtime.capabilities().shapeCount, triangleStress: { radius: 0, precision: 0, triangles: 0, vertices: 0, durationMs: 0 } }, error: error instanceof Error ? error.message : String(error) }
  }
}

run().then((report) => {
  ;(window as Window & { __bitbybitGeometryFeatureReport?: HarnessReport }).__bitbybitGeometryFeatureReport = report
  document.documentElement.dataset.status = report.status
  setStatus(JSON.stringify(report))
}).catch((error) => {
  document.documentElement.dataset.status = 'failed'
  setStatus(error instanceof Error ? error.message : String(error))
})

export {}
