/**
 * 解析智能体 SSE（data: {...}）行
 */

export function createSseLineBuffer() {
	let pending = ''

	return {
		push(chunkText) {
			if (!chunkText) return []
			pending += chunkText
			const lines = []
			let pos = 0
			while (true) {
				const end = pending.indexOf('\n', pos)
				if (end === -1) break
				lines.push(pending.slice(pos, end))
				pos = end + 1
			}
			pending = pending.slice(pos)
			return lines
		},
		flushLine() {
			if (!pending) return null
			const line = pending
			pending = ''
			return line
		}
	}
}

export function parseConsoleChatSseLine(line) {
	const trimmed = (line || '').trim()
	if (!trimmed || trimmed.startsWith(':')) return null
	if (!trimmed.startsWith('data:')) return null

	const payload = trimmed.slice(5).trim()
	if (!payload || payload === '[DONE]') {
		return { done: true }
	}

	try {
		return { data: JSON.parse(payload) }
	} catch (e) {
		return null
	}
}

/**
 * 从 SSE JSON 中提取 assistant 文本片段（可能是增量，也可能是累计全文）
 */
export function extractAssistantDelta(data) {
	if (!data || typeof data !== 'object') return ''

	if (data.error) {
		const err = data.error
		const msg = (typeof err === 'string' ? err : (err.message || err.msg)) || 'AI 服务异常'
		throw new Error(msg)
	}

	const parts = []
	const output = data.output
	if (Array.isArray(output)) {
		for (const item of output) {
			if (!item || item.role !== 'assistant' || !Array.isArray(item.content)) continue
			for (const block of item.content) {
				if (block && block.type === 'text' && block.text) {
					parts.push(block.text)
				}
			}
		}
	}

	if (!parts.length && typeof data.text === 'string') parts.push(data.text)
	if (!parts.length && typeof data.delta === 'string') parts.push(data.delta)

	return parts.join('')
}

/**
 * 合并流式 assistant 文本，兼容：
 * - 增量 token（直接拼接）
 * - 累计全文快照（startsWith 则替换）
 * - 结束包重复推送整段答案（去重）
 */
export function mergeAssistantStreamText(current, incoming) {
	const cur = current || ''
	const next = incoming || ''
	if (!next) return cur
	if (!cur) return next
	if (next === cur) return cur
	// 上游发「到目前为止的全文」或最终完整包
	if (next.startsWith(cur)) return next
	// 迟到的旧快照
	if (cur.startsWith(next)) return cur
	// 整段答案被再次推送
	if (next.length >= 8 && cur.endsWith(next)) return cur
	if (cur.length >= 8 && next.indexOf(cur) === 0) return next
	return cur + next
}
