// connection.svelte.ts is now a thin shim over the net-state store (netstate.svelte.ts, O2). It keeps
// the historical surface — `connection.online` plus the report/probe helpers the transport and the live
// stream call — so those consumers are unchanged while the single net-state machine drives everything
// underneath. `online` is true only in the fully-online machine state; a failing call or dropped stream
// reports via reportOffline, which enters the connecting hysteresis buffer once, and the store's probe
// then decides whether it becomes offline — so a transient blip never flips the chrome.

import {
  netState,
  emit,
  registerProbe as registerNetProbe,
  checkReachable as checkNetReachable,
  resetNetState,
} from './netstate.svelte';

export const connection = {
  /** online is true when the app can reach the gateway (the fully-online machine state). */
  get online(): boolean {
    return netState.online;
  },
};

/** registerProbe installs the reachability probe the store's watcher fires while connecting/offline.
 *  The transport wires a cheap authenticated read; it should reject when there is no session. */
export function registerProbe(fn: () => Promise<void>): void {
  registerNetProbe(fn);
}

/** checkReachable runs the reachability probe once, bounded by timeoutMs, and reports whether the
 *  gateway answered — a single attempt for the cold-start / recovery decision. */
export function checkReachable(timeoutMs: number): Promise<boolean> {
  return checkNetReachable(timeoutMs);
}

/** reportOnline marks the gateway reachable — a successful round-trip heals the machine to online. */
export function reportOnline(): void {
  emit('callOk');
}

/** reportOffline reports a failing call or dropped stream. It opens the connecting hysteresis buffer
 *  once (only from online); the store's probe then decides whether it becomes offline. */
export function reportOffline(): void {
  if (netState.online) emit('callFailed');
}

/** resetConnection restores the online state and stops the watcher (e.g. on logout). */
export function resetConnection(): void {
  resetNetState();
}
