package com.gzzm.lobster.skill;

import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;

import static org.junit.Assert.*;

public class SystemSkillLoaderTest {

    @Test
    public void sandboxSkillGetsBundleEvenWhenItOnlyHasResources() throws Exception {
        Path dir = Files.createTempDirectory("canvas-design-skill");
        try {
            Files.write(dir.resolve("SKILL.md"), "---\nname: canvas-design\n---\n".getBytes(StandardCharsets.UTF_8));
            Files.createDirectories(dir.resolve("canvas-fonts"));
            Files.write(dir.resolve("canvas-fonts").resolve("Display.ttf"), new byte[] {0, 1, 2});

            String ref = SystemSkillLoader.assetBundleRefFor(dir, true);

            assertNotNull(ref);
            assertTrue(ref.startsWith("fs://"));
            assertTrue(ref.contains("canvas-design-skill"));
            assertFalse("scripts/ is optional for resource-only sandbox skills", ref.contains("/scripts"));
        } finally {
            deleteTree(dir);
        }
    }

    @Test
    public void guidanceSkillDoesNotGetBundle() throws Exception {
        Path dir = Files.createTempDirectory("guidance-skill");
        try {
            Files.write(dir.resolve("SKILL.md"), "---\nname: guidance\n---\n".getBytes(StandardCharsets.UTF_8));

            assertNull(SystemSkillLoader.assetBundleRefFor(dir, false));
        } finally {
            deleteTree(dir);
        }
    }

    private static void deleteTree(Path root) throws IOException {
        if (root == null || !Files.exists(root)) return;
        Files.walk(root)
                .sorted(Comparator.reverseOrder())
                .forEach(path -> {
                    try {
                        Files.deleteIfExists(path);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
    }
}
