package dev.photosync.core.config;

import lombok.Builder;

/**
 * Unattended screenshots on a timer.
 *
 * <p>Off by default, and deliberately so: a mod that silently starts writing
 * files and uploading them the moment it is installed would be a bad neighbour.
 */
@Builder(toBuilder = true)
public record AutoCaptureSettings(
        boolean enabled,
        int intervalSeconds,
        String fileNameSuffix,
        boolean onlyInWorld,
        boolean skipWhenScreenOpen,
        boolean skipWhenStill) {

    public static final int MIN_INTERVAL_SECONDS = 5;
    public static final int MAX_INTERVAL_SECONDS = 3600;

    public static AutoCaptureSettings defaults() {
        return AutoCaptureSettings.builder()
                .enabled(false)
                .intervalSeconds(300)
                .fileNameSuffix("_auto")
                .onlyInWorld(true)
                .skipWhenScreenOpen(true)
                // On, because the alternative is a hundred identical photographs
                // of wherever the player was standing when they went for lunch.
                .skipWhenStill(true)
                .build();
    }

    AutoCaptureSettings normalized() {
        return toBuilder()
                .intervalSeconds(Math.min(MAX_INTERVAL_SECONDS, Math.max(MIN_INTERVAL_SECONDS, intervalSeconds)))
                .fileNameSuffix(sanitizeSuffix(fileNameSuffix))
                .build();
    }

    /**
     * The suffix lands in a file name, so anything that would break a path has
     * to go. An empty result is allowed -- it just means "no suffix".
     */
    private static String sanitizeSuffix(String raw) {
        if (raw == null) {
            return "";
        }
        StringBuilder clean = new StringBuilder(raw.length());
        raw.chars()
                .filter(ch -> ch > 0x1F && "\\/:*?\"<>|".indexOf(ch) < 0)
                .forEach(ch -> clean.append((char) ch));
        return clean.toString().strip();
    }
}
