package click.kamil.springstatemachineexporter;

import org.junit.jupiter.api.Test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

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

/**
 * Runs the golden JSON consistency audit script as a regression gate.
 */
class GoldenJsonAuditTest {

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

    @Test
    void goldenJsonExportsShouldPassConsistencyAudit() throws Exception {
        Path moduleRoot = findProjectRoot().resolve("state_machine_exporter");
        Path script = moduleRoot.resolve("scripts/audit_golden_json.py");
        assertThat(script).exists();

        Process process = new ProcessBuilder("python3", script.toString())
                .directory(moduleRoot.toFile())
                .redirectErrorStream(true)
                .start();

        String output;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            output = reader.lines().collect(Collectors.joining("\n"));
        }

        assertThat(process.waitFor(60, TimeUnit.SECONDS))
                .as("audit script timed out\n%s", output)
                .isTrue();
        assertThat(process.exitValue())
                .as("audit script failed\n%s", output)
                .isZero();
        assertThat(output).contains("Total BUG+WARN: 0");
    }
}
