package click.kamil.springstatemachineexporter;

import click.kamil.springstatemachineexporter.analysis.service.EnrichmentService;
import click.kamil.springstatemachineexporter.exporter.PlantUml;
import click.kamil.springstatemachineexporter.exporter.StateMachineExporter;
import click.kamil.springstatemachineexporter.service.ExportService;
import click.kamil.springstatemachineexporter.utils.TestScenario;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;

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

@Tag("render")
public class PlantUmlRenderTest {

    private final List<StateMachineExporter> exporters = List.of(new PlantUml());
    private final EnrichmentService enrichmentService = new EnrichmentService(Collections.emptyList());
    private final ExportService exportService = new ExportService(exporters, enrichmentService);

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

    private static List<TestScenario> provideTestScenarios() {
        Path root = findProjectRoot();
        return List.of(
                new TestScenario(
                        "Complex State Machine",
                        root.resolve("state_machines/complex_state_machine"),
                        Path.of("src/test/resources/golden/ComplexStateMachineConfig"),
                        "ComplexStateMachineConfig"
                ),
                new TestScenario(
                        "Fork Join State Machine",
                        root.resolve("state_machines/forkjoin_state_machine"),
                        Path.of("src/test/resources/golden/ForkJoinStateMachineConfig"),
                        "ForkJoinStateMachineConfig"
                ),
                new TestScenario(
                        "Kamil Enum State Machine",
                        root.resolve("state_machines/enumstate_state_machine"),
                        Path.of("src/test/resources/golden/KamilEnumStateMachineConfiguration"),
                        "KamilEnumStateMachineConfiguration"
                ),
                new TestScenario(
                        "Simple Enum Join State Machine",
                        root.resolve("state_machines/simple_state_machine"),
                        Path.of("src/test/resources/golden/SimpleEnumStateMachineConfiguration"),
                        "SimpleEnumStateMachineConfiguration"
                ),
                new TestScenario(
                        "One State Machine (Inheritance)",
                        root.resolve("state_machines/inheritance_state_machine"),
                        Path.of("src/test/resources/golden/OneStateMachineConfiguration"),
                        "OneStateMachineConfiguration"
                ),
                new TestScenario(
                        "Two State Machine (Extra Functions)",
                        root.resolve("state_machines/inheritance_extra_functions_state_machine"),
                        Path.of("src/test/resources/golden/TwoStateMachineExtraFunctionsConfiguration"),
                        "TwoStateMachineConfiguration"
                ),
                new TestScenario(
                        "Three State Machine (Extra Functions 2)",
                        root.resolve("state_machines/inheritance_extra_functions2_state_machine"),
                        Path.of("src/test/resources/golden/ThreeStateMachineConfiguration"),
                        "ThreeStateMachineConfiguration"
                ),
                new TestScenario(
                        "F1 State Machine (Example 4)",
                        root.resolve("state_machines/inheritance_extra_functions3_state_machine"),
                        Path.of("src/test/resources/golden/F1StateMachineConfiguration"),
                        "F1StateMachineConfiguration"
                ),
                new TestScenario(
                        "F2 State Machine (Example 4)",
                        root.resolve("state_machines/inheritance_extra_functions3_state_machine"),
                        Path.of("src/test/resources/golden/F2StateMachineConfiguration"),
                        "F2StateMachineConfiguration"
                ),
                new TestScenario(
                        "G1 State Machine (Example 4)",
                        root.resolve("state_machines/inheritance_extra_functions3_state_machine"),
                        Path.of("src/test/resources/golden/G1StateMachineConfiguration"),
                        "G1StateMachineConfiguration"
                ),
                new TestScenario(
                        "G2 State Machine (Example 4)",
                        root.resolve("state_machines/inheritance_extra_functions3_state_machine"),
                        Path.of("src/test/resources/golden/G2StateMachineConfiguration"),
                        "G2StateMachineConfiguration"
                )
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("provideTestScenarios")
    void testRenderMatchesGolden(TestScenario scenario, @TempDir Path tempDir) throws Exception {
        exportService.runExporter(scenario.inputPath(), tempDir, List.of("puml"), true);

        // Find the generated directory (it might be named with FQN)
        List<Path> generatedDirs;
        try (var stream = Files.list(tempDir)) {
            generatedDirs = stream.filter(Files::isDirectory).toList();
        }

        String targetBaseName = scenario.baseName();
        Path actualDir = generatedDirs.stream()
                .filter(d -> d.getFileName().toString().endsWith(targetBaseName))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("No output directory found for " + targetBaseName + " in " + generatedDirs));

        String actualBaseName = actualDir.getFileName().toString();
        String fileName = actualBaseName + ".puml";
        String goldenFileName = targetBaseName + ".puml";

        Path actualFile = actualDir.resolve(fileName);
        Path goldenFile = scenario.goldenPath().resolve(goldenFileName);

        if (Boolean.getBoolean("updateGolden")) {
            Files.createDirectories(goldenFile.getParent());
            Files.copy(actualFile, goldenFile, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
        } else {
            assertThat(actualFile)
                    .as("File %s should exist in output", fileName)
                    .exists();

            assertThat(actualFile)
                    .as("Content mismatch for %s", fileName)
                    .content().isEqualTo(Files.readString(goldenFile));
        }
    }
}
