import { deviceTargetHash, isInRollout } from "healkite-protocol/bucket";
import { manifestSigningPayload, manifestSigningPayloadV2 } from "healkite-protocol/manifest-signing";
import { pushTopic } from "healkite-protocol/push";
import { AppState } from "react-native";
import { applyLivePatch, holdLivePatch, preserve, restored, subscribeLivePatch, usePreservedState, wasLivePatched } from "./live";
import Native from "./NativeHealkite";

export interface HealkiteConfig {
  cdnUrl: string;
  /** Backup CDN (HealkiteCdnFallbackUrl / healkite_cdn_fallback_url), tried when cdnUrl is unreachable or failing. */
  cdnFallbackUrl?: string;
  channel: string;
  runtimeVersion: string;
  binaryVersion: string;
  deviceId: string;
  platform: "ios" | "android";
  /** True when a public key is baked into the binary: unsigned updates are refused. */
  signingRequired: boolean;
  /** True when the server's manifest key is baked in: unsigned/forged/replayed manifests are refused. */
  manifestSigningRequired: boolean;
  /** The channel from the app's config (channel differs while a PR preview is open). */
  baseChannel?: string;
  /** PR preview channel key in use, or null. */
  previewChannel?: string | null;
}

export interface HealkiteState {
  /** Bundle running in this process: sha256 or "embedded". */
  running: string;
  current: string | null;
  previous: string | null;
  /** Staged bundle that will run on next launch (or is on its trial launch). */
  pending: string | null;
  pendingLaunched: boolean;
  failed: string[];
  lastRollback: { sha256: string; at: number } | null;
  clearOnNextLaunch: boolean;
  /** How the last update was installed: "patch" (diff) or "full" download. */
  lastInstallMethod: "patch" | "full" | null;
}

/** Subset of the protocol v1 manifest the SDK needs (unknown fields ignored). */
interface ManifestRelease {
  id: string;
  label: string;
  sha256: string;
  url: string;
  size: number;
  mandatory?: boolean;
  description?: string;
  signature?: string;
  patches?: Record<string, { url: string; size: number; sha256: string; signature?: string }>;
}
interface Manifest {
  protocolVersion: number;
  channel: string;
  platform: string;
  runtimeVersion: string;
  generatedAt: number;
  manifestSignature?: string;
  /** Signature that also covers `targeted` (see manifestSigningPayloadV2). */
  manifestSignatureV2?: string;
  release: ManifestRelease | null;
  /** Releases for specific devices (matched by deviceTargetHash), newest first. */
  targeted?: Array<ManifestRelease & { devices: string[] }>;
  rollout?: { pct: number; salt: string };
  installPolicy?: { mode: "nextLaunch" | "onBackground" | "immediate"; minBackgroundSec?: number };
  killSwitch?: { title: string; message: string; url?: string } | null;
  endpoints?: { ingest?: string };
  eventSampleRate?: number;
}

export type CheckResult =
  | { status: "UPDATE_AVAILABLE"; release: ManifestRelease; url: string; manifest: Manifest; viaFallback?: boolean }
  | { status: "UP_TO_DATE" }
  | { status: "NOT_IN_ROLLOUT"; release: ManifestRelease }
  | { status: "SKIPPED_FAILED"; release: ManifestRelease }
  | { status: "ROLLBACK_TO_EMBEDDED" }
  | { status: "NO_RELEASE" };

export type SyncResult =
  | { status: "UP_TO_DATE" | "NOT_IN_ROLLOUT" | "SKIPPED_FAILED" | "NO_RELEASE" }
  | { status: "UPDATE_INSTALLED"; label: string; appliesOn: "nextLaunch" | "now" }
  | { status: "ROLLBACK_SCHEDULED" }
  | { status: "ERROR"; error: string };

let cachedConfig: HealkiteConfig | null = null;

export function getConfig(): HealkiteConfig {
  cachedConfig ??= JSON.parse(Native.getConfigJson()) as HealkiteConfig;
  return cachedConfig;
}

export function getState(): HealkiteState {
  return JSON.parse(Native.getStateJson()) as HealkiteState;
}

export function manifestUrl(config: HealkiteConfig = getConfig()): string {
  const base = config.cdnUrl.replace(/\/+$/, "");
  return `${base}/m/${config.channel}/${config.platform}/${config.runtimeVersion}.json`;
}

