package p.studio.compiler.messages;

import p.studio.utilities.structures.ReadOnlyList;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

public record HostAdmissionContext(
        ReadOnlyList<String> knownCapabilities,
        ReadOnlyList<String> declaredCapabilities,
        boolean enforceDeclaredCapabilities) {

    private static final ReadOnlyList<String> DEFAULT_KNOWN_CAPABILITIES = ReadOnlyList.wrap(List.of(
            "system",
            "gfx",
            "input",
            "audio",
            "fs",
            "log",
            "asset",
            "bank"));

    public HostAdmissionContext {
        knownCapabilities = knownCapabilities == null || knownCapabilities.isEmpty()
                ? DEFAULT_KNOWN_CAPABILITIES
                : normalize(knownCapabilities);
        declaredCapabilities = declaredCapabilities == null
                ? ReadOnlyList.empty()
                : normalize(declaredCapabilities);
    }

    public static HostAdmissionContext permissiveDefault() {
        return new HostAdmissionContext(DEFAULT_KNOWN_CAPABILITIES, ReadOnlyList.empty(), false);
    }

    public static HostAdmissionContext strictWithDeclaredCapabilities(
            final ReadOnlyList<String> declaredCapabilities) {
        return new HostAdmissionContext(DEFAULT_KNOWN_CAPABILITIES, declaredCapabilities, true);
    }

    private static ReadOnlyList<String> normalize(final ReadOnlyList<String> values) {
        final Set<String> dedup = new LinkedHashSet<>();
        for (final var value : values) {
            if (value == null || value.isBlank()) {
                continue;
            }
            dedup.add(value.trim().toLowerCase(Locale.ROOT));
        }
        return ReadOnlyList.wrap(dedup.stream().toList());
    }
}
