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 {
            // Full AnalysisResult serialization: self-contained interchange format for downstream
            // exporters (HTML, etc.) without requiring source code re-analysis.
            return objectMapper.writeValueAsString(result);
        } 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";
    }
}