function absolute(url: string, config: HealkiteConfig): string {
  return /^https?:\/\//.test(url) ? url : `${config.cdnUrl.replace(/\/+$/, "")}/${url.replace(/^\/+/, "")}`;
}

const trimBase = (u: string) => u.replace(/\/+$/, "");

/** Download URL, moved to the backup CDN when the primary failed (files are hash- and signature-checked either way). */
function fileUrl(url: string, config: HealkiteConfig, viaFallback: boolean): string {
  const abs = absolute(url, config);
  if (!viaFallback || !config.cdnFallbackUrl) return abs;
  const from = trimBase(config.cdnUrl);
  return abs.startsWith(`${from}/`) ? trimBase(config.cdnFallbackUrl) + abs.slice(from.length) : abs;
}

/** Whether the last manifest came from the backup CDN. */
let lastViaFallback = false;

/** The last manifest seen in this process (tells us where to send events). */
let lastManifest: Manifest | null = null;

export interface KillSwitch {
  title: string;
  message: string;
  url?: string;
}

let killSwitch: KillSwitch | null = null;
const killSwitchListeners = new Set<(k: KillSwitch | null) => void>();

/** Maintenance message from the latest manifest (null when the app should run normally). */
export function getKillSwitch(): KillSwitch | null {
  return killSwitch;
}

/** Called whenever the kill switch changes. Returns an unsubscribe function. */
export function subscribeKillSwitch(listener: (k: KillSwitch | null) => void): () => void {
  killSwitchListeners.add(listener);
  return () => killSwitchListeners.delete(listener);
}

function updateKillSwitch(next: KillSwitch | null): void {
  if (JSON.stringify(next) === JSON.stringify(killSwitch)) return;
  killSwitch = next;
  for (const l of killSwitchListeners) l(next);
}

const STALE = Symbol("stale manifest");

async function fetchManifest(config: HealkiteConfig): Promise<Manifest | null | typeof STALE> {
  // `Cache-Control: no-cache` makes the device revalidate (ETag → 304) instead of
  // reusing its local copy for max-age; the CDN edge still serves from its cache.
  // Don't use fetch's `cache: "no-cache"`: RN's polyfill appends a timestamp to the
  // URL, which would bypass the CDN on every check.
  const init = { headers: { accept: "application/json", "cache-control": "no-cache" } };
  const fallback = config.cdnFallbackUrl ? trimBase(config.cdnFallbackUrl) : "";
  let res: Response | null = null;
  lastViaFallback = false;
  try {
    res = await fetch(manifestUrl(config), init);
  } catch (e) {
    if (!fallback) throw e;
  }
  // Primary CDN down (network error or 5xx): the backup serves the same signed files.
  if (fallback && (!res || res.status >= 500)) {
    res = await fetch(manifestUrl({ ...config, cdnUrl: fallback }), init);
    lastViaFallback = true;
  }
  if (!res) throw new Error("Manifest request failed");
  if (res.status === 404) return null;
  if (!res.ok) throw new Error(`Manifest request failed: ${res.status}`);
  const manifest = (await res.json()) as Manifest;
  if (manifest.protocolVersion !== 1) throw new Error(`Unsupported protocol ${manifest.protocolVersion}`);
  // v2 covers per-device releases too; with only a v1 signature, targeted entries are unverified.
  const v2 = !!manifest.manifestSignatureV2;
  const verdict = Native.verifyManifest(
    v2 ? manifestSigningPayloadV2(manifest) : manifestSigningPayload(manifest),
    (v2 ? manifest.manifestSignatureV2 : manifest.manifestSignature) ?? "",
    manifest.generatedAt ?? 0,
  );
  if (verdict === "invalid") throw new Error("Manifest signature is invalid");
  // An older manifest than one already accepted (lagging CDN edge or a replay): ignore it.
  if (verdict === "stale") return STALE;
  if (verdict === "ok" && !v2) manifest.targeted = [];
  lastManifest = manifest;
  updateKillSwitch(manifest.killSwitch ?? null);
  return manifest;
}

