import { finishStartup } from "./profiler";
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 { createModules } from "./modules";
import { applyLivePatch, holdLivePatch, preserve, restored, subscribeLivePatch, usePreservedState, wasLivePatched } from "./live";
import Native from "./NativeHealkite";
import { getPromptHandler, type UpdateInfo } from "./prompt-core";
import { featuresInUse, markFeature } from "./usage";
import { SDK_VERSION } from "./sdk-version";

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;
  /** Release label ("v12") per bundle sha256, for bundles that can still run. Missing on binaries built with SDK < 0.6. */
  labels?: Record<string, string>;
}

/** 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;
  /** Show the app's update prompt (<UpdatePrompt />) first. */
  prompt?: 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;
      /** "onResume": when the user comes back to the app (installMode "onBackground"). */
      appliesOn: "nextLaunch" | "now" | "onResume";
      /** The update prompt is showing; it applies when the user accepts (or on next launch). */
      prompted?: boolean;
    }
  /** The update prompt is asking before downloading (<UpdatePrompt askBeforeDownload />). */
  | { status: "AWAITING_USER"; label: string }
  | { 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;
}

/* ------------------------------------------------------------------ version info */

export interface UpdateVersion {
  /** Release label from the dashboard/CLI ("v12"); null when not known yet. */
  label: string | null;
  sha256: string;
  /** First 7 characters of sha256. */
  shortId: string;
}

export interface VersionInfo {
  /** Store version of the binary, e.g. "2.4.0 (112)". */
  appVersion: string;
  runtimeVersion: string;
  /** Channel in use (the PR preview channel while a preview is open). */
  channel: string;
  /** The OTA update running now, or null while the bundle built into the binary runs. */
  update: UpdateVersion | null;
  /** An update that is downloaded and applies on the next start, or null. */
  pending: UpdateVersion | null;
  /** One line for a settings or about screen: "2.4.0 (112) · v12", or "2.4.0 (112)" with no update. */
  text: string;
}

/** Labels learned in this process (also kept here when the binary's native code can't store them). */
const knownLabels = new Map<string, string>();
const versionListeners = new Set<() => void>();

function notifyVersion(): void {
  for (const l of versionListeners) l();
}

/** Stores a bundle's release label natively (when the binary supports it) and in memory. */
function rememberLabel(sha256: string, label: string | undefined): void {
  if (!label || knownLabels.get(sha256) === label) return;
  knownLabels.set(sha256, label);
  try {
    if (typeof Native.setReleaseLabel === "function") Native.setReleaseLabel(sha256, label);
  } catch {
    // older binaries: the in-memory label still works for this session
  }
  notifyVersion();
}

/** App version, the running OTA update and any update waiting for the next start. */
export function getVersionInfo(): VersionInfo {
  markFeature("version-line");
  const config = getConfig();
  const state = getState();
  const describe = (sha: string | null): UpdateVersion | null =>
    !sha || sha === "embedded" ? null : { label: state.labels?.[sha] ?? knownLabels.get(sha) ?? null, sha256: sha, shortId: sha.slice(0, 7) };
  const update = describe(state.running);
  const pending = state.pending && state.pending !== state.running ? describe(state.pending) : null;
  const text = update ? `${config.binaryVersion} · ${update.label ?? update.shortId}` : config.binaryVersion;
  return { appVersion: config.binaryVersion, runtimeVersion: config.runtimeVersion, channel: config.channel, update, pending, text };
}

/** Called when the version info may have changed (an update was staged or its label became known). */
export function subscribeVersionInfo(listener: () => void): () => void {
  versionListeners.add(listener);
  return () => versionListeners.delete(listener);
}

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();
  learnLabels(manifest, state);
  // 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 };
}

/** Devices that installed an update before labels were stored learn its label from the manifest. */
function learnLabels(manifest: Manifest, state: HealkiteState): void {
  const mine = new Set([state.running, state.pending, state.current].filter((s): s is string => !!s && s !== "embedded"));
  for (const r of [manifest.release, ...(manifest.targeted ?? [])]) {
    if (r && mine.has(r.sha256) && !state.labels?.[r.sha256]) rememberLabel(r.sha256, r.label);
  }
}

/**
 * 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 {
  recordStartup();
  return JSON.parse(Native.notifyAppReady()) as HealkiteState;
}

/** Share of launches that send a start-up sample (keeps telemetry small on big apps). */
const STARTUP_SAMPLE_RATE = 0.2;

/** The app reached its first screen: record how long start-up took and the slowest modules (sampled). */
function recordStartup(): void {
  try {
    const r = finishStartup();
    if (r) markFeature("startup-profiler");
    if (!r || Math.random() >= STARTUP_SAMPLE_RATE) return;
    Native.recordEvent(JSON.stringify({ t: Date.now(), type: "perf", name: "startup", data: { sha256: getState().running, ms: r.ms, mods: r.mods } }));
  } catch {
    // profiling must never affect the app
  }
}

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

export interface SyncOptions {
  /**
   * When a downloaded update applies (overrides the release's setting and skips the update prompt):
   * - "nextLaunch": the next time the app starts (default).
   * - "onBackground": when the user comes back to the app after at least `minBackgroundSec` away.
   * - "immediate": now, as a live patch (keeps preserved state, waits for holdLivePatch()).
   */
  installMode?: "nextLaunch" | "onBackground" | "immediate";
  /** With "onBackground": how long the app must have been in the background (default: the release's value, else 0). */
  minBackgroundSec?: number;
  /** Also call notifyAppReady() first (default true). */
  notifyReady?: boolean;
}

let resumeSub: { remove(): void } | null = null;

