package vassistent.service;

import vassistent.model.ProblemLevel;
import vassistent.util.Logger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Writes the current problem level as animation state JSON for Unreal integration.
 */
public class AnimationFileService {
    private static final String DEFAULT_OUTPUT_PATH = "data/animation.json";
    private final String outputPath;

    /**
     * Creates the animation file service with default output path.
     */
    public AnimationFileService() {
        this(DEFAULT_OUTPUT_PATH);
    }

    /**
     * Creates the animation file service with an explicit output path.
     *
     * @param outputPath target JSON file path
     */
    public AnimationFileService(String outputPath) {
        this.outputPath = outputPath;
    }

    /**
     * Writes the mapped animation state for the given level to the configured JSON file.
     *
     * @param level evaluated problem level
     */
    public void wirteAnimationState(ProblemLevel level) {

        String animation = mapLevelToAnimation(level);

        File file = new File(outputPath);

        try {

            File parent = file.getParentFile();
            if (parent != null) {
                parent.mkdirs();
            }

            String json = """
                    {
                        "animation": "%s"
                    }
                    """.formatted(animation);

            try (FileWriter writer = new FileWriter(file, false)) {
                writer.write(json);
            }

            Logger.info("ANIMATION FILE", "Animation JSON written");

        } catch (IOException e) {
            Logger.error("ANIMATION FILE", "Failed to write animation file", e);
        }
    }

    /**
     * Maps a problem level to the animation identifier expected by Unreal.
     *
     * @param level evaluated problem level
     * @return animation key written into the JSON payload
     */
    private String mapLevelToAnimation(ProblemLevel level) {

        return switch (level) {
            case NONE -> "no";
            case WARNING -> "warning";
            case HIGH -> "high";
            case DISASTER -> "disaster";
        };
    }
}
