package cz.kamma.llamarunner;

import java.io.File;

/**
 * Builds llama-server command lines from ModelConfig.
 */
public class CommandBuilder {

    /**
     * Builds the command string from a ModelConfig.
     *
     * @param config the model configuration
     * @param modelsDirPath the path to the models directory
     * @return the complete command string
     */
    public String buildCommand(ModelConfig config, String modelsDirPath) {
        StringBuilder cmd = new StringBuilder("llama-server");
        cmd.append(" --host ").append(config.getHost());
        cmd.append(" --port ").append(config.getPort());
        cmd.append(" --parallel ").append(config.getParallel());
        cmd.append(" --batch-size ").append(config.getBatchSize());
        cmd.append(" -t ").append(config.getThreads());
        cmd.append(" -fa ").append(config.isFlashAttention() ? "on" : "off");
        cmd.append(" --temp ").append(config.getTemperature());
        cmd.append(" --top-p ").append(config.getTopP());
        cmd.append(" --top-k ").append(config.getTopK());
        cmd.append(" --min-p ").append(config.getMinP());

        if (config.isKvUnified()) {
            cmd.append(" --kv-unified");
        }

        cmd.append(" --cache-type-k ").append(config.getCacheTypeK());
        cmd.append(" --cache-type-v ").append(config.getCacheTypeV());

        cmd.append(" --ctx-size ").append(config.getCtxSize());

        if (!config.isFit()) {
            cmd.append(" -ngl ").append(config.getNgl());
        }

        if (config.isFit()) {
            cmd.append(" --fit on");
        }

        cmd.append(" --reasoning ").append(config.isReasoning() ? "on" : "off");

        String modelPath = buildModelPath(config.getModelPath(), modelsDirPath);
        cmd.append(" -m ").append(modelPath);

        String mmprojPath = buildModelPath(config.getMmprojPath(), modelsDirPath);
        if (!mmprojPath.isEmpty()) {
            cmd.append(" --mmproj ").append(mmprojPath);
        }

        String kwargsText = config.getChatTemplateKwargs();
        if (kwargsText != null && !kwargsText.trim().isEmpty()) {
            cmd.append(" --chat-template-kwargs \"");
            cmd.append(kwargsText.replace("\"", "\\\""));
            cmd.append("\"");
        }

        return cmd.toString();
    }

    /**
     * Builds the full model path.
     */
    private String buildModelPath(String modelPath, String modelsDirPath) {
        if (modelPath == null || modelPath.trim().isEmpty()) {
            return "";
        }

        File modelFile = new File(modelPath);
        if (modelFile.isAbsolute()) {
            return modelPath;
        }

        return new File(modelsDirPath, modelPath).getAbsolutePath();
    }
}
