package dev.fabricrs.loader;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

/**
 * Minimal Java 8-compatible precompiled-only native library loader for FLR v2 mods
 * packaged without embedded source fallback.
 */
public final class FlrThinLoader {
    private FlrThinLoader() {}

    public static synchronized boolean loadNative(
        Class<?> anchorClass,
        String modId,
        String libStem,
        boolean _ignored
    ) {
        String os = System.getProperty("os.name", "").toLowerCase();
        String arch = System.getProperty("os.arch", "").toLowerCase();

        String osName;
        String ext;
        if (os.contains("win")) {
            osName = "windows";
            ext = ".dll";
        } else if (os.contains("mac") || os.contains("darwin")) {
            osName = "macos";
            ext = ".dylib";
        } else {
            osName = "linux";
            ext = ".so";
        }

        String archName;
        if (arch.contains("aarch64") || arch.contains("arm64")) {
            archName = "aarch64";
        } else if (arch.contains("riscv64")) {
            archName = "riscv64";
        } else {
            archName = "x86_64";
        }

        String platform = osName + "-" + archName;
        String libFileName = System.mapLibraryName(libStem);

        try {
            InputStream is = anchorClass.getResourceAsStream("/META-INF/natives/" + platform + "/" + libFileName);
            if (is == null) {
                is = anchorClass.getResourceAsStream("/META-INF/natives/" + libFileName);
            }
            if (is == null) {
                throw new UnsatisfiedLinkError(
                    "No precompiled native library '" + libFileName + "' bundled for platform " + platform
                );
            }
            File tmp = File.createTempFile("flr_" + modId + "_", ext);
            tmp.deleteOnExit();
            try {
                Files.copy(is, tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);
            } finally {
                is.close();
            }
            System.load(tmp.getAbsolutePath());
            return true;
        } catch (UnsatisfiedLinkError ule) {
            throw ule;
        } catch (Throwable t) {
            throw new RuntimeException("Failed to load native library for mod '" + modId + "'", t);
        }
    }
}