/** Fetch the channel manifest and decide what this device should do. Never throws on 404. */
export async function checkForUpdate(): Promise<CheckResult> {
  const config = getConfig();
  const manifest = await fetchManifest(config);
  if (manifest === STALE) return { status: "UP_TO_DATE" };
  // A closed preview (nothing published there any more): go back to the app's own channel.
  if (config.previewChannel && (!manifest || !manifest.release)) {
    setPreview("");
    return checkForUpdate();
  }
  if (!manifest) return { status: "NO_RELEASE" };
  const state = getState();
  // A release sent to this specific device wins over the channel release (and skips the rollout %).
  const mine = deviceTargetHash(config.deviceId);
  const targeted = (manifest.targeted ?? []).find((t) => Array.isArray(t.devices) && t.devices.includes(mine));
  if (targeted) {
    if (targeted.sha256 === state.running || targeted.sha256 === state.pending) return { status: "UP_TO_DATE" };
    if (state.failed.includes(targeted.sha256)) return { status: "SKIPPED_FAILED", release: targeted };
    return { status: "UPDATE_AVAILABLE", release: targeted, url: fileUrl(targeted.url, config, lastViaFallback), manifest, viaFallback: lastViaFallback };
  }
  const release = manifest.release;
  if (!release) {
    const onOta = state.running !== "embedded" || state.pending !== null || state.current !== null;
    return onOta && !state.clearOnNextLaunch ? { status: "ROLLBACK_TO_EMBEDDED" } : { status: "UP_TO_DATE" };
  }
  if (release.sha256 === state.running || release.sha256 === state.pending) return { status: "UP_TO_DATE" };
  if (state.failed.includes(release.sha256)) return { status: "SKIPPED_FAILED", release };
  if (manifest.rollout && !isInRollout(config.deviceId, manifest.rollout.salt, manifest.rollout.pct)) {
    return { status: "NOT_IN_ROLLOUT", release };
  }
  return { status: "UPDATE_AVAILABLE", release, url: fileUrl(release.url, config, lastViaFallback), manifest, viaFallback: lastViaFallback };
}

/**
 * Confirm the running bundle works. Call once the first screen has rendered.
 * If a freshly installed bundle never reaches this point, Healkite rolls it
 * back automatically on the next launch.
 */
export function notifyAppReady(): HealkiteState {
  return JSON.parse(Native.notifyAppReady()) as HealkiteState;
}

export function restart(): void {
  Native.restart();
}

export interface SyncOptions {
  /** Override the manifest's install policy. */
  installMode?: "nextLaunch" | "immediate";
  /** Also call notifyAppReady() first (default true). */
  notifyReady?: boolean;
}

const launchedAt = Date.now();
let sessionSent = false;

type ErrorHandler = (error: unknown, isFatal?: boolean) => void;
interface ErrorUtilsLike {
  getGlobalHandler(): ErrorHandler | undefined;
  setGlobalHandler(handler: ErrorHandler): void;
}
let errorHandlerInstalled = false;
let stacksSent = 0;

/**
 * Records uncaught JS errors (fatal = the app is about to crash) against the
 * running bundle, so Guarded Releases see crashes that happen after startup.
 * Installed automatically when the SDK is imported; chains to the previous handler.
 */
export function installErrorHandler(): void {
  if (errorHandlerInstalled) return;
  const eu = (globalThis as { ErrorUtils?: ErrorUtilsLike }).ErrorUtils;
  if (!eu?.getGlobalHandler || !eu.setGlobalHandler) return;
  const previous = eu.getGlobalHandler();
  eu.setGlobalHandler((error, isFatal) => {
    try {
      const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
      // A few stacks per launch are enough to find the change that broke a release (see `healkite blame`).
      const stack = error instanceof Error && typeof error.stack === "string" && stacksSent++ < 5 ? error.stack.slice(0, 1500) : undefined;
      Native.recordEvent(
        JSON.stringify({
          t: Date.now(),
          type: "error",
          name: isFatal ? "fatal" : "js",
          data: { sha256: getState().running, message: message.slice(0, 300), ...(stack ? { stack } : {}) },
        }),
      );
      if (isFatal) void flushDebugLogs();
    } catch {
      // never interfere with the app's own crash handling
    }
    previous?.(error, isFatal);
  });
  errorHandlerInstalled = true;
}

const EVENT_NAME = /^[A-Za-z0-9_.-]{1,64}$/;

/**
 * Records an app-defined event (e.g. "checkout_success") against the running
 * bundle. Guarded Releases can halt a rollout when events per session drop vs
 * the previous release. Stored natively; sent with the next batch.
 */
