package click.kamil.springstatemachineexporter.analysis.service;

import click.kamil.springstatemachineexporter.exporter.JsonExporter;
import click.kamil.springstatemachineexporter.service.ExportService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.StreamSupport;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Verifies switch-case branch pruning for string-key dispatch chains.
 */
class StringDispatchCallGraphGapTest {

    private static Path findProjectRoot() {
        Path current = Path.of(".").toAbsolutePath();
        while (current != null && !Files.exists(current.resolve("settings.gradle"))) {
            current = current.getParent();
        }
        return current;
    }

    @Test
    void payStringDispatchEndpointShouldMatchOnlyPayTransition(@TempDir Path tempDir) throws Exception {
        Path sampleRoot = findProjectRoot().resolve("state_machines/layered_dispatcher_sample");
        ExportService exportService = new ExportService(List.of(new JsonExporter()));
        exportService.runExporter(sampleRoot, tempDir, List.of("json"), true, List.of(), null, null,
                click.kamil.springstatemachineexporter.exporter.EnumFormat.fn,
                click.kamil.springstatemachineexporter.exporter.EnumFormat.fn);

        JsonNode orderMachine = readMachineJson(tempDir, "StandardOrderStateMachineConfiguration", new ObjectMapper());
        List<JsonNode> matchedChains = findMatchedCallChains(orderMachine, "POST /api/string-dispatch/orders/pay");

        assertThat(matchedChains).hasSize(1);
        assertThat(matchedChains.get(0).get("matchedTransitions")).hasSize(1);
        assertThat(matchedChains.get(0).get("matchedTransitions").get(0).get("event").asText())
                .isEqualTo("click.kamil.examples.statemachine.layered.order.OrderTransitionEvent.PAY");
    }

    private static JsonNode readMachineJson(Path outputDir, String configBaseName, ObjectMapper mapper)
            throws Exception {
        Path machineDir;
        try (var stream = Files.list(outputDir)) {
            machineDir = stream
                    .filter(Files::isDirectory)
                    .filter(path -> path.getFileName().toString().endsWith(configBaseName))
                    .findFirst()
                    .orElseThrow(() -> new IllegalStateException("No output for " + configBaseName));
        }
        Path jsonFile = machineDir.resolve(machineDir.getFileName() + ".json");
        return mapper.readTree(jsonFile.toFile());
    }

    private static List<JsonNode> findMatchedCallChains(JsonNode machineJson, String endpointName) {
        JsonNode callChains = machineJson.path("metadata").path("callChains");
        if (!callChains.isArray()) {
            return List.of();
        }
        List<JsonNode> result = new ArrayList<>();
        for (JsonNode chain : callChains) {
            if (!endpointName.equals(chain.path("entryPoint").path("name").asText())) {
                continue;
            }
            JsonNode matched = chain.get("matchedTransitions");
            if (matched != null && matched.isArray() && !matched.isEmpty()) {
                result.add(chain);
            }
        }
        return result;
    }
}
