package org.openautonomousconnection.webserver.runtime;

import javax.tools.*;
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

/**
 * Compiles and loads Java web pages at runtime.
 *
 * NOTE: Requires running with a JDK (ToolProvider.getSystemJavaCompiler != null).
 */
public final class JavaPageCompiler {

    private JavaPageCompiler() {}

    public static Class<?> compile(File javaFile) throws Exception {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) throw new IllegalStateException("JDK required (JavaCompiler not available)");

        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

        Iterable<? extends JavaFileObject> units = fileManager.getJavaFileObjects(javaFile);

        // Compile in-place (class next to the .java file)
        List<String> options = List.of("-classpath", System.getProperty("java.class.path"));

        boolean success = compiler.getTask(null, fileManager, null, options, null, units).call();
        fileManager.close();

        if (!success) throw new RuntimeException("Compilation failed: " + javaFile.getName());

        URLClassLoader cl = new URLClassLoader(new URL[]{ javaFile.getParentFile().toURI().toURL() });

        String className = javaFile.getName().replace(".java", "");
        return cl.loadClass(className);
    }
}
