package tech.easyflow.agent.runtime.output;

import com.easyagents.agent.runtime.event.AgentRuntimeEvent;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import tech.easyflow.core.chat.protocol.ChatDomain;
import tech.easyflow.core.chat.protocol.ChatEnvelope;
import tech.easyflow.core.chat.protocol.ChatType;
import tech.easyflow.core.chat.protocol.sse.ChatSseEmitter;

import java.util.Map;
import java.util.Objects;

/**
 * 保持现有 EasyFlow ChatEnvelope 行为的运行输出。
 */
public final class LegacyAgentRunOutput implements AgentRunOutput {

    private final ChatSseEmitter delegate;

    /**
     * 创建 Legacy 输出。
     */
    public LegacyAgentRunOutput() {
        this(new ChatSseEmitter());
    }

    /**
     * 使用指定 SSE 发射器创建 Legacy 输出。
     *
     * @param delegate SSE 发射器
     */
    public LegacyAgentRunOutput(ChatSseEmitter delegate) {
        this.delegate = Objects.requireNonNull(delegate, "delegate cannot be null");
    }

    @Override
    public SseEmitter emitter() {
        return delegate.getEmitter();
    }

    @Override
    public boolean emitRuntimeEvent(AgentRuntimeEvent event) {
        return !delegate.isClosed();
    }

    @Override
    public boolean emitViewEvent(ChatDomain domain, ChatType type, Object payload) {
        ChatEnvelope<Object> envelope = new ChatEnvelope<>();
        envelope.setDomain(domain);
        envelope.setType(type);
        envelope.setPayload(payload);
        return delegate.send(envelope);
    }

    @Override
    public boolean finish(String finalText) {
        ChatEnvelope<Map<String, Object>> envelope = new ChatEnvelope<>();
        envelope.setDomain(ChatDomain.SYSTEM);
        envelope.setType(ChatType.DONE);
        if (finalText != null) {
            envelope.setPayload(Map.of("finalText", finalText));
        }
        return delegate.sendDone(envelope);
    }

    @Override
    public void complete() {
        delegate.complete();
    }

    @Override
    public void completeWithError(Throwable error) {
        delegate.completeWithError(error);
    }

    @Override
    public boolean isClosed() {
        return delegate.isClosed();
    }
}
