// 简单的流式数据管理器：开启流、更新流、订阅流、关闭流
const streams = {};

function notify(stream) {
  stream.subs.forEach((cb) => cb(stream.text, stream.finished, stream.payload));
}

function openStream(id, initial = '', finished = false, payload = null) {
  if (!id) return;
  streams[id] = streams[id] || { text: '', finished: false, payload: null, subs: new Set() };
  streams[id].text = initial || '';
  streams[id].finished = !!finished;
  streams[id].payload = payload || null;
  // notify existing subscribers
  notify(streams[id]);
}

function updateStream(id, text, finished = false, payload = null) {
  if (!id || !streams[id]) return;
  streams[id].text = text || '';
  streams[id].finished = !!finished;
  streams[id].payload = payload || null;
  notify(streams[id]);
}

function subscribe(id, cb) {
  if (!id) return () => {};
  streams[id] = streams[id] || { text: '', finished: false, payload: null, subs: new Set() };
  streams[id].subs.add(cb);
  // send current snapshot immediately
  cb(streams[id].text, streams[id].finished, streams[id].payload);
  return () => {
    streams[id] && streams[id].subs.delete(cb);
    // 移除空流
    if (streams[id] && streams[id].subs.size === 0 && streams[id].finished) {
      delete streams[id];
    }
  };
}

function closeStream(id) {
  if (!id || !streams[id]) return;
  streams[id].subs.forEach((cb) => cb(streams[id].text, true, streams[id].payload));
  delete streams[id];
}

function getSnapshot(id) {
  if (!id || !streams[id]) return { text: '', finished: false, payload: null };
  return { text: streams[id].text, finished: streams[id].finished, payload: streams[id].payload };
}

export default {
  openStream,
  updateStream,
  subscribe,
  closeStream,
  getSnapshot,
};
