package com.lemenzo.gallery.editor;

/** Conservative bitmap memory budgeting for large camera images. */
public final class BitmapBudget {
    private static final long MIN_WORKING_BYTES = 64L * 1024L * 1024L;
    private BitmapBudget() {}

    /**
     * Returns 0 when native dimensions are safe, otherwise a max edge that keeps
     * the source + rendered output + temporary overhead within a conservative heap budget.
     */
    public static int safeDecodeMaxEdge(int width, int height) {
        if (width <= 0 || height <= 0) return 0;
        Runtime runtime = Runtime.getRuntime();
        long available = Math.max(0L, runtime.maxMemory() - (runtime.totalMemory() - runtime.freeMemory()));
        long budget = Math.max(MIN_WORKING_BYTES, (long)(available * 0.58));
        double pixels = (double) width * (double) height;
        // Two ARGB_8888 bitmaps plus ~20% renderer/encoder overhead.
        double estimated = pixels * 4.0 * 2.2;
        if (estimated <= budget) return 0;
        double scale = Math.sqrt(budget / estimated);
        scale = Math.max(0.10, Math.min(1.0, scale));
        return Math.max(2048, (int)Math.floor(Math.max(width, height) * scale));
    }
}
