package click.kamil.springstatemachineexporter;

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 net.sourceforge.plantuml.FileFormat;
import net.sourceforge.plantuml.FileFormatOption;
import net.sourceforge.plantuml.SourceStringReader;

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

public class GoldenUpdater {

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

    public static void main(String[] args) throws Exception {
        List<TestScenario> scenarios = provideTestScenarios();
        Path rootDir = Path.of("state_machine_exporter");

        for (TestScenario scenario : scenarios) {
            System.out.println("Updating golden files for: " + scenario.name());
            Path tempDir = Files.createTempDirectory("golden-update-");
            try {
                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);

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

                String actualBaseName = actualDir.getFileName().toString();
                Path goldenDirPath = rootDir.resolve(scenario.goldenPath());
                Files.createDirectories(goldenDirPath);

                for (StateMachineExporter exporter : exporters) {
                    String fileName = actualBaseName + exporter.getFileExtension();
                    String goldenFileName = targetBaseName + exporter.getFileExtension();

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

                    System.out.println("  Writing " + goldenFile);
                    Files.copy(actualFile, goldenFile, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
                    
                    // Special case for PlantUML: also generate PNG
                    if (exporter instanceof PlantUml) {
                        String pngFileName = targetBaseName + ".png";
                        Path goldenPngFile = goldenDirPath.resolve(pngFileName);
                        System.out.println("  Rendering " + goldenPngFile);
                        
                        String pumlContent = Files.readString(actualFile);
                        SourceStringReader reader = new SourceStringReader(pumlContent);
                        ByteArrayOutputStream os = new ByteArrayOutputStream();
                        reader.outputImage(os, new FileFormatOption(FileFormat.PNG));
                        Files.write(goldenPngFile, os.toByteArray());
                    }
                }
            } finally {
                // delete tempDir
                deleteDirectory(tempDir);
            }
        }
    }

    private static void deleteDirectory(Path path) throws IOException {
        if (Files.isDirectory(path)) {
            try (var stream = Files.list(path)) {
                for (Path p : stream.toList()) {
                    deleteDirectory(p);
                }
            }
        }
        Files.delete(path);
    }