export function trackEvent(name: string, props?: Record<string, string | number | boolean>): boolean {
  if (!EVENT_NAME.test(name)) return false;
  const data: Record<string, string | number | boolean> = { sha256: getState().running };
  for (const [k, v] of Object.entries(props ?? {}).slice(0, 10)) {
    if (k !== "sha256" && ["string", "number", "boolean"].includes(typeof v)) data[k.slice(0, 40)] = typeof v === "string" ? v.slice(0, 100) : v;
  }
  try {
    return Native.recordEvent(JSON.stringify({ t: Date.now(), type: "custom", name, data }));
  } catch {
    return false;
  }
}

// ---------- production debugging (logpoints) ----------

interface DebugLog {
  sessionId: string;
  t: number;
  lp: string;
  data: Record<string, unknown>;
}
const debugQueue: DebugLog[] = [];
const debugCounts = new Map<string, number>();
let debugTimer: ReturnType<typeof setTimeout> | null = null;
const SENSITIVE_KEY = /pass(word)?|secret|token|auth|cookie|session|card|cvv|cvc|ssn|pin\b|otp/i;
/** Per logpoint per launch: a logpoint inside a render loop must not flood the network. */
const MAX_LOGS_PER_LOGPOINT = 50;

/** JSON-safe copy of captured values: depth/size limited, secrets by key name redacted, cycles cut. */
export function captureValue(value: unknown, depth = 0, seen = new WeakSet<object>()): unknown {
  if (value === undefined) return "undefined";
  if (value === null || typeof value === "boolean") return value;
  if (typeof value === "number") return Number.isFinite(value) ? value : String(value);
  if (typeof value === "bigint") return `${value}n`;
  if (typeof value === "string") return value.length > 300 ? `${value.slice(0, 300)}…` : value;
  if (typeof value === "function") return `[function ${value.name || "anonymous"}]`;
  if (typeof value === "symbol") return value.toString();
  if (value instanceof Error) return { error: `${value.name}: ${value.message}`.slice(0, 300) };
  if (value instanceof Date) return value.toISOString();
  if (typeof value !== "object") return String(value);
  if (seen.has(value)) return "[circular]";
  if (depth >= 3) return Array.isArray(value) ? `[array(${value.length})]` : "[object]";
  seen.add(value);
  if (Array.isArray(value)) {
    const items = value.slice(0, 20).map((v) => captureValue(v, depth + 1, seen));
    return value.length > 20 ? [...items, `… ${value.length - 20} more`] : items;
  }
  const out: Record<string, unknown> = {};
  for (const [k, v] of Object.entries(value).slice(0, 30)) out[k] = SENSITIVE_KEY.test(k) ? "[redacted]" : captureValue(v, depth + 1, seen);
  return out;
}

function debugLogsUrl(): string | null {
  const ingest = lastManifest?.endpoints?.ingest;
  return ingest ? ingest.replace(/\/v1\/ingest$/, "/v1/debug-logs") : null;
}

/** Called by logpoints the Healkite Babel plugin inserts into a debug build. Never throws. */
function hkLog(sessionId: string, lp: string, capture: () => Record<string, unknown>): void {
  try {
    const key = `${sessionId}:${lp}`;
    const n = debugCounts.get(key) ?? 0;
    if (n >= MAX_LOGS_PER_LOGPOINT || debugQueue.length >= 200) return;
    debugCounts.set(key, n + 1);
    let values: Record<string, unknown>;
    try {
      values = capture();
    } catch (e) {
      values = { __error: String((e as Error)?.message ?? e) };
    }
    debugQueue.push({ sessionId, t: Date.now(), lp, data: captureValue(values) as Record<string, unknown> });
    debugTimer ??= setTimeout(() => {
      debugTimer = null;
      void flushDebugLogs();
    }, 2000);
  } catch {
    // never break the app being debugged
  }
}

/** Sends captured logpoint values (debug builds only). Keeps them for a later try on network failure. */
export async function flushDebugLogs(): Promise<void> {
  if (!debugQueue.length) return;
  const url = debugLogsUrl();
  if (!url) {
    debugTimer ??= setTimeout(() => {
      debugTimer = null;
      void flushDebugLogs();
    }, 5000);
    return;
  }
  const config = getConfig();
  const batch = debugQueue.splice(0, 50);
  const bySession = new Map<string, DebugLog[]>();
  for (const l of batch) bySession.set(l.sessionId, [...(bySession.get(l.sessionId) ?? []), l]);
  for (const [sessionId, logs] of bySession) {
    try {
      const res = await fetch(url, {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ channel: config.channel, deviceId: config.deviceId, sessionId, logs: logs.map(({ t, lp, data }) => ({ t, lp, data })) }),
      });
      if (res.status >= 500) throw new Error(`debug logs ${res.status}`);
    } catch {
      if (debugQueue.length < 150) debugQueue.unshift(...logs);
      return;
    }
  }
  if (debugQueue.length) void flushDebugLogs();
}

