import {
  pipe,
  sortBy,
  toPairs,
  fromPairs,
  map,
  identity,
  cond,
  is,
  T,
} from "ramda"

// First declare the function
let sortObjectKeys

// Then define it
sortObjectKeys = cond([
  [is(Array), map((x) => sortObjectKeys(x))],
  [
    is(Object),
    pipe(
      toPairs,
      sortBy(([key]) => key),
      map(([key, val]) => [key, sortObjectKeys(val)]),
      fromPairs,
    ),
  ],
  [T, identity],
])
const hash = (str) => {
  // FNV-1a hash algorithm (32-bit)
  let hash = 2166136261 // FNV offset basis
  for (let i = 0; i < str.length; i++) {
    hash ^= str.charCodeAt(i)
    // Multiply by the FNV prime
    hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24)
  }

  // Convert to alphanumeric string (base 36)
  return (hash >>> 0).toString(36)
}
const createStableHash = pipe(sortObjectKeys, JSON.stringify, hash)
export default createStableHash
export { createStableHash }
