function textContent(content) {
  if (typeof content === 'string') return content
  if (!Array.isArray(content)) return ''
  return content.map(block => {
    if (typeof block === 'string') return block
    if (!block || typeof block !== 'object') return ''
    return block.text || block.thinking || block.summary || ''
  }).join('')
}

function qoderMeta(event) {
  return {
    providerEvent: String(event?.event || ''),
    ...(event?.id ? { providerEventId: String(event.id) } : {}),
    ...(event?.data?.turn_id ? { providerTurnId: String(event.data.turn_id) } : {}),
  }
}

export function parseJsonLine(line) {
  const value = String(line || '').trim()
  if (!value.startsWith('{')) return null
  try {
    const parsed = JSON.parse(value)
    return parsed && typeof parsed === 'object' ? parsed : null
  } catch {
    return null
  }
}

export function mapCodexJsonEvent(event) {
  if (!event || typeof event !== 'object') return []
  if (event.type === 'thread.started' && event.thread_id) {
    return [{ t: 'provider_session', provider: 'local-codex', providerSessionId: String(event.thread_id) }]
  }
  if (event.type === 'turn.started') return [{ t: 'status', v: 'Codex 已开始执行' }]
  if (event.type === 'turn.completed') return [{ t: 'status', v: 'Codex 已完成本轮执行' }]
  if (event.type === 'error' && event.message) return [{ t: 'error', v: String(event.message) }]

  const item = event.item
  if (!item || typeof item !== 'object') return []
  const providerItemId = item.id ? { providerItemId: String(item.id) } : {}

  if (event.type === 'item.completed' && item.type === 'agent_message') {
    const value = textContent(item.text ?? item.content)
    return value ? [{ t: 'delta', v: value }] : []
  }
  if ((event.type === 'item.completed' || event.type === 'item.started') && item.type === 'reasoning') {
    const value = textContent(item.text ?? item.summary ?? item.content)
    return value ? [{ t: 'reasoning_summary', v: value }] : []
  }
  if (item.type === 'command_execution' && event.type === 'item.started') {
    return [{
      t: 'tool_call',
      name: 'shell',
      args: { command: String(item.command || '') },
      ...providerItemId,
    }]
  }
  if (item.type === 'command_execution' && event.type === 'item.completed') {
    return [{
      t: 'tool_result',
      name: 'shell',
      result: String(item.aggregated_output ?? item.output ?? ''),
      ...providerItemId,
      ...(Number.isFinite(item.exit_code) ? { exitCode: item.exit_code } : {}),
    }]
  }
  if (item.type === 'error' && item.message) {
    return [{ t: 'warning', v: String(item.message), ...providerItemId }]
  }
  return []
}

export function normalizeArtifact(input, context = {}) {
  const name = String(input?.name || input?.path || input?.filename || '').replace(/^\/+/, '')
  return {
    name,
    path: String(input?.path || name).replace(/^\/+/, ''),
    size: Number.isFinite(Number(input?.size)) ? Number(input.size) : null,
    mime: String(input?.mime || input?.content_type || input?.contentType || ''),
    sessionId: String(context.sessionId || input?.sessionId || ''),
    provider: String(context.provider || input?.provider || ''),
    url: String(input?.url || input?.download_url || input?.downloadUrl || ''),
  }
}

export function mapQoderCloudEvent(event, context = {}) {
  if (!event || typeof event !== 'object') return []
  const type = String(event.event || event.type || '')
  const data = event.data && typeof event.data === 'object' ? event.data : {}
  const meta = qoderMeta({ ...event, event: type, data })
  if (!type) return []

  if (type === 'agent.message') {
    const value = textContent(data.content ?? data.text ?? data.message)
    return value ? [{ t: 'delta', v: value, ...meta }] : []
  }
  if (/thinking|reasoning|plan/i.test(type)) {
    const value = textContent(data.content ?? data.thinking ?? data.summary ?? data.text)
    return value ? [{ t: 'reasoning_summary', v: value, ...meta }] : []
  }
  if (/tool\.(?:started|start|use)|tool_use/i.test(type)) {
    return [{
      t: 'tool_call',
      name: String(data.tool_name || data.name || data.tool || 'tool'),
      args: data.input || data.args || data.arguments || {},
      ...meta,
    }]
  }
  if (/tool\.(?:completed|complete|result)|tool_result/i.test(type)) {
    return [{
      t: 'tool_result',
      name: String(data.tool_name || data.name || data.tool || 'tool'),
      result: typeof data.result === 'string' ? data.result : JSON.stringify(data.result ?? data.output ?? ''),
      ...meta,
    }]
  }
  if (/file|artifact/i.test(type)) {
    const source = data.file || data.artifact || data
    const artifact = normalizeArtifact(source, { ...context, provider: 'qoder-cloud-agent' })
    return artifact.name ? [{ t: 'artifact', artifact, ...meta }] : []
  }
  if (type === 'session.error') {
    return [{ t: 'error', v: String(data?.error?.message || data?.error || data?.message || 'QODER Cloud Agent 会话失败'), ...meta }]
  }
  if (type === 'session.status_idle' || type === 'terminated') {
    return [{ t: 'provider_done', ...meta }]
  }
  if (type.startsWith('session.status_')) {
    const state = type.slice('session.status_'.length)
    const labels = {
      created: 'QODER Cloud Agent 会话已创建',
      queued: 'QODER Cloud Agent 已排队',
      running: 'QODER Cloud Agent 正在执行',
      working: 'QODER Cloud Agent 正在执行',
    }
    return [{ t: 'status', v: labels[state] || `QODER Cloud Agent 状态：${state}`, ...meta }]
  }
  return []
}
