package p.studio.compiler.services;

import p.studio.compiler.source.identifiers.ModuleId;
import p.studio.compiler.source.tables.ModuleReference;
import p.studio.compiler.source.tables.ModuleTable;
import p.studio.utilities.structures.ReadOnlyList;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

record PbsModuleAssembly(
        ReadOnlyList<PbsParsedSourceFile> parsedSourceFiles,
        Map<ModuleId, Set<ModuleId>> moduleDependencyGraph,
        ReadOnlyList<ModuleReference> canonicalModulePool,
        Set<ModuleId> failedModuleIds,
        ModuleTable moduleTable) {
    PbsModuleAssembly {
        parsedSourceFiles = parsedSourceFiles == null ? ReadOnlyList.empty() : parsedSourceFiles;
        canonicalModulePool = canonicalModulePool == null ? ReadOnlyList.empty() : canonicalModulePool;
        failedModuleIds = failedModuleIds == null ? Set.of() : Set.copyOf(failedModuleIds);

        if (moduleDependencyGraph == null || moduleDependencyGraph.isEmpty()) {
            moduleDependencyGraph = Map.of();
        } else {
            final var copiedGraph = new HashMap<ModuleId, Set<ModuleId>>();
            for (final var entry : moduleDependencyGraph.entrySet()) {
                copiedGraph.put(entry.getKey(), Set.copyOf(entry.getValue() == null ? Set.of() : entry.getValue()));
            }
            moduleDependencyGraph = Map.copyOf(copiedGraph);
        }

        if (moduleTable == null) {
            moduleTable = new ModuleTable();
        }
    }

    Set<ModuleId> mutableFailedModuleIds() {
        return new HashSet<>(failedModuleIds);
    }
}
