package com.infoepoch.pms.agent.tool;

import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.DateTimeException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.function.BiFunction;

@Component
public class CurrentTimeTool implements BiFunction<String, ToolContext, String> {

    @Override
    public String apply(@ToolParam(description = "Optional timezone such as Asia/Shanghai") String timezone,
                        ToolContext toolContext) {
        ZoneId zoneId = resolveZoneId(timezone);
        return ZonedDateTime.now(zoneId).format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    }

    private ZoneId resolveZoneId(String timezone) {
        if (!StringUtils.hasText(timezone)) {
            return ZoneId.systemDefault();
        }
        try {
            return ZoneId.of(timezone.trim());
        } catch (DateTimeException exception) {
            return ZoneId.systemDefault();
        }
    }
}