    private static List<TestScenario> provideTestScenarios() {
        return List.of(
                new TestScenario(
                        "Complex State Machine",
                        Path.of("state_machines/complex_state_machine"),
                        Path.of("src/test/resources/golden/ComplexStateMachineConfig"),
                        "ComplexStateMachineConfig"
                ),
                new TestScenario(
                        "Fork Join State Machine",
                        Path.of("state_machines/forkjoin_state_machine"),
                        Path.of("src/test/resources/golden/ForkJoinStateMachineConfig"),
                        "ForkJoinStateMachineConfig"
                ),
                new TestScenario(
                        "Kamil Enum State Machine",
                        Path.of("state_machines/enumstate_state_machine"),
                        Path.of("src/test/resources/golden/KamilEnumStateMachineConfiguration"),
                        "KamilEnumStateMachineConfiguration"
                ),
                new TestScenario(
                        "Simple Enum Join State Machine",
                        Path.of("state_machines/simple_state_machine"),
                        Path.of("src/test/resources/golden/SimpleEnumStateMachineConfiguration"),
                        "SimpleEnumStateMachineConfiguration"
                ),
                new TestScenario(
                        "One State Machine (Inheritance)",
                        Path.of("state_machines/inheritance_state_machine"),
                        Path.of("src/test/resources/golden/OneStateMachineConfiguration"),
                        "OneStateMachineConfiguration"
                ),
                new TestScenario(
                        "Two State Machine (Extra Functions)",
                        Path.of("state_machines/inheritance_extra_functions_state_machine"),
                        Path.of("src/test/resources/golden/TwoStateMachineExtraFunctionsConfiguration"),
                        "TwoStateMachineConfiguration"
                ),
                new TestScenario(
                        "Three State Machine (Extra Functions 2)",
                        Path.of("state_machines/inheritance_extra_functions2_state_machine"),
                        Path.of("src/test/resources/golden/ThreeStateMachineConfiguration"),
                        "ThreeStateMachineConfiguration"
                ),
                new TestScenario(
                        "F1 State Machine (Example 4)",
                        Path.of("state_machines/inheritance_extra_functions3_state_machine"),
                        Path.of("src/test/resources/golden/F1StateMachineConfiguration"),
                        "F1StateMachineConfiguration"
                ),
                new TestScenario(
                        "F2 State Machine (Example 4)",
                        Path.of("state_machines/inheritance_extra_functions3_state_machine"),
                        Path.of("src/test/resources/golden/F2StateMachineConfiguration"),
                        "F2StateMachineConfiguration"
                ),
                new TestScenario(
                        "G1 State Machine (Example 4)",
                        Path.of("state_machines/inheritance_extra_functions3_state_machine"),
                        Path.of("src/test/resources/golden/G1StateMachineConfiguration"),
                        "G1StateMachineConfiguration"
                ),
                new TestScenario(
                        "G2 State Machine (Example 4)",
                        Path.of("state_machines/inheritance_extra_functions3_state_machine"),
                        Path.of("src/test/resources/golden/G2StateMachineConfiguration"),
                        "G2StateMachineConfiguration"
                ),
                new TestScenario(
                        "Extended Analysis Sample",
                        Path.of("state_machines/extended_analysis_sample"),
                        Path.of("src/test/resources/golden/ExtendedStateMachineConfig"),
                        "ExtendedStateMachineConfig"
                ),
                new TestScenario(
                        "Payment State Machine (Extended Sample)",
                        Path.of("state_machines/extended_analysis_sample"),
                        Path.of("src/test/resources/golden/PaymentStateMachineConfig"),
                        "PaymentStateMachineConfig"
                ),
                new TestScenario(
                        "Extended Analysis Sample (PROD)",
                        Path.of("state_machines/extended_analysis_sample"),
                        Path.of("src/test/resources/golden/ExtendedStateMachineConfig_PROD"),
                        "ExtendedStateMachineConfig",
                        List.of("prod")
                ),
                new TestScenario(
                        "Inheritance Sample",
                        Path.of("state_machines/inheritance_sample"),
                        Path.of("src/test/resources/golden/InheritanceStateMachineConfig"),
                        "InheritanceStateMachineConfig"
                ),
                new TestScenario(
                        "Enterprise Order System",
                        Path.of("state_machines/enterprise_order_system"),
                        Path.of("src/test/resources/golden/EnterpriseStateMachineConfig"),
                        "EnterpriseStateMachineConfig"
                ),
                new TestScenario(
                        "Enterprise Order State Machine",
                        Path.of("state_machines/state_machine_enterprise"),
                        Path.of("src/test/resources/golden/OrderStateMachineConfiguration"),
                        "OrderStateMachineConfiguration"
                ),
                new TestScenario(
                        "Multi-Module Sample",
                        Path.of("state_machines/multi_module_sample/core-module"),
                        Path.of("src/test/resources/golden/OrderStateMachineConfig"),
                        "OrderStateMachineConfig"
                ),
                new TestScenario(
                        "Maven Multi-Module Sample",
                        Path.of("state_machines/maven_multi_module/core-module"),
                        Path.of("src/test/resources/golden/MavenOrderStateMachine"),
                        "MavenOrderStateMachine"
                ),
                new TestScenario(
                        "Complex Multi-Module Sample",
                        Path.of("state_machines/complex_multi_module_sm"),
                        Path.of("src/test/resources/golden/StateMachineConfig"),
                        "StateMachineConfig"
                ),
                new TestScenario(
                        "Polymorphic Events Sample",
                        Path.of("state_machines/polymorphic_events_sample"),
                        Path.of("src/test/resources/golden/PolymorphicStateMachineConfiguration"),
                        "PolymorphicStateMachineConfiguration"
                ),
                new TestScenario(
                        "Layered Dispatcher (Order)",
                        Path.of("state_machines/layered_dispatcher_sample"),
                        Path.of("src/test/resources/golden/StandardOrderStateMachineConfiguration"),
                        "StandardOrderStateMachineConfiguration"
                ),
                new TestScenario(
                        "Layered Dispatcher (Document)",
                        Path.of("state_machines/layered_dispatcher_sample"),
                        Path.of("src/test/resources/golden/StandardDocumentStateMachineConfiguration"),
                        "StandardDocumentStateMachineConfiguration"
                ),
                new TestScenario(
                        "Enterprise Document State Machine",
                        Path.of("state_machines/state_machine_enterprise"),
                        Path.of("src/test/resources/golden/DocumentStateMachineConfiguration"),
                        "DocumentStateMachineConfiguration"
                ),
                new TestScenario(
                        "Enterprise User State Machine",
                        Path.of("state_machines/state_machine_enterprise"),
                        Path.of("src/test/resources/golden/UserStateMachineConfiguration"),
                        "UserStateMachineConfiguration"
                )
        );
    }
}
