package p.studio.lsp.services.compiler;

import org.junit.jupiter.api.Test;
import p.studio.lsp.messages.BaselineIssueSeverity;
import p.studio.lsp.messages.LspProjectContext;

import java.nio.file.Files;
import java.nio.file.Path;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

class CompilerLanguageServiceBridgeTest {

    @Test
    void analyzeDocumentReturnsCompilerDiagnosticsForOverlayContent() {
        final Path projectRoot = findRepoRoot(Path.of("").toAbsolutePath().normalize())
                .resolve("test-projects")
                .resolve("main")
                .toAbsolutePath()
                .normalize();
        final Path documentPath = projectRoot.resolve("src").resolve("main.pbs");
        final String invalidOverlay = """
                fn frame() -> void {
                  let broken: int = ;
                }
                """;
        final CompilerLanguageServiceBridge bridge = new CompilerLanguageServiceBridge();

        final var analysis = bridge.analyzeDocument(
                new LspProjectContext("main", "pbs", projectRoot),
                documentPath.toUri().toString(),
                invalidOverlay);

        assertFalse(analysis.issues().isEmpty(), "analyzeDocument must surface compiler diagnostics");
        assertTrue(analysis.issues().stream().anyMatch(issue -> issue.severity() == BaselineIssueSeverity.ERROR));
        assertTrue(analysis.issues().stream().anyMatch(issue -> issue.startLine() == 1));
        assertTrue(analysis.issues().stream().noneMatch(issue -> issue.message().contains("Compiler-backed baseline")));
    }

    private Path findRepoRoot(final Path start) {
        var current = start;
        while (current != null) {
            if (Files.exists(current.resolve("settings.gradle.kts"))
                    && Files.exists(current.resolve("test-projects").resolve("main").resolve("prometeu.json"))) {
                return current;
            }
            current = current.getParent();
        }
        throw new IllegalStateException("unable to locate repository root from " + start);
    }
}
