package com.elphel.imagej.gpu.jna;

import com.sun.jna.Native;
import com.sun.jna.Pointer;

/**
 * Stage-3 validation: imclt_rbg_all. Run convert_direct then the inverse-CLT RBG reconstruction
 * natively (NVRTC + driver-API, no JCuda) through JNA, and compare the de-pitched RBG output to
 * the tile_processor_gpu golden (clt/aux_chnN.rbg). Builds directly on the Stage-2 setup.
 *
 * Run:
 *   java -Djna.library.path=&lt;dir with libtileproc.so&gt; -cp target/classes:&lt;jna.jar&gt; \
 *        com.elphel.imagej.gpu.jna.Stage3 [data_root] [lwir]
 * By Claude on 2026-06-25.
 */
public class Stage3 {
    public static void main(String[] args) {
        String root = (args.length > 0) ? args[0] : "/home/elphel/git/tile_processor_gpu";
        int    lwir = (args.length > 1) ? Integer.parseInt(args[1]) : 1;
        String srcdir = "/home/elphel/git/tile_processor_gpu/src";
        String devrt  = "/usr/local/cuda/targets/x86_64-linux/lib/libcudadevrt.a";

        System.out.printf("Stage3 (convert_direct + imclt_rbg_all via JNA): root=%s lwir=%d%n", root, lwir);
        TpJna lib = Native.load("tileproc", TpJna.class);
        Pointer m = lib.tp_create_module(srcdir, devrt);
        if (m == null) { System.out.println("FAIL: tp_create_module:\n" + lib.tp_last_error()); System.exit(1); }

        double[] cltErr = new double[1], rbgErr = new double[1];
        int[]    nActive = new int[1];
        int rc = lib.tp_imclt_selftest(m, lwir, root, cltErr, rbgErr, nActive);
        if (rc != 0) { System.out.printf("FAIL: selftest rc=%d: %s%n", rc, lib.tp_last_error()); System.exit(2); }

        // Closeness check (NVRTC vs offline-nvcc + CDP reorder), not bitwise.
        boolean ok = (rbgErr[0] >= 0) && !Double.isNaN(rbgErr[0]) && (rbgErr[0] < 1.0) && (nActive[0] > 0);
        System.out.printf("  convert_direct: num_active=%d  max|CLT-golden|=%.6g%n", nActive[0], cltErr[0]);
        System.out.printf("  imclt_rbg_all:  max|RBG-golden|=%.6g  %s%n", rbgErr[0], ok ? "PASS" : "REVIEW");
        lib.tp_destroy_module(m);
        System.out.println(ok ? "RESULT: PASS (imclt_rbg_all matches golden via JNA)" : "RESULT: REVIEW (see maxErr)");
        System.exit(ok ? 0 : 3);
    }
}
