package click.kamil.springstatemachineexporter.exporter;

import click.kamil.springstatemachineexporter.model.StateMachineModel;
import click.kamil.springstatemachineexporter.model.Transition;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.util.List;
import java.util.Set;

public class JsonExporter implements StateMachineExporter {

    private final ObjectMapper objectMapper;

    public JsonExporter() {
        this.objectMapper = new ObjectMapper()
                .enable(SerializationFeature.INDENT_OUTPUT);
    }

    @Override
    public String export(click.kamil.springstatemachineexporter.analysis.model.AnalysisResult result, ExportOptions options) {
        try {
            java.util.Map<String, Object> output = new java.util.HashMap<>();
            output.put("name", result.getName());
            output.put("transitions", result.getTransitions());
            output.put("startStates", result.getStartStates());
            output.put("endStates", result.getEndStates());
            output.put("renderChoicesAsDiamonds", options.isRenderChoicesAsDiamonds());
            output.put("metadata", result.getMetadata());
            
            return objectMapper.writeValueAsString(output);
        } catch (Exception e) {
            throw new RuntimeException("Failed to export to JSON", e);
        }
    }

    @Override
    public String export(String name, List<Transition> transitions, Set<String> startStates, Set<String> endStates, ExportOptions options) {
        try {
            StateMachineModel model = StateMachineModel.builder()
                    .name(name)
                    .transitions(transitions)
                    .startStates(startStates)
                    .endStates(endStates)
                    .renderChoicesAsDiamonds(options.isRenderChoicesAsDiamonds())
                    .build();
            return objectMapper.writeValueAsString(model);
        } catch (Exception e) {
            throw new RuntimeException("Failed to export to JSON", e);
        }
    }

    @Override
    public String getFileExtension() {
        return ".json";
    }
}
