package p.studio.compiler.utilities;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import p.studio.compiler.messages.BuildingIssueSink;

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

import static org.junit.jupiter.api.Assertions.*;

class PrometeuManifestUtilsTest {

    @TempDir
    Path tempDir;

    @Test
    void buildManifestParsesStdlib() throws IOException {
        final var manifestPath = writeManifest("""
                {
                  "name": "main",
                  "version": "1.0.0",
                  "language": "pbs",
                  "stdlib": "1",
                  "dependencies": []
                }
                """);

        final var issues = BuildingIssueSink.empty();
        final var manifest = PrometeuManifestUtils.buildManifest(tempDir, manifestPath, issues);

        assertTrue(manifest.isPresent());
        assertFalse(issues.hasErrors());
        assertEquals(1, manifest.get().stdlib());
    }

    @Test
    void buildManifestRejectsMissingStdlib() throws IOException {
        final var manifestPath = writeManifest("""
                {
                  "name": "main",
                  "version": "1.0.0",
                  "language": "pbs",
                  "dependencies": []
                }
                """);

        final var issues = BuildingIssueSink.empty();
        final var manifest = PrometeuManifestUtils.buildManifest(tempDir, manifestPath, issues);

        assertTrue(manifest.isEmpty());
        assertTrue(issues.hasErrors());
        assertTrue(issues.asCollection().stream().anyMatch(issue -> issue.getMessage().contains("missing 'stdlib'")));
    }

    @Test
    void buildManifestRejectsNonMajorStdlib() throws IOException {
        final var manifestPath = writeManifest("""
                {
                  "name": "main",
                  "version": "1.0.0",
                  "language": "pbs",
                  "stdlib": "1.0",
                  "dependencies": []
                }
                """);

        final var issues = BuildingIssueSink.empty();
        final var manifest = PrometeuManifestUtils.buildManifest(tempDir, manifestPath, issues);

        assertTrue(manifest.isEmpty());
        assertTrue(issues.hasErrors());
        assertTrue(issues.asCollection().stream().anyMatch(issue -> issue.getMessage().contains("invalid 'stdlib'")));
    }

    private Path writeManifest(final String content) throws IOException {
        final var manifestPath = tempDir.resolve("prometeu.json");
        Files.writeString(manifestPath, content);
        return manifestPath;
    }
}