/** Applies the staged update (as a live patch) when the app comes back after `minBackgroundSec` in the background. */
function applyOnResume(minBackgroundSec: number): void {
  resumeSub?.remove();
  let backgroundAt = 0;
  resumeSub = AppState.addEventListener("change", (s) => {
    if (s === "background") backgroundAt = Date.now();
    else if (s === "active" && backgroundAt && Date.now() - backgroundAt >= minBackgroundSec * 1000) {
      resumeSub?.remove();
      resumeSub = null;
      void applyLivePatch();
    }
  });
}

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 {
  markFeature("crash-reporting");
  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();
      // A crash inside a team's module counts against that module's release only.
      if (error instanceof Error && typeof error.stack === "string") modules.errorInModule(error.stack);
    } 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;
  markFeature("business-events");
  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;
  }
}

// ---------- per-team modules (Re.Pack) ----------

export const modules = createModules({
  config: () => getConfig(),
  track: (name) => {
    trackEvent(name);
  },
});

// ---------- 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 },
    sdk: { version: SDK_VERSION, features: featuresInUse(config) },
    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));
  }
}

let inflight: { key: string; promise: Promise<SyncResult> } | null = null;
let syncCalled = false;

/* ------------------------------------------------------------------ development hints */

declare const __DEV__: boolean | undefined;
declare function require(id: string): unknown;
let hintsEnabled = true;

/**
 * Development builds log a few tips about recommended features the app doesn't use yet (JS console and
 * device log), about 10 s after start. `setHints(false)` turns them off. Release builds never print them
 * (and leave the hint text out of the bundle).
 */
export function setHints(enabled: boolean): void {
  hintsEnabled = enabled;
}

if (typeof __DEV__ !== "undefined" && __DEV__) {
  setTimeout(() => {
    if (!hintsEnabled) return;
    try {
      const { hintLines } = require("./hints") as typeof import("./hints");
      const lines = hintLines(featuresInUse(getConfig()), syncCalled);
      if (lines.length) console.log(lines.join("\n"));
    } catch {
      // hints must never affect the app
    }
  }, 10_000);
}

/**
 * One-call integration: confirm health, check, download, stage (and apply per the install mode).
 * A call made while the same sync is running shares its result instead of downloading twice.
 */
export async function sync(options: SyncOptions = {}): Promise<SyncResult> {
  syncCalled = true;
  const key = JSON.stringify(options);
  while (inflight && inflight.key !== key) await inflight.promise.catch(() => undefined);
  if (inflight) return inflight.promise;
  const run = (async () => {
    try {
      return await syncInner(options);
    } finally {
      await flushEvents();
    }
  })();
  inflight = { key, promise: run };
  try {
    return await run;
  } finally {
    if (inflight?.promise === run) inflight = null;
  }
}

/** Downloads, verifies and stages the update for the next start (tries the backup CDN once). */
async function stage(check: Extract<CheckResult, { status: "UPDATE_AVAILABLE" }>): Promise<void> {
  const config = getConfig();
  const running = getState().running;
  const patch = check.release.patches?.[running];
  rememberLabel(check.release.sha256, check.release.label);
  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);
  }
  notifyVersion();
}

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 release = check.release;
        const label = release.label;
        // The app's <UpdatePrompt /> asks the user (releases marked "Ask the user", or every update with `all`).
        const prompt = options.installMode ? null : getPromptHandler();
        if (prompt && (release.prompt === true || prompt.all)) {
          const update: UpdateInfo = {
            label,
            description: release.description,
            mandatory: release.mandatory === true,
            size: release.size,
            sha256: release.sha256,
          };
          if (prompt.askBeforeDownload && !update.mandatory) {
            prompt.show({ update, staged: false, accept: () => stage(check).then(() => applyLivePatch()) });
            return { status: "AWAITING_USER", label };
          }
          await stage(check);
          prompt.show({ update, staged: true, accept: () => applyLivePatch() });
          return { status: "UPDATE_INSTALLED", label, appliesOn: "nextLaunch", prompted: true };
        }
        await stage(check);
        // The manifest's install policy belongs to the channel release, not to device-targeted ones.
        const policy = check.manifest.release?.sha256 === release.sha256 ? check.manifest.installPolicy : undefined;
        const mode = options.installMode ?? (release.mandatory ? "immediate" : (policy?.mode ?? "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, appliesOn: "now" };
        }
        if (mode === "onBackground") {
          applyOnResume(options.minBackgroundSec ?? policy?.minBackgroundSec ?? 0);
          return { status: "UPDATE_INSTALLED", label, appliesOn: "onResume" };
        }
        return { status: "UPDATE_INSTALLED", 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";
export { HealkiteVersion, useVersionInfo } from "./Version";
export type { HealkiteVersionProps } from "./Version";
export { UpdatePrompt, useUpdate, withUpdatePrompt } from "./UpdatePrompt";
export type { UpdatePhase, UpdatePromptProps, UseUpdate, UseUpdateOptions } from "./UpdatePrompt";
export type { UpdateInfo } from "./prompt-core";

/* ------------------------------------------------------------------ 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> {
  markFeature("previews");
  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> {
  markFeature("instant-hotfix");
  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,
  getVersionInfo,
  subscribeVersionInfo,
  setHints,
  checkForUpdate,
  notifyAppReady,
  restart,
  sync,
  manifestUrl,
  flushEvents,
  getKillSwitch,
  subscribeKillSwitch,
  installErrorHandler,
  trackEvent,
  preserve,
  restored,
  wasLivePatched,
  holdLivePatch,
  applyLivePatch,
  subscribeLivePatch,
  usePreservedState,
  modules,
};
export default Healkite;
