package com.red.circle.other.infra.utils;

import com.red.circle.tool.core.date.ZonedDateTimeAsiaRiyadhUtils;
import com.red.circle.tool.core.date.ZonedId;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.time.LocalDate;
import java.time.ZoneId;import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 赛季工具类（基于星座周期）
 */
public class SeasonUtils {
    
    /**
     * 星座赛季定义
     * 每个赛季对应一个星座周期
     */
    private static final List<SeasonPeriod> SEASON_PERIODS = Arrays.asList(
        new SeasonPeriod("水瓶座", 1, 20, 2, 18),
        new SeasonPeriod("双鱼座", 2, 19, 3, 20),
        new SeasonPeriod("牡羊座", 3, 21, 4, 19),
        new SeasonPeriod("金牛座", 4, 20, 5, 20),
        new SeasonPeriod("双子座", 5, 21, 6, 21),
        new SeasonPeriod("巨蟹座", 6, 22, 7, 22),
        new SeasonPeriod("狮子座", 7, 23, 8, 22),
        new SeasonPeriod("处女座", 8, 23, 9, 22),
        new SeasonPeriod("天秤座", 9, 23, 10, 22),
        new SeasonPeriod("天蝎座", 10, 23, 11, 21),
        new SeasonPeriod("射手座", 11, 22, 12, 21),
        new SeasonPeriod("摩羯座", 12, 22, 1, 19)
    );
    
    /**
     * 获取当前赛季的cycleKey
     * 格式：yyyyMMdd-yyyyMMdd
     */
    public static String getCurrentSeasonCycleKey() {
        ZonedDateTime now = ZonedDateTimeAsiaRiyadhUtils.now();
        return getSeasonCycleKey(now);
    }
    
    /**
     * 获取从指定日期到现在的所有历史赛季 cycleKey（不含当前赛季），从旧到新排列.
     * @param startDate 起始日期（包含该日期所在赛季）
     */
    public static List<String> getAllHistoricalSeasonCycleKeys(LocalDate startDate) {
        List<String> cycleKeys = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String currentSeasonKey = getCurrentSeasonCycleKey();
        ZonedDateTime current = startDate.atStartOfDay(ZonedId.ASIA_RIYADH.getZonedId());
        ZonedDateTime now = ZonedDateTimeAsiaRiyadhUtils.now();

        while (!current.isAfter(now)) {
            String cycleKey = getSeasonCycleKey(current);
            // 当前赛季跳过（仍在进行中）
            if (cycleKey.equals(currentSeasonKey)) {
                break;
            }
            if (!cycleKeys.contains(cycleKey)) {
                cycleKeys.add(cycleKey);
            }
            // 跳到本赛季结束日 +1 天，进入下一个赛季
            String endPart = cycleKey.split("-")[1];
            LocalDate endDate = LocalDate.parse(endPart, formatter);
            current = endDate.plusDays(1).atStartOfDay(ZonedId.ASIA_RIYADH.getZonedId());
        }
        return cycleKeys;
    }

    /**
     * 获取上一个赛季的cycleKey
     * 通过获取当前赛季开始日期前一天，来定位到上一个赛季
     */
    public static String getLastSeasonCycleKey() {
        ZonedDateTime now = ZonedDateTimeAsiaRiyadhUtils.now();
        SeasonPeriod currentSeason = getCurrentSeason(now);
        
        // 获取当前赛季的开始日期
        LocalDate currentSeasonStart = getSeasonStartDate(now, currentSeason);
        
        // 当前赛季开始日期前一天，一定在上一个赛季内
        ZonedDateTime lastSeasonDate = currentSeasonStart.minusDays(1)
            .atStartOfDay(ZonedId.ASIA_RIYADH.getZonedId());
        
        return getSeasonCycleKey(lastSeasonDate);
    }
    
    /**
     * 获取指定日期所在赛季的cycleKey
     */
    public static String getSeasonCycleKey(ZonedDateTime dateTime) {
        SeasonPeriod season = getCurrentSeason(dateTime);
        
        int year = dateTime.getYear();
        
        // 处理跨年的赛季（摩羯座和水瓶座）
        LocalDate startDate;
        LocalDate endDate;
        
        if (season.startMonth > season.endMonth) {
            // 跨年赛季：摩羯座(12/22-1/19)
            if (dateTime.getMonthValue() == season.endMonth) {
                // 如果当前是结束月份(1月)，开始日期在去年
                startDate = LocalDate.of(year - 1, season.startMonth, season.startDay);
                endDate = LocalDate.of(year, season.endMonth, season.endDay);
            } else {
                // 如果当前是开始月份(12月)，结束日期在明年
                startDate = LocalDate.of(year, season.startMonth, season.startDay);
                endDate = LocalDate.of(year + 1, season.endMonth, season.endDay);
            }
        } else {
            // 同年赛季
            startDate = LocalDate.of(year, season.startMonth, season.startDay);
            endDate = LocalDate.of(year, season.endMonth, season.endDay);
        }
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        return startDate.format(formatter) + "-" + endDate.format(formatter);
    }
    
    /**
     * 获取指定日期所在赛季的开始日期
     */
    private static LocalDate getSeasonStartDate(ZonedDateTime dateTime, SeasonPeriod season) {
        int year = dateTime.getYear();
        
        if (season.startMonth > season.endMonth) {
            // 跨年赛季：摩羯座(12/22-1/19)
            if (dateTime.getMonthValue() == season.endMonth) {
                // 如果当前是结束月份(1月)，开始日期在去年
                return LocalDate.of(year - 1, season.startMonth, season.startDay);
            } else {
                // 如果当前是开始月份(12月)
                return LocalDate.of(year, season.startMonth, season.startDay);
            }
        } else {
            // 同年赛季
            return LocalDate.of(year, season.startMonth, season.startDay);
        }
    }
    
    /**
     * 获取当前所在的赛季信息
     */
    private static SeasonPeriod getCurrentSeason(ZonedDateTime dateTime) {
        int month = dateTime.getMonthValue();
        int day = dateTime.getDayOfMonth();
        
        for (SeasonPeriod season : SEASON_PERIODS) {
            if (isInSeason(month, day, season)) {
                return season;
            }
        }
        
        throw new IllegalStateException("无法确定当前赛季");
    }
    
    /**
     * 判断日期是否在赛季内
     */
    private static boolean isInSeason(int month, int day, SeasonPeriod season) {
        if (season.startMonth == season.endMonth) {
            // 同月份
            return month == season.startMonth && day >= season.startDay && day <= season.endDay;
        } else if (season.startMonth < season.endMonth) {
            // 跨月但不跨年
            if (month == season.startMonth) {
                return day >= season.startDay;
            } else if (month == season.endMonth) {
                return day <= season.endDay;
            } else {
                return month > season.startMonth && month < season.endMonth;
            }
        } else {
            // 跨年（摩羯座）
            if (month == season.startMonth) {
                return day >= season.startDay;
            } else if (month == season.endMonth) {
                return day <= season.endDay;
            } else {
                return month > season.startMonth || month < season.endMonth;
            }
        }
    }
    
    /**
     * 赛季周期定义
     */
    @Data
    @AllArgsConstructor
    private static class SeasonPeriod {
        private String name;        // 星座名称
        private int startMonth;     // 开始月份
        private int startDay;       // 开始日期
        private int endMonth;       // 结束月份
        private int endDay;         // 结束日期
    }
}