package com.infoepoch.pms.agent.domain.itworkbench.state;

import com.infoepoch.pms.agent.config.JsonUtils;
import com.infoepoch.pms.agent.domain.itworkbench.model.WorkbenchConversationState;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.Optional;

/**
 * 工作台智能体 - 会话状态缓存
 */
@Service
@RequiredArgsConstructor
public class WorkbenchConversationStateService {

    private static final String KEY_PREFIX = "workbench:state:";
    private static final Duration TTL = Duration.ofMinutes(120);

    private final RedisTemplate<String, String> redisTemplate;

    public Optional<WorkbenchConversationState> load(String sessionId) {
        if (!StringUtils.hasText(sessionId)) {
            return Optional.empty();
        }
        String json = redisTemplate.opsForValue().get(KEY_PREFIX + sessionId);
        if (!StringUtils.hasText(json)) {
            return Optional.empty();
        }
        try {
            return Optional.ofNullable(JsonUtils.jsonToObject(json, WorkbenchConversationState.class));
        } catch (Exception e) {
            return Optional.empty();
        }
    }

    public void save(WorkbenchConversationState state) {
        if (state == null || !StringUtils.hasText(state.sessionId())) {
            return;
        }
        String json = JsonUtils.objectToJson(state);
        redisTemplate.opsForValue().set(KEY_PREFIX + state.sessionId(), json, TTL);
    }
}
