package dev.fabricrs.loader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * Minimal Java 8-compatible native library loader for FLR v2 mods.
 * Packaged into mod JARs under the mod's isolated package and relocated by cargo-fabric.
 */
public final class FlrRuntimeLoader {
    private FlrRuntimeLoader() {}

    public static synchronized boolean loadNative(
        Class<?> anchorClass,
        String modId,
        String libStem,
        boolean allowSourceFallback
    ) {
        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);
        boolean forceRecompile = Boolean.getBoolean("fabric-rs.recompile");

        try {
            if (!forceRecompile) {
                InputStream is = anchorClass.getResourceAsStream("/META-INF/natives/" + platform + "/" + libFileName);
                if (is == null) {
                    is = anchorClass.getResourceAsStream("/META-INF/natives/" + libFileName);
                }
                if (is != null) {
                    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;
                }
            }

            if (allowSourceFallback) {
                InputStream srcMarker = anchorClass.getResourceAsStream("/META-INF/flr-src/Cargo.toml");
                if (srcMarker != null) {
                    srcMarker.close();
                    System.out.println("[fabric-rs:" + modId + "] No precompiled binary for " + platform + "; compiling from embedded sources...");
                    String cargoBin = resolveCargoBinary();
                    if (cargoBin == null) {
                        throw new UnsatisfiedLinkError(
                            "No native library for " + platform + " in JAR and 'cargo' was not found in PATH or ~/.cargo/bin."
                        );
                    }
                    File compiled = compileFromEmbeddedSource(anchorClass, modId, libFileName, cargoBin);
                    if (compiled != null && compiled.exists()) {
                        System.load(compiled.getAbsolutePath());
                        return true;
                    }
                }
            }

            throw new UnsatisfiedLinkError(
                "Failed to locate or build native library '" + libFileName + "' for platform " + platform
            );
        } catch (UnsatisfiedLinkError ule) {
            throw ule;
        } catch (Throwable t) {
            throw new RuntimeException("Failed to initialize native library for mod '" + modId + "'", t);
        }
    }

    private static String resolveCargoBinary() {
        String exe = System.getProperty("os.name", "").toLowerCase().contains("win") ? "cargo.exe" : "cargo";
        if (checkExecutable(exe)) {
            return exe;
        }
        String userHome = System.getProperty("user.home", "");
        if (!userHome.isEmpty()) {
            File candidate = new File(userHome, ".cargo/bin/" + exe);
            if (candidate.isFile() && checkExecutable(candidate.getAbsolutePath())) {
                return candidate.getAbsolutePath();
            }
        }
        return null;
    }

    private static boolean checkExecutable(String bin) {
        try {
            Process p = new ProcessBuilder(bin, "--version").start();
            return p.waitFor() == 0;
        } catch (Exception ignored) {
            return false;
        }
    }

    private static File compileFromEmbeddedSource(
        Class<?> anchorClass,
        String modId,
        String libFileName,
        String cargoBin
    ) throws Exception {
        URL jarUrl = anchorClass.getProtectionDomain().getCodeSource().getLocation();
        File jarFile = new File(jarUrl.toURI());
        if (!jarFile.isFile()) {
            return null;
        }

        String hash = sha256Hex(jarFile).substring(0, 16);
        File cacheDir = new File(".fabric-rs/cache/" + modId + "/" + hash);
        File targetLib = new File(cacheDir, "target/release/" + libFileName);
        if (targetLib.exists()) {
            System.out.println("[fabric-rs:" + modId + "] Using cached native build: " + targetLib.getAbsolutePath());
            return targetLib;
        }

        if (!cacheDir.exists() && !cacheDir.mkdirs()) {
            throw new RuntimeException("Cannot create cache directory: " + cacheDir.getAbsolutePath());
        }

        String prefix = "META-INF/flr-src/";
        JarFile jar = new JarFile(jarFile);
        try {
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                if (name.startsWith(prefix) && name.length() > prefix.length()) {
                    String rel = name.substring(prefix.length());
                    File dest = new File(cacheDir, rel);
                    if (entry.isDirectory()) {
                        dest.mkdirs();
                    } else {
                        File parent = dest.getParentFile();
                        if (parent != null) {
                            parent.mkdirs();
                        }
                        InputStream in = jar.getInputStream(entry);
                        try {
                            OutputStream out = new FileOutputStream(dest);
                            try {
                                byte[] buf = new byte[8192];
                                int n;
                                while ((n = in.read(buf)) != -1) {
                                    out.write(buf, 0, n);
                                }
                            } finally {
                                out.close();
                            }
                        } finally {
                            in.close();
                        }
                    }
                }
            }
        } finally {
            jar.close();
        }

        ProcessBuilder pb = new ProcessBuilder(cargoBin, "build", "--release");
        pb.directory(cacheDir);
        pb.inheritIO();
        int exitCode = pb.start().waitFor();
        if (exitCode != 0) {
            throw new RuntimeException("Embedded cargo build --release failed with exit code " + exitCode);
        }
        if (!targetLib.exists()) {
            throw new FileNotFoundException("Expected compiled library missing: " + targetLib.getAbsolutePath());
        }
        return targetLib;
    }

    private static String sha256Hex(File file) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            FileInputStream in = new FileInputStream(file);
            try {
                byte[] buf = new byte[8192];
                int n;
                while ((n = in.read(buf)) != -1) {
                    md.update(buf, 0, n);
                }
            } finally {
                in.close();
            }
            byte[] digest = md.digest();
            StringBuilder sb = new StringBuilder(digest.length * 2);
            for (int i = 0; i < digest.length; i++) {
                sb.append(String.format("%02x", digest[i] & 0xff));
            }
            return sb.toString();
        } catch (Exception e) {
            return Long.toHexString(file.lastModified()) + "_" + file.length();
        }
    }
}
