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-font-promotion.json')
const [inventory, success, failure, mutation, roundTrip, chrome, semantics, progress] = await Promise.all([
  load('config/freecad-property-font-inventory.json'),
  load('config/freecad-property-font-success.json'),
  load('config/freecad-property-font-failure.json'),
  load('config/freecad-property-font-mutation.json'),
  load('config/freecad-property-font-roundtrip.json'),
  load('config/chrome-property-font-verification.json'),
  load('config/freecad-native-property-semantics.json'),
  load('config/freecad-follow-up-task-progress.json'),
])
const fail = (message) => { throw new Error(`FreeCAD PropertyFont 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-propertyfont-${phase}`)) fail(`phase ${phase} is not completed in the evidence ledger`)
if (inventory.status !== 'pass' || inventory.propertyType !== 'App::PropertyFont' || inventory.recordCount !== 2 || inventory.objectTypeCount !== 2 || inventory.records?.filter(({ valueModel }) => valueModel?.writable === true).length !== 2) 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::PropertyFont')
if (propertyType?.support !== 'native-editable-codec' || propertyType.recordCount !== 2 || propertyType.objectTypeCount !== 2 || propertyType.statusNames?.length !== 0) fail('global property semantics did not promote App::PropertyFont')
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 || roundTrip.classification.fontResourceBoundary !== 'font family name persists in FCStd; font files and availability remain presentation-only' || chrome.persistence?.loadedType !== 'App::PropertyFont' || chrome.persistence.fcstdElement !== 'String' || chrome.persistence.fcstdValue !== 'Noto Sans CJK SC' || chrome.resource?.released !== true || chrome.release?.workerTerminated !== true) fail('round-trip or browser closure evidence is incomplete')

const report = {
  schemaVersion: 1,
  status: 'pass',
  taskId: 'PROP-app-propertyfont-I',
  baseline: semantics.baseline,
  propertyType: 'App::PropertyFont',
  recordCount: 2,
  phaseEvidence: Object.fromEntries(requiredCompletedPhases.map((phase) => [phase, completed.get(`PROP-app-propertyfont-${phase}`).evidence])),
  promotion: {
    from: inventory.classification,
    to: propertyType.support,
    facadeValueModel: 'bounded-utf8-font-family-string-with-native-string-fcstd-payload',
    writableRecords: 2,
    objectTypeCount: propertyType.objectTypeCount,
    fcstdElement: chrome.persistence.fcstdElement,
    defaultValue: success.phases.default.value,
    nativeRoundTripValue: roundTrip.classification.resavedValue,
    browserRoundTripValue: chrome.persistence.loadedValue,
    fontResourceBoundary: roundTrip.classification.fontResourceBoundary,
    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-font-promotion-generated', output: 'config/freecad-property-font-promotion.json', promotion: report.promotion, exactBlockerSync: report.exactBlockerSync }, null, 2))


