/* The boot census.

   Every command the app issues passes one counter here — src/lib/api.js on
   the way into `invoke`, and src/lib/events.js on the way into `listen`,
   which is an invoke like any other (Tauri registers the subscription over
   the same bridge). A plugin that registers its own listener through
   @tauri-apps/api directly goes past both doors and is not counted — the
   media card's and the transfer notice's `addPluginListener` are the two —
   so what this measures is the app's own traffic. The question it answers
   is the one nobody could answer before: how much of the world does the
   app ask for before it has drawn anything?

   It seals at the first frame the shell paints and never re-opens, so a
   probe landing a second and a half later still reads the launch. That is
   what tests/mobile/smoke.mjs holds a budget against — the point is to
   catch a round that loads the world at boot, not to police milliseconds.

   A plain object, deliberately: this module is shared with the desktop, it
   imports nothing, and it must not throw. On the desktop nothing seals it
   and nothing reads it. */
export const boot = {
    /** the moment the chain starts — the shell's onMount sets it */
    t0: 0,
    /** every invoke and every listen, until the seal */
    calls: 0,
    /** how many of them left in the shell's own first turn, before any
     *  answer could have come back. A chain that waits on itself can only
     *  issue its first call there, so this is the one number that says
     *  whether the boot chain is still going out in one round; the shell
     *  latches it at the end of onMount. -1 until it does. */
    sync: -1,
    /** the first hundred and twenty of them, in the order they went out —
     *  past any budget the walk holds, so "is X at boot?" is never
     *  answered by a list that stopped short */
    cmds: [],
    /** onMount → the first frame the app could have drawn into */
    frameMs: null,
    /** onMount → lib.loaded, which is what Home waits for */
    libMs: null,
    sealed: false,
};

export function countBoot(cmd) {
    if (boot.sealed) return;
    boot.calls++;
    if (boot.cmds.length < 120) boot.cmds.push(cmd);
}

export function sealBoot() {
    if (boot.sealed) return;
    boot.sealed = true;
    try { boot.frameMs = Math.round(performance.now() - boot.t0); } catch { /* a webview without the timer */ }
}
