package crypto.r35157.nenjim;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class DirectoryClassLoader extends ClassLoader {

    private final Path rootDir;
    private final Map<String, Class<?>> loadedClasses = new HashMap<>();

    public DirectoryClassLoader(Path rootDir) {
        this.rootDir = rootDir;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        if (loadedClasses.containsKey(name)) {
            return loadedClasses.get(name);
        }

        String relativePath = name.replace('.', '/') + ".class";
        File classFile = rootDir.resolve(relativePath).toFile();

        if (!classFile.exists()) {
            throw new ClassNotFoundException("Class file not found: " + classFile.getAbsolutePath());
        }

        try (FileInputStream fis = new FileInputStream(classFile)) {
            byte[] bytes = fis.readAllBytes();
            Class<?> clazz = defineClass(name, bytes, 0, bytes.length);
            loadedClasses.put(name, clazz);
            return clazz;
        } catch (IOException e) {
            throw new ClassNotFoundException("Failed to load class: " + name, e);
        }
    }
}
