package com.foxx.androidcast.crash;

/*********************************************************************
 * CrashNativeBridge.java
 * Created at: Wed 20 May 2026 14:31:55 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class CrashNativeBridge
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 47 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	b476dd21b8dfd795a94780873f0b906d0c9a5f8559152368f661014481407275
**********************************************************************/
import android.content.Context;
import android.util.Log;

/** Installs native SIG* handlers that write backtrace stubs for the watcher process. */
public final class CrashNativeBridge {
    private static final String TAG = "CrashNativeBridge";
    private static final String LIB = "androidcast_codecs";
    private static volatile boolean loaded;

    private CrashNativeBridge() {}

    public static void init(Context context) {
        if (!ensureLoaded()) {
            return;
        }
        try {
            String dir = context.getFilesDir().getAbsolutePath() + "/crash_reports/native";
            nativeInstallCrashHook(dir);
        } catch (Throwable t) {
            Log.w(TAG, "nativeInstallCrashHook failed: " + t.getMessage());
        }
    }

    private static boolean ensureLoaded() {
        if (loaded) {
            return true;
        }
        try {
            System.loadLibrary(LIB);
            loaded = true;
            return true;
        } catch (UnsatisfiedLinkError e) {
            return false;
        }
    }

    private static native void nativeInstallCrashHook(String nativeReportDir);
}
