export type FcstdRoundTripDirection = 'freecad-web-freecad' | 'web-freecad-web'
export type FcstdRoundTripDifference = { path: string; expected: string; actual: string; classification: 'unknown' }
export type FcstdRoundTripResult = { schemaVersion: 1; id: string; direction: FcstdRoundTripDirection; status: 'pass' | 'fail-unknown-difference'; differences: FcstdRoundTripDifference[]; sourceFingerprint: string; receivedFingerprint: string; domains: string[] }

const normalize = (value: unknown): unknown => {
  if (Array.isArray(value)) return value.map(normalize)
  if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, entry]) => [key, normalize(entry)]))
  return value
}

export const fingerprintRoundTrip = (value: unknown) => JSON.stringify(normalize(value))

export const compareFcstdRoundTrip = (id: string, direction: FcstdRoundTripDirection, expected: unknown, received: unknown, domains: string[]): FcstdRoundTripResult => {
  const sourceFingerprint = fingerprintRoundTrip(expected)
  const receivedFingerprint = fingerprintRoundTrip(received)
  const differences = sourceFingerprint === receivedFingerprint ? [] : [{ path: id, expected: sourceFingerprint, actual: receivedFingerprint, classification: 'unknown' as const }]
  return { schemaVersion: 1, id, direction, status: differences.length === 0 ? 'pass' : 'fail-unknown-difference', differences, sourceFingerprint, receivedFingerprint, domains: [...new Set(domains)] }
}
