/**
 * WebSocket Composable
 */
import { ref, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'

export interface WebSocketMessage {
  type: string
  execution_id?: string
  status?: string
  progress?: number
  message?: string
  result?: any
  error?: string
  execution_time?: number
}

export function useWebSocket(executionId: string) {
  const status = ref<string>('pending')
  const progress = ref<number>(0)
  const result = ref<any>(null)
  const error = ref<string | null>(null)
  const executionTime = ref<number | null>(null)
  const connected = ref<boolean>(false)
  const ws = ref<WebSocket | null>(null)
  let heartbeatInterval: number | null = null

  // 获取WebSocket URL
  const getWebSocketUrl = () => {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
    const hostname = window.location.hostname
    const port = hostname === 'localhost' || hostname === '127.0.0.1' ? '8037' : '8037'
    return `${protocol}//${hostname}:${port}/api/v1/ws/executions/${executionId}`
  }

  // 连接WebSocket
  const connect = () => {
    if (ws.value && ws.value.readyState === WebSocket.OPEN) {
      return // 已经连接
    }

    const wsUrl = getWebSocketUrl()
    console.log('[WebSocket] 连接中:', wsUrl)

    try {
      ws.value = new WebSocket(wsUrl)

      ws.value.onopen = () => {
        console.log('[WebSocket] 连接已建立')
        connected.value = true
        
        // 启动心跳
        startHeartbeat()
      }

      ws.value.onmessage = (event) => {
        try {
          const message: WebSocketMessage = JSON.parse(event.data)
          handleMessage(message)
        } catch (e) {
          console.error('[WebSocket] 解析消息失败:', e)
        }
      }

      ws.value.onerror = (err) => {
        console.error('[WebSocket] 错误:', err)
        connected.value = false
        ElMessage.error('WebSocket连接错误')
      }

      ws.value.onclose = () => {
        console.log('[WebSocket] 连接已关闭')
        connected.value = false
        stopHeartbeat()
        
        // 如果执行还在进行中，尝试重连
        if (status.value === 'running' || status.value === 'pending') {
          setTimeout(() => {
            console.log('[WebSocket] 尝试重连...')
            connect()
          }, 3000)
        }
      }
    } catch (err) {
      console.error('[WebSocket] 连接失败:', err)
      ElMessage.error('WebSocket连接失败')
    }
  }

  // 处理消息
  const handleMessage = (message: WebSocketMessage) => {
    console.log('[WebSocket] 收到消息:', message)

    switch (message.type) {
      case 'status':
        if (message.status) {
          status.value = message.status
        }
        if (message.progress !== undefined) {
          progress.value = message.progress
        }
        if (message.result) {
          result.value = message.result
        }
        if (message.error) {
          error.value = message.error
        }
        if (message.execution_time !== undefined) {
          executionTime.value = message.execution_time
        }
        break

      case 'pong':
        // 心跳响应，无需处理
        break

      case 'error':
        error.value = message.message || '未知错误'
        ElMessage.error(message.message || '执行出错')
        break
    }
  }

  // 启动心跳
  const startHeartbeat = () => {
    heartbeatInterval = window.setInterval(() => {
      if (ws.value && ws.value.readyState === WebSocket.OPEN) {
        ws.value.send(JSON.stringify({ type: 'ping' }))
      }
    }, 30000) // 每30秒发送一次心跳
  }

  // 停止心跳
  const stopHeartbeat = () => {
    if (heartbeatInterval) {
      clearInterval(heartbeatInterval)
      heartbeatInterval = null
    }
  }

  // 断开连接
  const disconnect = () => {
    stopHeartbeat()
    if (ws.value) {
      ws.value.close()
      ws.value = null
    }
    connected.value = false
  }

  // 清理
  onUnmounted(() => {
    disconnect()
  })

  return {
    status,
    progress,
    result,
    error,
    executionTime,
    connected,
    connect,
    disconnect
  }
}