try {
  (globalThis as { __hkLog?: typeof hkLog }).__hkLog = hkLog;
} catch {
  // frozen global (tests): logpoints just won't report
}

try {
  installErrorHandler();
  // Send queued events when the app goes to the background (no extra wake-ups).
  AppState?.addEventListener?.("change", (state) => {
    if (state === "background") {
      void flushEvents();
      void flushDebugLogs();
    }
  });
} catch {
  // native module unavailable (tests without the mock): skip
}

/**
 * Sends queued native events (installs, rollbacks, errors…) plus one session
 * ping per launch to the ingest endpoint named in the manifest. Never throws;
 * on network failure the events go back into the native queue.
 */
export async function flushEvents(): Promise<void> {
  const ingest = lastManifest?.endpoints?.ingest;
  if (!ingest) return;
  const config = getConfig();
  const rate = lastManifest?.eventSampleRate ?? 1;
  const sampledIn = rate >= 1 || isInRollout(config.deviceId, "healkite-events", Math.round(rate * 100));
  const events = JSON.parse(Native.drainEventsJson()) as unknown[];
  if (!sampledIn || (events.length === 0 && sessionSent)) return;

  const body = {
    protocolVersion: 1,
    channel: config.channel,
    deviceId: config.deviceId,
    platform: config.platform,
    binaryVersion: config.binaryVersion,
    runtimeVersion: config.runtimeVersion,
    bundle: getState().running,
    session: sessionSent ? undefined : { start: launchedAt, durationMs: 0, crashed: false, jsErrors: 0, ready: true },
    events,
  };
  try {
    const res = await fetch(ingest, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(body),
    });
    // 4xx means the batch itself is bad: drop it rather than retry forever.
    if (res.status >= 500) throw new Error(`ingest ${res.status}`);
    sessionSent = true;
  } catch {
    if (events.length) Native.requeueEventsJson(JSON.stringify(events));
  }
}

/** One-call integration: confirm health, check, download, stage (and optionally restart). */
export async function sync(options: SyncOptions = {}): Promise<SyncResult> {
  try {
    return await syncInner(options);
  } finally {
    await flushEvents();
  }
}

async function syncInner(options: SyncOptions): Promise<SyncResult> {
  try {
    if (options.notifyReady !== false) notifyAppReady();
    const check = await checkForUpdate();
    switch (check.status) {
      case "UP_TO_DATE":
      case "NOT_IN_ROLLOUT":
      case "SKIPPED_FAILED":
      case "NO_RELEASE":
        return { status: check.status };
      case "ROLLBACK_TO_EMBEDDED":
        Native.clearUpdates();
        return { status: "ROLLBACK_SCHEDULED" };
      case "UPDATE_AVAILABLE": {
        const config = getConfig();
        const running = getState().running;
        const patch = check.release.patches?.[running];
        const install = (viaFallback: boolean) =>
          Native.installUpdate(
            check.release.sha256,
            fileUrl(check.release.url, config, viaFallback),
            check.release.signature ?? "",
            patch
              ? JSON.stringify({ from: running, url: fileUrl(patch.url, config, viaFallback), sha256: patch.sha256, size: patch.size, signature: patch.signature })
              : "",
          );
        try {
          await install(!!check.viaFallback);
        } catch (e) {
          // Manifest came from the primary but the download failed: try the backup CDN once.
          if (check.viaFallback || !config.cdnFallbackUrl) throw e;
          await install(true);
        }
        const mode =
          options.installMode ??
          (check.release.mandatory ? "immediate" : check.manifest.installPolicy?.mode === "immediate" ? "immediate" : "nextLaunch");
        if (mode === "immediate") {
          // Live patch: reload at a safe moment and hand the registered state across (after flushEvents()).
          setTimeout(() => void applyLivePatch(), 250);
          return { status: "UPDATE_INSTALLED", label: check.release.label, appliesOn: "now" };
        }
        return { status: "UPDATE_INSTALLED", label: check.release.label, appliesOn: "nextLaunch" };
      }
    }
  } catch (e) {
    return { status: "ERROR", error: e instanceof Error ? e.message : String(e) };
  }
}

