package dev.fabricrs.loader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.URI;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 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 && hasEmbeddedSources(anchorClass)) {
                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 precompiled native library '" + libFileName + "' for platform " + platform
                            + " in JAR, and 'cargo' was not found in CARGO_HOME/bin, PATH, or ~/.cargo/bin. "
                            + "Install Rust from https://rustup.rs (with a C linker) to enable local compilation."
                    );
                }
                File compiled = compileFromEmbeddedSource(
                    anchorClass,
                    modId,
                    platform,
                    libStem,
                    libFileName,
                    cargoBin,
                    forceRecompile
                );
                if (compiled != null && compiled.isFile()) {
                    File tmp = File.createTempFile("flr_" + modId + "_", ext);
                    tmp.deleteOnExit();
                    Files.copy(compiled.toPath(), tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);
                    System.load(tmp.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 boolean hasEmbeddedSources(Class<?> anchorClass) {
        InputStream props = anchorClass.getResourceAsStream("/META-INF/flr-src/.flr-build.properties");
        if (props != null) {
            try { props.close(); } catch (Exception ignored) {}
            return true;
        }
        InputStream cargoToml = anchorClass.getResourceAsStream("/META-INF/flr-src/Cargo.toml");
        if (cargoToml != null) {
            try { cargoToml.close(); } catch (Exception ignored) {}
            return true;
        }
        return false;
    }

    private static String resolveCargoBinary() {
        boolean isWin = System.getProperty("os.name", "").toLowerCase().contains("win");
        String exe = isWin ? "cargo.exe" : "cargo";

        String cargoHome = System.getenv("CARGO_HOME");
        if (cargoHome != null && !cargoHome.isEmpty()) {
            File candidate = new File(new File(cargoHome, "bin"), exe);
            if (candidate.isFile() && checkExecutable(candidate.getAbsolutePath())) {
                return candidate.getAbsolutePath();
            }
        }

        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 resolveWritableCacheDir(String modId, String hash) {
        List<File> candidates = new ArrayList<File>();
        candidates.add(new File(".fabric-rs/cache/" + modId + "/" + hash));
        String userHome = System.getProperty("user.home", "");
        if (!userHome.isEmpty()) {
            candidates.add(new File(userHome, ".cache/flr/native-builds/" + modId + "/" + hash));
        }
        String tmpDir = System.getProperty("java.io.tmpdir", "");
        if (!tmpDir.isEmpty()) {
            candidates.add(new File(tmpDir, "flr-cache/" + modId + "/" + hash));
        }
        for (int i = 0; i < candidates.size(); i++) {
            File dir = candidates.get(i);
            if (dir.exists() || dir.mkdirs()) {
                File probe = new File(dir, ".flr-write-probe");
                try {
                    FileOutputStream fos = new FileOutputStream(probe);
                    fos.write(1);
                    fos.close();
                    probe.delete();
                    return dir;
                } catch (Exception ignored) {
                }
            }
        }
        throw new RuntimeException("Cannot create writable cache directory for mod '" + modId + "'");
    }

    private static Properties loadBuildProperties(Class<?> anchorClass) {
        Properties props = new Properties();
        InputStream in = anchorClass.getResourceAsStream("/META-INF/flr-src/.flr-build.properties");
        if (in != null) {
            try {
                props.load(in);
            } catch (Exception ignored) {
            } finally {
                try { in.close(); } catch (Exception ignored) {}
            }
        }
        return props;
    }

    private static List<String> loadFileManifest(Class<?> anchorClass) {
        InputStream in = anchorClass.getResourceAsStream("/META-INF/flr-src/.flr-files.txt");
        if (in == null) {
            return null;
        }
        List<String> files = new ArrayList<String>();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                String trimmed = line.trim();
                if (!trimmed.isEmpty()) {
                    files.add(trimmed);
                }
            }
        } catch (Exception e) {
            return null;
        } finally {
            try { in.close(); } catch (Exception ignored) {}
        }
        return files;
    }

    private static File safeResolve(File cacheDir, String rel) {
        String norm = rel.replace('\\', '/');
        if (norm.isEmpty() || norm.startsWith("/") || norm.contains(":")) {
            throw new SecurityException("Invalid embedded source path: " + rel);
        }
        String[] parts = norm.split("/");
        for (int i = 0; i < parts.length; i++) {
            if ("..".equals(parts[i])) {
                throw new SecurityException("Path traversal in embedded source: " + rel);
            }
        }
        Path rootNorm = cacheDir.toPath().toAbsolutePath().normalize();
        Path targetNorm = rootNorm.resolve(norm).normalize();
        if (!targetNorm.startsWith(rootNorm)) {
            throw new SecurityException("Escaped cache directory for path: " + rel);
        }
        return targetNorm.toFile();
    }

    private static void writeStreamToFile(InputStream in, File dest) throws Exception {
        File parent = dest.getParentFile();
        if (parent != null && !parent.exists()) {
            parent.mkdirs();
        }
        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();
        }
    }

    private static void extractFromManifestList(
        Class<?> anchorClass,
        File cacheDir,
        List<String> files
    ) throws Exception {
        for (int i = 0; i < files.size(); i++) {
            String rel = files.get(i);
            File dest = safeResolve(cacheDir, rel);
            InputStream in = anchorClass.getResourceAsStream("/META-INF/flr-src/" + rel);
            if (in == null) {
                throw new FileNotFoundException("Missing embedded source resource: /META-INF/flr-src/" + rel);
            }
            try {
                writeStreamToFile(in, dest);
            } finally {
                in.close();
            }
        }
    }

    private static File resolveJarFile(Class<?> anchorClass) {
        try {
            URL url = anchorClass.getProtectionDomain().getCodeSource().getLocation();
            if (url != null) {
                String spec = url.toString();
                if (spec.startsWith("jar:")) {
                    int bang = spec.indexOf("!/");
                    if (bang > 4) {
                        spec = spec.substring(4, bang);
                    }
                }
                if (spec.startsWith("file:")) {
                    File f = new File(new URI(spec));
                    if (f.isFile()) {
                        return f;
                    }
                }
            }
        } catch (Exception ignored) {
        }
        return null;
    }

    private static void extractFromJarFallback(File jarFile, File cacheDir) throws Exception {
        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 = safeResolve(cacheDir, rel);
                    if (entry.isDirectory()) {
                        dest.mkdirs();
                    } else {
                        InputStream in = jar.getInputStream(entry);
                        try {
                            writeStreamToFile(in, dest);
                        } finally {
                            in.close();
                        }
                    }
                }
            }
        } finally {
            jar.close();
        }
    }

    private static void writeMarkerAtomically(File marker) throws Exception {
        File tmp = new File(marker.getParentFile(), marker.getName() + ".tmp");
        FileOutputStream fos = new FileOutputStream(tmp);
        try {
            fos.write("ok\n".getBytes(StandardCharsets.UTF_8));
        } finally {
            fos.close();
        }
        try {
            Files.move(tmp.toPath(), marker.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
        } catch (AtomicMoveNotSupportedException e) {
            Files.move(tmp.toPath(), marker.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }
    }

    private static File findBuiltLibrary(File releaseDir, String libFileName, String libStem) {
        File exact = new File(releaseDir, libFileName);
        if (exact.isFile()) {
            return exact;
        }
        File[] files = releaseDir.listFiles();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                if (!f.isFile()) {
                    continue;
                }
                String n = f.getName();
                if ((n.endsWith(".so") || n.endsWith(".dll") || n.endsWith(".dylib"))
                    && (n.contains(libStem) || n.contains(libStem.replace('-', '_')))) {
                    return f;
                }
            }
        }
        return null;
    }

    private static File compileFromEmbeddedSource(
        Class<?> anchorClass,
        String modId,
        String platform,
        String libStem,
        String libFileName,
        String cargoBin,
        boolean forceRecompile
    ) throws Exception {
        Properties props = loadBuildProperties(anchorClass);
        List<String> fileManifest = loadFileManifest(anchorClass);

        String hash = props.getProperty("source_hash", "").trim();
        File legacyJar = null;
        if (hash.isEmpty() || fileManifest == null) {
            legacyJar = resolveJarFile(anchorClass);
            if (hash.isEmpty()) {
                if (legacyJar != null) {
                    hash = sha256Hex(legacyJar).substring(0, 16);
                } else {
                    hash = "embedded";
                }
            }
        }

        File cacheDir = resolveWritableCacheDir(modId, hash);
        File lockFile = new File(cacheDir.getParentFile(), cacheDir.getName() + ".lock");
        RandomAccessFile raf = new RandomAccessFile(lockFile, "rw");
        FileChannel channel = raf.getChannel();
        FileLock lock = channel.lock();
        try {
            String effectiveStem = props.getProperty("lib_stem", libStem).trim();
            if (effectiveStem.isEmpty()) {
                effectiveStem = libStem;
            }
            String effectiveLibName = System.mapLibraryName(effectiveStem);

            File targetDir = new File(cacheDir, "target-" + platform);
            File releaseDir = new File(targetDir, "release");
            File builtMarker = new File(cacheDir, ".flr-built-" + platform + ".ok");

            if (!forceRecompile && builtMarker.isFile()) {
                File existing = findBuiltLibrary(releaseDir, effectiveLibName, effectiveStem);
                if (existing != null) {
                    System.out.println("[fabric-rs:" + modId + "] Using cached native build: " + existing.getAbsolutePath());
                    return existing;
                }
            }

            File extractMarker = new File(cacheDir, ".flr-extracted.ok");
            if (forceRecompile || !extractMarker.isFile()) {
                if (fileManifest != null) {
                    extractFromManifestList(anchorClass, cacheDir, fileManifest);
                } else if (legacyJar != null) {
                    extractFromJarFallback(legacyJar, cacheDir);
                } else {
                    throw new RuntimeException("Cannot locate embedded sources inside mod JAR");
                }
                writeMarkerAtomically(extractMarker);
            }

            String manifestRel = props.getProperty("manifest_rel", "Cargo.toml").trim();
            String pkgName = props.getProperty("package", "").trim();
            String sdkIdxRel = props.getProperty("sdk_index_rel", ".flr/sdk.flridx").trim();
            boolean vendored = "true".equalsIgnoreCase(props.getProperty("vendored", "false").trim());
            boolean hasLockfile = "true".equalsIgnoreCase(props.getProperty("has_lockfile", "false").trim())
                || new File(cacheDir, "Cargo.lock").isFile();
            String features = props.getProperty("features", "").trim();
            boolean noDefaultFeatures =
                "true".equalsIgnoreCase(props.getProperty("no_default_features", "false").trim());

            File sdkIdxFile = sdkIdxRel.isEmpty() ? null : new File(cacheDir, sdkIdxRel);
            File manifestFile = new File(cacheDir, manifestRel);

            int exitCode = runCargoBuild(
                cargoBin,
                cacheDir,
                manifestFile,
                manifestRel,
                pkgName,
                targetDir,
                sdkIdxFile,
                hasLockfile,
                vendored,
                features,
                noDefaultFeatures,
                modId
            );
            if (exitCode != 0 && hasLockfile && !vendored) {
                System.out.println("[fabric-rs:" + modId + "] Retrying cargo build without --locked...");
                exitCode = runCargoBuild(
                    cargoBin,
                    cacheDir,
                    manifestFile,
                    manifestRel,
                    pkgName,
                    targetDir,
                    sdkIdxFile,
                    false,
                    false,
                    features,
                    noDefaultFeatures,
                    modId
                );
            }
            if (exitCode != 0) {
                throw new RuntimeException("Embedded cargo build --release failed with exit code " + exitCode);
            }

            File compiled = findBuiltLibrary(releaseDir, effectiveLibName, effectiveStem);
            if (compiled == null) {
                throw new FileNotFoundException(
                    "Expected compiled library missing in " + releaseDir.getAbsolutePath()
                );
            }
            writeMarkerAtomically(builtMarker);
            return compiled;
        } finally {
            try { lock.release(); } catch (Exception ignored) {}
            try { channel.close(); } catch (Exception ignored) {}
            try { raf.close(); } catch (Exception ignored) {}
        }
    }

    private static int runCargoBuild(
        String cargoBin,
        File cacheDir,
        File manifestFile,
        String manifestRel,
        String pkgName,
        File targetDir,
        File sdkIdxFile,
        boolean useLocked,
        boolean useOffline,
        String features,
        boolean noDefaultFeatures,
        String modId
    ) throws Exception {
        List<String> cmd = new ArrayList<String>();
        cmd.add(cargoBin);
        cmd.add("build");
        cmd.add("--release");
        if (!"Cargo.toml".equals(manifestRel) && manifestFile.isFile()) {
            cmd.add("--manifest-path");
            cmd.add(manifestFile.getAbsolutePath());
        }
        if (!pkgName.isEmpty()) {
            cmd.add("--package");
            cmd.add(pkgName);
        }
        if (noDefaultFeatures) {
            cmd.add("--no-default-features");
        }
        if (features != null && !features.isEmpty()) {
            cmd.add("--features");
            cmd.add(features);
        }
        if (useLocked) {
            cmd.add("--locked");
        }
        if (useOffline) {
            cmd.add("--offline");
        }

        ProcessBuilder pb = new ProcessBuilder(cmd);
        pb.directory(cacheDir);
        pb.redirectErrorStream(true);

        Map<String, String> env = pb.environment();
        env.put("CARGO_TARGET_DIR", targetDir.getAbsolutePath());
        if (sdkIdxFile != null && sdkIdxFile.isFile()) {
            env.put("FLR_SDK_INDEX", sdkIdxFile.getAbsolutePath());
            env.put("FLR_STRICT_VALIDATE", "1");
        }
        File cargoParent = new File(cargoBin).getParentFile();
        if (cargoParent != null) {
            String curPath = env.get("PATH");
            String parentPath = cargoParent.getAbsolutePath();
            if (curPath == null || curPath.isEmpty()) {
                env.put("PATH", parentPath);
            } else if (!curPath.contains(parentPath)) {
                env.put("PATH", parentPath + File.pathSeparator + curPath);
            }
        }

        Process p = pb.start();
        String[] tail = new String[80];
        int tailCount = 0;

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8));
        try {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("[fabric-rs:" + modId + "] " + line);
                tail[tailCount % tail.length] = line;
                tailCount++;
            }
        } finally {
            try { reader.close(); } catch (Exception ignored) {}
        }

        long timeoutSecs = Long.getLong("fabric-rs.compileTimeoutSecs", 900L);
        if (!p.waitFor(timeoutSecs, TimeUnit.SECONDS)) {
            p.destroyForcibly();
            throw new RuntimeException("Embedded cargo build timed out after " + timeoutSecs + "s");
        }
        int exitCode = p.exitValue();
        if (exitCode != 0) {
            StringBuilder sb = new StringBuilder();
            int start = Math.max(0, tailCount - tail.length);
            for (int i = start; i < tailCount; i++) {
                String l = tail[i % tail.length];
                if (l != null) {
                    sb.append('\n').append(l);
                }
            }
            System.err.println("[fabric-rs:" + modId + "] Cargo build failed (exit " + exitCode + "). Tail:" + sb.toString());
        }
        return exitCode;
    }

    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();
        }
    }
}
