package p.studio.projectstate;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public record ProjectLocalStudioSetup(
        String prometeuRuntimePath,
        EditorIndentationSetup editorIndentation) {
    public ProjectLocalStudioSetup {
        prometeuRuntimePath = normalizeText(prometeuRuntimePath);
        editorIndentation = editorIndentation == null
                ? EditorIndentationSetup.defaults()
                : editorIndentation.normalize();
    }

    public static ProjectLocalStudioSetup defaults() {
        return new ProjectLocalStudioSetup(null, EditorIndentationSetup.defaults());
    }

    private static String normalizeText(final String value) {
        if (value == null) {
            return null;
        }
        final String trimmed = value.trim();
        return trimmed.isEmpty() ? null : trimmed;
    }

    @JsonIgnoreProperties(ignoreUnknown = true)
    public record EditorIndentationSetup(
            String mode,
            Integer width) {
        private static final String DEFAULT_MODE = "spaces";
        private static final int DEFAULT_WIDTH = 4;

        public EditorIndentationSetup {
            mode = normalizeMode(mode);
            width = normalizeWidth(width);
        }

        public static EditorIndentationSetup defaults() {
            return new EditorIndentationSetup(DEFAULT_MODE, DEFAULT_WIDTH);
        }

        public EditorIndentationSetup normalize() {
            return new EditorIndentationSetup(mode, width);
        }

        public String statusLabel() {
            return switch (mode) {
                case "tabs" -> "Tabs: " + width;
                default -> "Spaces: " + width;
            };
        }

        public String tabInsertion() {
            return " ".repeat(width);
        }

        private static String normalizeMode(final String value) {
            if (value == null) {
                return DEFAULT_MODE;
            }
            final String normalized = value.trim().toLowerCase();
            if (normalized.isBlank()) {
                return DEFAULT_MODE;
            }
            return switch (normalized) {
                case "tabs", "spaces" -> normalized;
                default -> DEFAULT_MODE;
            };
        }

        private static Integer normalizeWidth(final Integer value) {
            if (value == null || value <= 0) {
                return DEFAULT_WIDTH;
            }
            return value;
        }
    }
}
