package click.kamil.springstatemachineexporter;

import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import click.kamil.springstatemachineexporter.analysis.service.EnrichmentService;
import click.kamil.springstatemachineexporter.exporter.Dot;
import click.kamil.springstatemachineexporter.exporter.JsonExporter;
import click.kamil.springstatemachineexporter.exporter.PlantUml;
import click.kamil.springstatemachineexporter.exporter.Scxml;
import click.kamil.springstatemachineexporter.exporter.StateMachineExporter;
import click.kamil.springstatemachineexporter.service.ExportService;
import click.kamil.springstatemachineexporter.utils.TestScenario;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

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;

public class RegressionTest {

    private static final List<StateMachineExporter> EXPORTERS =
            List.of(new PlantUml(), new Dot(), new Scxml(), new JsonExporter());

    private ExportService exportService() {
        return new ExportService(EXPORTERS);
    }

    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"
                ),
                new TestScenario(
                        "Extended Analysis Sample",
                        root.resolve("state_machines/extended_analysis_sample"),
                        Path.of("src/test/resources/golden/ExtendedStateMachineConfig"),
                        "ExtendedStateMachineConfig"
                ),
                new TestScenario(
                        "Payment State Machine (Extended Sample)",
                        root.resolve("state_machines/extended_analysis_sample"),
                        Path.of("src/test/resources/golden/PaymentStateMachineConfig"),
                        "PaymentStateMachineConfig"
                ),
                new TestScenario(
                        "Extended Analysis Sample (PROD)",
                        root.resolve("state_machines/extended_analysis_sample"),
                        Path.of("src/test/resources/golden/ExtendedStateMachineConfig_PROD"),
                        "ExtendedStateMachineConfig",
                        List.of("prod")
                ),
                new TestScenario(
                        "Inheritance Sample",
                        root.resolve("state_machines/inheritance_sample"),
                        Path.of("src/test/resources/golden/InheritanceStateMachineConfig"),
                        "InheritanceStateMachineConfig"
                ),
                new TestScenario(
                        "Enterprise Order System",
                        root.resolve("state_machines/enterprise_order_system"),
                        Path.of("src/test/resources/golden/EnterpriseStateMachineConfig"),
                        "EnterpriseStateMachineConfig"
                ),
                new TestScenario(
                        "Enterprise Factory Order Machine",
                        root.resolve("state_machines/state_machine_enterprise"),
                        Path.of("src/test/resources/golden/OrderStateMachineConfiguration"),
                        "OrderStateMachineConfiguration"
                ),
                new TestScenario(
                        "Multi-Module Sample",
                        root.resolve("state_machines/multi_module_sample/core-module"),
                        Path.of("src/test/resources/golden/OrderStateMachineConfig"),
                        "OrderStateMachineConfig"
                ),
                new TestScenario(
                        "Maven Multi-Module Sample",
                        root.resolve("state_machines/maven_multi_module/core-module"),
                        Path.of("src/test/resources/golden/MavenOrderStateMachine"),
                        "MavenOrderStateMachine"
                ),
                new TestScenario(
                        "Complex Multi-Module Sample",
                        root.resolve("state_machines/complex_multi_module_sm"),
                        Path.of("src/test/resources/golden/StateMachineConfig"),
                        "StateMachineConfig"
                ),
                new TestScenario(
                        "Polymorphic Events Sample",
                        root.resolve("state_machines/polymorphic_events_sample"),
                        Path.of("src/test/resources/golden/PolymorphicStateMachineConfiguration"),
                        "PolymorphicStateMachineConfiguration"
                ),
                new TestScenario(
                        "Layered Dispatcher (Order)",
                        root.resolve("state_machines/layered_dispatcher_sample"),
                        Path.of("src/test/resources/golden/StandardOrderStateMachineConfiguration"),
                        "StandardOrderStateMachineConfiguration"
                ),
                new TestScenario(
                        "Layered Dispatcher (Document)",
                        root.resolve("state_machines/layered_dispatcher_sample"),
                        Path.of("src/test/resources/golden/StandardDocumentStateMachineConfiguration"),
                        "StandardDocumentStateMachineConfiguration"
                ),
                new TestScenario(
                        "Enterprise Document State Machine",
                        root.resolve("state_machines/state_machine_enterprise"),
                        Path.of("src/test/resources/golden/DocumentStateMachineConfiguration"),
                        "DocumentStateMachineConfiguration"
                ),
                new TestScenario(
                        "Enterprise User State Machine",
                        root.resolve("state_machines/state_machine_enterprise"),
                        Path.of("src/test/resources/golden/UserStateMachineConfiguration"),
                        "UserStateMachineConfiguration"
                )
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("provideTestScenarios")
    @Execution(ExecutionMode.CONCURRENT)
    void testOutputMatchesGolden(TestScenario scenario, @TempDir Path tempDir) throws Exception {
        System.out.println("Running test for " + scenario.name());
        ExportService exportService = exportService();
        if (scenario.inputPath() == null) System.out.println("inputPath is NULL");
        if (tempDir == null) System.out.println("tempDir is NULL");
        
        exportService.runExporter(scenario.inputPath(), tempDir, List.of("puml", "dot", "scxml", "json"), true, scenario.activeProfiles(), null, null, click.kamil.springstatemachineexporter.exporter.EnumFormat.fn, click.kamil.springstatemachineexporter.exporter.EnumFormat.fn);

        // 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();

List<Path> generatedFiles;
try (var stream = Files.list(actualDir)) {
    generatedFiles = stream.filter(Files::isRegularFile).toList();
}

for (Path actualFile : generatedFiles) {
    String fileName = actualFile.getFileName().toString();
    // Map actual filename to golden filename (handle FQN difference)
    String goldenFileName = fileName.replace(actualBaseName, targetBaseName);
    Path goldenFile = scenario.goldenPath().resolve(goldenFileName);

    if (System.getProperty("updateGolden", "false").equals("true")) {
        Files.createDirectories(scenario.goldenPath());
        Files.copy(actualFile, goldenFile, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
        System.out.println("Updated golden file: " + goldenFile);
    } else {
        assertThat(goldenFile)
                .as("Golden file missing for %s", fileName)
                .exists();

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

