package tech.easyflow.agent.runtime.artifact;

import org.springframework.stereotype.Component;
import tech.easyflow.agent.runtime.AgentRuntimeStateCleanupService;
import tech.easyflow.chatlog.domain.dto.ChatMessageRecord;
import tech.easyflow.chatlog.domain.dto.ChatSessionSummary;
import tech.easyflow.chatlog.service.ChatSessionExtension;
import tech.easyflow.common.web.exceptions.BusinessException;

import java.math.BigInteger;
import java.util.List;
import java.util.Objects;

/**
 * Agent 会话的 Artifact 生命周期与历史安全投影扩展。
 */
@Component
public class AgentArtifactChatSessionExtension implements ChatSessionExtension {

    private static final String AGENT_ASSISTANT_CODE = "AGENT";

    private final AgentRuntimeStateCleanupService runtimeStateCleanupService;
    private final AgentArtifactService artifactService;

    /**
     * 创建 Agent 会话扩展。
     *
     * @param runtimeStateCleanupService Agent 运行态清理服务
     * @param artifactService Artifact 服务
     */
    public AgentArtifactChatSessionExtension(AgentRuntimeStateCleanupService runtimeStateCleanupService,
                                             AgentArtifactService artifactService) {
        this.runtimeStateCleanupService = runtimeStateCleanupService;
        this.artifactService = artifactService;
    }

    @Override
    public boolean supports(ChatSessionSummary summary) {
        return summary != null && AGENT_ASSISTANT_CODE.equals(summary.getAssistantCode());
    }

    @Override
    public void beforeDelete(ChatSessionSummary summary, BigInteger userId, BigInteger operatorId) {
        requireIdentity(summary, userId);
        runtimeStateCleanupService.clearChatSession(summary.getId(), userId);
    }

    @Override
    public void afterDelete(ChatSessionSummary summary, BigInteger userId, BigInteger operatorId) {
        requireIdentity(summary, userId);
        artifactService.markSessionDeletePending(
                summary.getTenantId(), userId, summary.getAssistantId(), summary.getId());
    }

    @Override
    public void projectMessages(ChatSessionSummary summary, List<ChatMessageRecord> records) {
        requireIdentity(summary, summary.getUserId());
        artifactService.projectHistoryArtifacts(records,
                summary.getTenantId(), summary.getUserId(), summary.getAssistantId(), summary.getId());
    }

    private void requireIdentity(ChatSessionSummary summary, BigInteger userId) {
        if (summary == null || summary.getId() == null || summary.getTenantId() == null
                || summary.getAssistantId() == null || summary.getUserId() == null
                || !Objects.equals(summary.getUserId(), userId)) {
            throw new BusinessException("Agent 会话归属不完整");
        }
    }
}
