export type SessionStatus = 'idle' | 'connecting' | 'connected' | 'error'

export interface TermSessionData {
  id: string
  serverId: number
  serverName: string
  cwd: string
  cmdHistory: string[]
  cmdIdx: number
  reconnectAttempt: number
  manualDisconnect: boolean
  status: SessionStatus
  showOverlay: boolean
  overlayMsg: string
  reconnectCountdown: string
  uptime: string
  pingMs: number | null
  connectionStartTime: number
  pendingPath: string
  initialCdSent: boolean
}

export interface TermSessionNative {
  ws: WebSocket | null
  term: import('@xterm/xterm').Terminal | null
  fitAddon: import('@xterm/addon-fit').FitAddon | null
  resizeObserver: ResizeObserver | null
  reconnectTimer: ReturnType<typeof setTimeout> | null
  initTimeout: ReturnType<typeof setTimeout> | null
  pingTimer: ReturnType<typeof setInterval> | null
  uptimeTimer: ReturnType<typeof setInterval> | null
}

/** SSH shell ready (TERMINAL_INIT received), not merely WebSocket open. */
export function isSessionReady(s: TermSessionData): boolean {
  return s.status === 'connected'
}

export interface TerminalServerItem {
  id: number
  name: string
  domain: string
  is_online: boolean
}

export function sanitizeRemotePath(raw: string): string {
  const p = (raw || '').trim()
  return p && /^[^\x00-\x1f\x7f"'`\\]+$/.test(p) ? p : ''
}

export function sessionStatusLabel(s: TermSessionData): string {
  switch (s.status) {
    case 'connecting':
      return '连接中'
    case 'connected':
      return '已连接'
    case 'error':
      return '连接失败'
    case 'idle':
      return '连接中'
    default:
      return '连接中'
  }
}

export function sessionStatusColor(s: TermSessionData): string {
  switch (s.status) {
    case 'connecting':
      return 'warning'
    case 'connected':
      return 'success'
    case 'error':
      return 'error'
    case 'idle':
      return 'warning'
    default:
      return 'warning'
  }
}
