import { ApiError, api, getCsrf, triggerUnauthorized } from './api'
import type { AITerminalSuggestion } from './types'

/**
 * POST a JSON body and consume the server's SSE response. EventSource cannot
 * carry the CSRF header, so the panel uses fetch + ReadableStream instead.
 */
export async function streamChat(
  path: string,
  body: unknown,
  onEvent: (event: string, data: any) => void,
  signal?: AbortSignal,
): Promise<void> {
  let res: Response
  try {
    res = await fetch(path, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-Token': getCsrf(),
      },
      credentials: 'same-origin',
      body: JSON.stringify(body ?? {}),
      signal,
    })
  } catch (e) {
    if ((e as Error).name === 'AbortError') return
    throw new ApiError('无法连接面板，请检查网络或服务状态', 0)
  }

  if (res.status === 401) {
    triggerUnauthorized()
    throw new ApiError('登录已过期，请重新登录', 401)
  }

  const ctype = res.headers.get('Content-Type') ?? ''
  if (!res.ok || !ctype.includes('text/event-stream')) {
    let message = `请求失败 (HTTP ${res.status})`
    try {
      const env = await res.json()
      if (env?.msg) message = env.msg
    } catch {
      /* non JSON error */
    }
    throw new ApiError(message, res.status)
  }

  const reader = res.body?.getReader()
  if (!reader) throw new ApiError('当前浏览器不支持流式响应', 0)
  const decoder = new TextDecoder()
  let buffer = ''
  try {
    for (;;) {
      const { done, value } = await reader.read()
      if (done) break
      buffer += decoder.decode(value, { stream: true })
      buffer = buffer.replace(/\r\n/g, '\n')
      let cut = buffer.indexOf('\n\n')
      while (cut >= 0) {
        dispatch(buffer.slice(0, cut), onEvent)
        buffer = buffer.slice(cut + 2)
        cut = buffer.indexOf('\n\n')
      }
    }
    if (buffer.trim()) dispatch(buffer, onEvent)
  } catch (e) {
    if ((e as Error).name === 'AbortError') return
    throw e
  } finally {
    reader.releaseLock()
  }
}

function dispatch(chunk: string, onEvent: (event: string, data: any) => void) {
  let event = 'message'
  const dataLines: string[] = []
  for (const line of chunk.split('\n')) {
    if (line.startsWith('event:')) event = line.slice(6).trim()
    else if (line.startsWith('data:')) dataLines.push(line.slice(5).replace(/^\s/, ''))
  }
  if (dataLines.length === 0) return
  const raw = dataLines.join('\n')
  let data: any = raw
  try {
    data = JSON.parse(raw)
  } catch {
    /* keep raw text */
  }
  onEvent(event, data)
}

/** Ask the terminal assistant for a command suggestion. */
export function assistTerminal(line: string, mode: string, context: string): Promise<AITerminalSuggestion> {
  return api.post<AITerminalSuggestion>('api/v1/ai/terminal/assist', { line, mode, context })
}

/** Ask the assistant to explain the output and optionally propose one next step. */
export function interpretTerminal(
  question: string,
  command: string,
  output: string,
): Promise<AITerminalSuggestion> {
  return api.post<AITerminalSuggestion>('api/v1/ai/terminal/interpret', { question, command, output })
}
