// Cherry player SDK — protected core loader.
// The .wasm carries YOUR key and YOUR domain allowlist; keep this folder together.
let corePromise = null

async function core(baseUrl) {
  if (corePromise) return corePromise
  corePromise = (async () => {
    if (!globalThis.Go) {
      await import(new URL('./wasm_exec.js', baseUrl).href)
    }
    const go = new globalThis.Go()
    const res = await fetch(new URL('./cherry-civ.wasm', baseUrl))
    const { instance } = await WebAssembly.instantiateStreaming(res, go.importObject)
    go.run(instance)
    return globalThis.__cherryCiv
  })()
  return corePromise
}

/** What a file needs before anything is decrypted: { protected, needsPasscode, sealedToKeyId, domains }. */
export async function inspectCiv(bytes, baseUrl = import.meta.url) {
  return (await core(baseUrl)).inspect(bytes)
}

/**
 * Open a protected .civ. Returns { ok:true, civ } or { ok:false, reason }.
 * The host is taken from the page, never from the caller — the allowlist is not the page's to relax.
 */
export async function openCiv(bytes, passcode = '', baseUrl = import.meta.url) {
  return (await core(baseUrl)).open(bytes, passcode, globalThis.location?.hostname ?? '')
}

/** The key id this build was stamped with — for "which player is this?" diagnostics. */
export async function playerKeyId(baseUrl = import.meta.url) {
  return (await core(baseUrl)).keyId()
}
