package jnpf.attendance.schedule;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * 半小时时间段标签解析（与 {@link SimilarHistoricalJobSlotRow#getSlotRangeLabel()} 约定一致）。
 */
public final class HalfHourSlotLabel {

    private static final DateTimeFormatter HM = DateTimeFormatter.ofPattern("HH:mm");

    /** 展示用：小时不补零（如 {@code 9:00-14:00}），与 {@link #HM} 的语义、跨日尾段规则一致。 */
    private static final DateTimeFormatter HM_DISPLAY = DateTimeFormatter.ofPattern("H:mm");

    private HalfHourSlotLabel() {}

    /** 左闭右开 [startInclusiveMinute, endExclusiveMinute)，0～1440；尾段 {@code xx:xx-00:00} 视为跨到 24:00。 */
    public static int[] startEndExclusiveMinutes(String slotRangeLabel) {
        if (slotRangeLabel == null) {
            return new int[] {0, 0};
        }
        String s = slotRangeLabel.trim();
        int dash = s.indexOf('-');
        if (dash < 0) {
            return new int[] {0, 0};
        }
        String a = s.substring(0, dash).trim();
        String b = s.substring(dash + 1).trim();
        try {
            int sm = localTimeToMinute(LocalTime.parse(a, HM));
            int em = localTimeToMinute(LocalTime.parse(b, HM));
            if ("00:00".equals(b) && sm >= 23 * 60) {
                em = 24 * 60;
            } else if (em <= sm && em > 0) {
                em += 24 * 60;
            }
            return new int[] {sm, em};
        } catch (DateTimeParseException e) {
            return new int[] {0, 0};
        }
    }

    public static int localTimeToMinute(LocalTime t) {
        return t.getHour() * 60 + t.getMinute();
    }

    public static String formatMinuteRange(int startInclusiveMinute, int endExclusiveMinute) {
        int sm = Math.max(0, Math.min(24 * 60, startInclusiveMinute));
        int em = Math.max(0, Math.min(24 * 60, endExclusiveMinute));
        LocalTime st = LocalTime.of(sm / 60, sm % 60);
        if (em >= 24 * 60) {
            return st.format(HM) + "-00:00";
        }
        LocalTime en = LocalTime.of(em / 60, em % 60);
        return st.format(HM) + "-" + en.format(HM);
    }

    /**
     * 与 {@link #formatMinuteRange} 相同的起止语义，展示为小时不补零的 {@code H:mm-H:mm}（如 {@code 9:00-14:00}）。
     */
    public static String formatMinuteRangeDisplay(int startInclusiveMinute, int endExclusiveMinute) {
        int sm = Math.max(0, Math.min(24 * 60, startInclusiveMinute));
        int em = Math.max(0, Math.min(24 * 60, endExclusiveMinute));
        LocalTime st = LocalTime.of(sm / 60, sm % 60);
        if (em >= 24 * 60) {
            return st.format(HM_DISPLAY) + "-" + LocalTime.MIDNIGHT.format(HM_DISPLAY);
        }
        LocalTime en = LocalTime.of(em / 60, em % 60);
        return st.format(HM_DISPLAY) + "-" + en.format(HM_DISPLAY);
    }

    public static boolean overlaps(int slotS, int slotE, int winS, int winE) {
        return slotS < winE && winS < slotE;
    }
}
