import { readFile, writeFile } from 'node:fs/promises'
import { resolve } from 'node:path'

const root = resolve(new URL('..', import.meta.url).pathname)
const load = (path) => readFile(resolve(root, path), 'utf8').then(JSON.parse)
const outputPath = resolve(root, 'config/freecad-property-area-promotion.json')
const [inventory, success, failure, mutation, roundTrip, chrome, semantics, progress] = await Promise.all([
  load('config/freecad-property-area-inventory.json'),
  load('config/freecad-property-area-success.json'),
  load('config/freecad-property-area-failure.json'),
  load('config/freecad-property-area-mutation.json'),
  load('config/freecad-property-area-roundtrip.json'),
  load('config/chrome-property-area-verification.json'),
  load('config/freecad-native-property-semantics.json'),
  load('config/freecad-follow-up-task-progress.json'),
])
const fail = (message) => { throw new Error(`FreeCAD PropertyArea promotion generation failed: ${message}`) }
const requiredCompletedPhases = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
const completed = new Map(progress.completedTasks?.map((entry) => [entry.id, entry]) ?? [])
for (const phase of requiredCompletedPhases) if (!completed.has(`PROP-app-propertyarea-${phase}`)) fail(`phase ${phase} is not completed in the evidence ledger`)
if (inventory.status !== 'pass' || inventory.propertyType !== 'App::PropertyArea' || inventory.recordCount !== 1 || inventory.records?.[0]?.valueModel?.derived !== true || inventory.records[0].valueModel.writable !== false) fail('inventory evidence is invalid')
for (const [name, artifact] of Object.entries({ success, failure, mutation, roundTrip, chrome })) if (artifact.status !== 'pass') fail(`${name} evidence is not passing`)
const propertyType = semantics.types?.find(({ typeId }) => typeId === 'App::PropertyArea')
if (propertyType?.support !== 'native-editable-codec' || propertyType.recordCount !== 1 || propertyType.statusNames?.join(',') !== 'PropOutput,PropReadOnly') fail('global property semantics did not promote App::PropertyArea with its native status')
const opaque = semantics.supportSummary?.['opaque-fcstd-proxy']
const editable = semantics.supportSummary?.['native-editable-codec']
if (opaque?.typeCount !== 46 || opaque.recordCount !== 457 || editable?.typeCount !== 34 || editable.recordCount !== 4370) fail('global property support summary is not synchronized')
if (roundTrip.classification?.zeroUnknownDrift !== true || chrome.ui?.areaReadOnly !== true || chrome.persistence?.loadedAreaType !== 'App::PropertyArea' || chrome.persistence.loadedElementsType !== 'App::PropertyLinkSubList' || chrome.release?.workerTerminated !== true) fail('round-trip or browser closure evidence is incomplete')

const report = {
  schemaVersion: 1,
  status: 'pass',
  taskId: 'PROP-app-propertyarea-I',
  baseline: semantics.baseline,
  propertyType: 'App::PropertyArea',
  recordCount: 1,
  phaseEvidence: Object.fromEntries(requiredCompletedPhases.map((phase) => [phase, completed.get(`PROP-app-propertyarea-${phase}`).evidence])),
  promotion: {
    from: inventory.classification,
    to: propertyType.support,
    facadeValueModel: 'read-only-derived-mm^2-with-link-sub-list-input',
    inputType: 'App::PropertyLinkSubList',
    fcstdAreaElement: chrome.persistence.fcstdAreaElement,
    fcstdElementsElement: chrome.persistence.fcstdElementsElement,
    nativeRoundTripArea: roundTrip.classification.resavedArea,
    browserRoundTripArea: chrome.persistence.loadedArea,
    browserRoundTripElementCount: chrome.persistence.loadedElementCount,
    sourceGeometryPreserved: roundTrip.classification.sourceGeometryPreserved,
    zeroUnknownDrift: roundTrip.classification.zeroUnknownDrift,
  },
  exactBlockerSync: {
    nativeEditableTypes: editable.typeCount,
    nativeEditableRecords: editable.recordCount,
    opaqueTypes: opaque.typeCount,
    opaqueRecords: opaque.recordCount,
    exactPromotionReady: semantics.exactPromotionReady,
    exactBlocker: semantics.exactBlocker,
  },
  systemExact: false,
  generatedAt: new Date().toISOString(),
}
await writeFile(outputPath, `${JSON.stringify(report, null, 2)}\n`)
console.log(JSON.stringify({ status: 'freecad-property-area-promotion-generated', output: 'config/freecad-property-area-promotion.json', promotion: report.promotion, exactBlockerSync: report.exactBlockerSync }, null, 2))


