package tech.easyflow.agent.runtime;

import org.springframework.stereotype.Service;
import tech.easyflow.agent.runtime.hitl.AgentHitlPendingService;
import tech.easyflow.agent.runtime.session.EasyFlowAgentSessionStore;

import java.math.BigInteger;

/**
 * Agent 运行态持久化状态清理服务。
 */
@Service
public class AgentRuntimeStateCleanupService {

    private final AgentRunRegistry agentRunRegistry;
    private final EasyFlowAgentSessionStore sessionStore;
    private final AgentHitlPendingService pendingService;

    /**
     * 创建清理服务。
     *
     * @param agentRunRegistry 当前节点运行态注册表
     * @param sessionStore AgentScope session store
     * @param pendingService HITL pending 服务
     */
    public AgentRuntimeStateCleanupService(AgentRunRegistry agentRunRegistry,
                                           EasyFlowAgentSessionStore sessionStore,
                                           AgentHitlPendingService pendingService) {
        this.agentRunRegistry = agentRunRegistry;
        this.sessionStore = sessionStore;
        this.pendingService = pendingService;
    }

    /**
     * 清理指定正式聊天会话关联的 Agent 运行态。
     *
     * @param chatSessionId chatlog 会话 ID
     * @param userId 当前用户 ID
     */
    public void clearChatSession(BigInteger chatSessionId, BigInteger userId) {
        if (chatSessionId == null) {
            return;
        }
        String runtimeSessionId = chatSessionId.toString();
        agentRunRegistry.cancelSession(runtimeSessionId, userId == null ? null : userId.toString());
        sessionStore.deleteByChatSessionId(chatSessionId);
        pendingService.deleteByChatSessionId(chatSessionId);
    }
}
