package cz.kamma.llamarunner;

import java.io.File;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

/**
 * Validation utilities for configuration inputs.
 */
public class ConfigValidation {

    /**
     * Validates a ModelConfig object.
     *
     * @param config the model config to validate
     * @return error message if invalid, null if valid
     */
    public static String validateConfig(ModelConfig config) {
        // Validate port
        if (config.getPort() < 1 || config.getPort() > 65535) {
            return "Port must be between 1 and 65535";
        }

        // Validate parallel
        if (config.getParallel() < 1) {
            return "Parallel must be at least 1";
        }

        // Validate threads
        if (config.getThreads() < 1) {
            return "Threads must be at least 1";
        }

        // Validate temperature
        if (config.getTemperature() < 0) {
            return "Temperature must be non-negative";
        }

        // Validate topP
        if (config.getTopP() < 0 || config.getTopP() > 1) {
            return "Top P must be between 0 and 1";
        }

        // Validate topK
        if (config.getTopK() < 0) {
            return "Top K must be non-negative";
        }

        // Validate minP
        if (config.getMinP() < 0 || config.getMinP() > 1) {
            return "Min P must be between 0 and 1";
        }

        // Validate ctxSize
        if (config.getCtxSize() < 0) {
            return "Context size must be non-negative";
        }

        // Validate model path
        if (config.getModelPath() == null || config.getModelPath().trim().isEmpty()) {
            return "Model path cannot be empty";
        }
        File modelFile = new File(config.getModelPath());
        if (!modelFile.exists()) {
            return "Model file does not exist: " + config.getModelPath();
        }
        if (!modelFile.isFile()) {
            return "Model path is not a file: " + config.getModelPath();
        }

        // Validate optional mmproj path
        String mmprojPath = config.getMmprojPath();
        if (mmprojPath != null && !mmprojPath.trim().isEmpty()) {
            File mmprojFile = new File(mmprojPath);
            if (!mmprojFile.exists()) {
                return "MMProj file does not exist: " + mmprojPath;
            }
            if (!mmprojFile.isFile()) {
                return "MMProj path is not a file: " + mmprojPath;
            }
        }

        // Validate JSON kwargs
        String json = config.getChatTemplateKwargs();
        if (json != null && !json.trim().isEmpty()) {
            try {
                new Gson().fromJson(json, Object.class);
            } catch (JsonSyntaxException e) {
                return "Invalid JSON format in kwargs";
            }
        }

        return null;
    }
}
