package p.studio.compiler.workspaces.stages;

import lombok.extern.slf4j.Slf4j;
import p.studio.compiler.messages.BuildingIssueSink;
import p.studio.compiler.messages.DependencyConfig;
import p.studio.compiler.models.BuilderPipelineContext;
import p.studio.compiler.source.tables.FileTable;
import p.studio.compiler.workspaces.DependencyService;
import p.studio.compiler.workspaces.PipelineStage;
import p.studio.utilities.logs.LogAggregator;

import java.io.IOException;
import java.nio.file.Paths;

@Slf4j
public class ResolveDepsPipelineStage implements PipelineStage {
    @Override
    public BuildingIssueSink run(final BuilderPipelineContext ctx, LogAggregator logs) {
        try {
            ctx.rootProjectPathCanon = Paths.get(ctx.config.rootProjectPath()).toRealPath();
        } catch (IOException e) {
            return BuildingIssueSink.empty()
                    .report(builder -> builder
                            .error(true)
                            .message("[BUILD]: root project directory no found: " + ctx.config.rootProjectPath())
                            .exception(e));
        }
        final var dependencyConfig = new DependencyConfig(ctx.config.explain(), ctx.rootProjectPathCanon);
        ctx.resolvedWorkspace = DependencyService.INSTANCE.run(dependencyConfig, logs);
        ctx.fileTable = new FileTable(ctx.resolvedWorkspace.graph().projectTable().size());
        return BuildingIssueSink.empty();
    }
}
