package p.studio.compiler.workspaces;

import lombok.extern.slf4j.Slf4j;
import p.studio.compiler.exceptions.BuildException;
import p.studio.compiler.messages.DependencyConfig;
import p.studio.compiler.models.DependencyContext;
import p.studio.compiler.models.ResolvedWorkspace;
import p.studio.compiler.workspaces.phases.*;
import p.studio.utilities.logs.LogAggregator;

import java.util.List;

@Slf4j
public final class DependencyService {
    public final static DependencyService INSTANCE;

    static {
        final var phases = List.of(
                new SeedPhase(),
                new DiscoverPhase(),
                new WireProjectsPhase(),
                new ValidatePhase(),
                new StackPhase()
        );
        INSTANCE = new DependencyService(phases);
    }

    private final List<DependencyPhase> phases;

    DependencyService(List<DependencyPhase> phases) {
        this.phases = phases;
    }

    public ResolvedWorkspace run(
            final DependencyConfig config,
            final LogAggregator logs) {
        final var ctx = DependencyContext.basedOn(config);

        for (final var dependencyPhase : phases) {
            final var issues = dependencyPhase.run(ctx);
            issues.forEach(issue -> issue.print(logs.using(log)));
            if (issues.hasErrors()) {
                throw new BuildException("[DEPS]: issues found during dependency phase: " + dependencyPhase.getClass().getSimpleName());
            }
        }

        logs.using(log).info("[DEPS]: dependency completed successfully");

        return ctx.toResolvedWorkspace();
    }
}
