package p.studio.compiler.messages;

import lombok.Builder;
import lombok.Getter;
import p.studio.utilities.logs.LogAggregator;

@Builder
@Getter
public class BuildingIssue {
    private final boolean error;
    private final String message;
    private final Throwable exception;
    private final String phase;
    private final String code;
    private final Integer fileId;
    private final Integer start;
    private final Integer end;
    private final Integer functionIndex;
    private final Integer pc;

    public void print(LogAggregator logs) {
        final var composed = composeMessage();
        if (error) {
            if (exception != null) {
                logs.error(composed, exception);
            } else {
                logs.error(composed);
            }
        } else {
            logs.warn(composed);
        }
    }

    private String composeMessage() {
        final var sb = new StringBuilder();
        if (phase != null && !phase.isBlank()) {
            sb.append('[').append(phase).append(']').append(' ');
        }
        if (code != null && !code.isBlank()) {
            sb.append('(').append(code).append(')').append(' ');
        }
        sb.append(message == null ? "" : message);
        if (fileId != null && fileId >= 0) {
            final var safeStart = start == null ? -1 : start;
            final var safeEnd = end == null ? -1 : end;
            sb.append(" [file=").append(fileId)
                    .append(':').append(safeStart)
                    .append('-').append(safeEnd)
                    .append(']');
        }
        if (functionIndex != null && functionIndex >= 0) {
            sb.append(" [fn=").append(functionIndex).append(']');
        }
        if (pc != null && pc >= 0) {
            sb.append(" [pc=").append(pc).append(']');
        }
        return sb.toString().trim();
    }
}
