package com.microservices.mon.k8s.utils;

import com.microservices.common.core.exception.ServiceException;

import java.util.Calendar;
import java.util.Date;

public class DateTimeNormalizer {

    private static final int[] NORMAL_HOURS = {0, 6, 12, 18};

    /**
     * 规范化
     *
     * @param start 开始时间（可为 null）
     * @param end   结束时间（可为 null）
     * @return 0-开始，1-结束
     */
    public static Date[] normalize(Date start, Date end) {
        Date now = new Date();
        if (end == null) {
            end = now;
        }
        if (start == null) {
            // 如果开始时间为空则设置默认值为结束时间前十天
            Calendar c = Calendar.getInstance();
            c.setTime(end);
            c.add(Calendar.DAY_OF_MONTH, -10);
            start = c.getTime();
        }

        if (start.after(end)) {
            throw new ServiceException("开始时间不能晚于结束时间");
        }
        start = normalizeDown(start);
        end = normalizeUp(end);
        return new Date[]{start, end};
    }

    /* ---------- 核心工具 ---------- */

    private static Date normalizeDown(Date d) {
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        int hour = c.get(Calendar.HOUR_OF_DAY);
        int target = 0;
        for (int i = NORMAL_HOURS.length - 1; i >= 0; i--) {
            if (NORMAL_HOURS[i] <= hour) {
                target = NORMAL_HOURS[i];
                break;
            }
        }
        if (target > hour) {          // 说明 hour < 0（不可能），或向前跨天
            c.add(Calendar.DATE, -1);
            target = 18;
        }
        c.set(Calendar.HOUR_OF_DAY, target);
        return c.getTime();
    }

    private static Date normalizeUp(Date d) {
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);

        int hour = c.get(Calendar.HOUR_OF_DAY);
        int target = 0;
        for (int nh : NORMAL_HOURS) {
            if (nh >= hour) {
                target = nh;
                break;
            }
        }
        if (target < hour) {          // 说明需要次日 00:00
            c.add(Calendar.DATE, 1);
        }
        c.set(Calendar.HOUR_OF_DAY, target);
        return c.getTime();
    }

    /* ---------- 简单测试 ---------- */
    public static void main(String[] args) {
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date start = parse("2025-10-01 04:59:21");
        Date end = parse("2025-10-11 11:02:03");

        Date[] r1 = normalize(start, end);
        System.out.println("开始: " + sdf.format(r1[0]));
        System.out.println("结束: " + sdf.format(r1[1]));

        Date[] r2 = normalize(null, end);
        System.out.println("开始: " + sdf.format(r2[0]));
        System.out.println("结束: " + sdf.format(r2[1]));

        Date[] r3 = normalize(start, null);
        System.out.println("开始: " + sdf.format(r3[0]));
        System.out.println("结束: " + sdf.format(r3[1]));
    }

    private static Date parse(String s) {
        try {
            return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(s);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
