package cn.iocoder.yudao.module.llm.handler;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class AigcCustomDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
    private static final DateTimeFormatter FORMATTER_WITH_SPACE = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter FORMATTER_WITH_T = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

    @Override
    public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String dateTimeString = jsonParser.getValueAsString();
        String dateTimeString1 = dateTimeString.replaceAll("\\..*", "");
        try {
            return LocalDateTime.parse(dateTimeString1, FORMATTER_WITH_SPACE);
        } catch (DateTimeParseException e1) {
            try {
                return LocalDateTime.parse(dateTimeString1, FORMATTER_WITH_T);
            } catch (DateTimeParseException e2) {
                throw new RuntimeException("Failed to parse date time string: " + dateTimeString1, e2);
            }
        }
    }
}
