package com.infoepoch.pms.agent.platform.shared.observation;

import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 会话级工具轨迹事件缓冲区。
 */
@Component
public class ToolExecutionTraceBuffer {

    private final Map<String, List<ToolExecutionTraceEvent>> buffer = new ConcurrentHashMap<>();
    private final Map<String, List<ToolExecutionTraceEvent>> history = new ConcurrentHashMap<>();

    /**
     * 追加事件到指定线程缓冲区。
     */
    public void append(String threadId, ToolExecutionTraceEvent event) {
        buffer.computeIfAbsent(threadId, key -> new ArrayList<>()).add(event);
        history.computeIfAbsent(threadId, key -> new ArrayList<>()).add(event);
    }

    /**
     * 取出并清空当前已积累的事件。
     */
    public List<ToolExecutionTraceEvent> drain(String threadId) {
        List<ToolExecutionTraceEvent> events = buffer.remove(threadId);
        if (events == null) {
            return List.of();
        }
        return List.copyOf(events);
    }

    /**
     * 获取当前线程的完整轨迹快照。
     */
    public List<ToolExecutionTraceEvent> snapshot(String threadId) {
        List<ToolExecutionTraceEvent> events = history.get(threadId);
        if (events == null) {
            return List.of();
        }
        return List.copyOf(events);
    }

    /**
     * 清理线程缓冲区。
     */
    public void clear(String threadId) {
        buffer.remove(threadId);
        history.remove(threadId);
    }
}