export { KillSwitchGate, useKillSwitch } from "./KillSwitch";
export { applyLivePatch, holdLivePatch, preserve, restored, subscribeLivePatch, usePreservedState, wasLivePatched } from "./live";
export type { LivePatchPhase } from "./live";
export { PreviewBanner, usePreview } from "./Preview";

/* ------------------------------------------------------------------ PR previews */

const previewListeners = new Set<(p: PreviewInfo | null) => void>();
export interface PreviewInfo {
  channel: string;
  baseChannel: string;
}

function setPreview(channel: string): void {
  cachedConfig = JSON.parse(Native.setPreviewChannel(channel)) as HealkiteConfig;
  const p = getPreview();
  for (const l of previewListeners) l(p);
}

/** The PR preview this app is running, or null. */
export function getPreview(): PreviewInfo | null {
  const c = getConfig();
  return c.previewChannel ? { channel: c.previewChannel, baseChannel: c.baseChannel ?? c.channel } : null;
}

export function subscribePreview(listener: (p: PreviewInfo | null) => void): () => void {
  previewListeners.add(listener);
  return () => previewListeners.delete(listener);
}

/** Extracts a preview channel key from a link, or null when the link isn't a Healkite preview. */
export function previewChannelFromUrl(url: string): string | null {
  const m = /[?&](?:healkite-preview|channel)=([a-z0-9][a-z0-9-]{2,99})(?:&|#|$)/.exec(url);
  if (!m) return null;
  return /healkite-preview/.test(url) ? m[1]! : null;
}

/**
 * Open a PR preview from a deep link (e.g. myapp://healkite-preview?channel=pr-123-abc): the app switches
 * to that channel, installs its bundle and restarts. Returns false for links that aren't previews,
 * so you can pass every incoming URL through it.
 *   Linking.addEventListener("url", ({ url }) => Healkite.openPreview(url));
 *   Linking.getInitialURL().then((url) => url && Healkite.openPreview(url));
 */
export async function openPreview(urlOrChannel: string): Promise<boolean> {
  const channel = /^[a-z0-9][a-z0-9-]{2,99}$/.test(urlOrChannel) ? urlOrChannel : previewChannelFromUrl(urlOrChannel);
  if (!channel) return false;
  if (getConfig().previewChannel === channel) return true;
  setPreview(channel);
  await sync({ installMode: "immediate", notifyReady: false });
  return true;
}

/** Leave the preview: back to the app's channel, its current release (or the built-in bundle), and restart. */
export async function exitPreview(): Promise<void> {
  if (!getConfig().previewChannel) return;
  setPreview("");
  const r = await sync({ installMode: "immediate", notifyReady: false });
  // An update restarts by itself; otherwise restart so the built-in/current bundle loads now.
  if (r.status === "ROLLBACK_SCHEDULED" || r.status === "UP_TO_DATE" || r.status === "NO_RELEASE") restart();
}

/**
 * Instant hotfix: the FCM topic this device should subscribe to. Healkite sends one silent message to
 * it when you push a hotfix, e.g. with @react-native-firebase/messaging:
 *   await messaging().subscribeToTopic(Healkite.getPushTopic());
 */
export function getPushTopic(): string {
  const c = getConfig();
  return pushTopic(c.channel, c.platform, c.runtimeVersion);
}

/**
 * Handle a push message (foreground or background). Returns false for messages that aren't from
 * Healkite, so you can pass every message through it:
 *   messaging().setBackgroundMessageHandler((m) => Healkite.handlePush(m.data));
 *   messaging().onMessage((m) => Healkite.handlePush(m.data));
 */
export async function handlePush(data: Record<string, unknown> | undefined | null): Promise<boolean> {
  const kind = data?.healkite;
  if (kind !== "sync" && kind !== "immediate") return false;
  await sync({ installMode: kind === "immediate" ? "immediate" : undefined, notifyReady: false });
  return true;
}

const Healkite = {
  getConfig,
  openPreview,
  exitPreview,
  getPreview,
  subscribePreview,
  getPushTopic,
  handlePush,
  getState,
  checkForUpdate,
  notifyAppReady,
  restart,
  sync,
  manifestUrl,
  flushEvents,
  getKillSwitch,
  subscribeKillSwitch,
  installErrorHandler,
  trackEvent,
  preserve,
  restored,
  wasLivePatched,
  holdLivePatch,
  applyLivePatch,
  subscribeLivePatch,
  usePreservedState,
};
export default Healkite;
