package com.foxx.androidcast.stats;

/*********************************************************************
 * SessionStatsContext.java
 * Created at: Tue 19 May 2026 19:43:06 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class SessionStatsContext
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (3 commits, 81 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	9d291f1bb62281400283aa0db81ccc3f63f918740285af85d2ce31d2e3b22ab9
**********************************************************************/
import android.content.Context;

import java.util.concurrent.atomic.AtomicReference;

/** Active session stats recorder for transport/pump hooks without threading references everywhere. */
public final class SessionStatsContext {
  private static final AtomicReference<SessionStatsRecorder> ACTIVE = new AtomicReference<>();

  private SessionStatsContext() {}

  public static void bind(SessionStatsRecorder recorder) {
    ACTIVE.set(recorder);
  }

  public static void unbind(SessionStatsRecorder recorder) {
    ACTIVE.compareAndSet(recorder, null);
  }

  public static SessionStatsRecorder get() {
    return ACTIVE.get();
  }

  public static void recordOutboundMessage(byte type, boolean keyFrame, int payloadBytes) {
    SessionStatsRecorder r = ACTIVE.get();
    if (r != null) {
      r.recordOutboundMessage(type, keyFrame, payloadBytes);
    }
  }

  public static void recordInboundMessage(byte type, boolean keyFrame, int payloadBytes) {
    SessionStatsRecorder r = ACTIVE.get();
    if (r != null) {
      r.recordInboundMessage(type, keyFrame, payloadBytes);
    }
  }

  public static void onDatagramSent(int wireBytes) {
    SessionStatsRecorder r = ACTIVE.get();
    if (r != null) {
      r.onDatagramSent(wireBytes);
    }
  }

  public static void onDatagramReceived(int wireBytes) {
    SessionStatsRecorder r = ACTIVE.get();
    if (r != null) {
      r.onDatagramReceived(wireBytes);
    }
  }

  public static void flushGeneralIfDue() {
    SessionStatsRecorder r = ACTIVE.get();
    if (r != null) {
      r.flushGeneralIfDue();
    }
  }

  /**
   * Best-effort: persist the active session when the JVM is about to die from an uncaught exception.
   * Native crashes (SIGSEGV) are not covered.
   */
  public static void flushActiveOnUncaughtException(Context context) {
    SessionStatsRecorder r = ACTIVE.get();
    if (r == null) {
      return;
    }
    try {
      r.finish(context.getApplicationContext(), "crash");
    } catch (Throwable ignored) {
    }
  }
}
