import type { Car, CarState } from '@/types/car'
import { extractSocFromKv, normalizeSocRatio, parseSocNumber } from '@/utils/batterySoc'

type Kv = { key?: string | null; value?: string | null }

function kv(rows: Kv[] | null | undefined, ...keys: string[]): string {
  if (!rows?.length) return ''
  for (const key of keys) {
    const hit = rows.find((r) => r.key === key)
    if (hit?.value != null && hit.value !== '') return String(hit.value)
  }
  return ''
}

/**
 * SimpleLite /projection/cars 会把「正常但未初始化」「导航失联」等一律标成 fault，
 * 与地图标签/车体 AlarmLevel 不一致。这里用 lstatus + 车体 status 重新推导。
 */
export function deriveCarState(car: Pick<Car, 'state' | 'lstatus'>, statusRows?: Kv[] | null): CarState {
  const lstatus = (car.lstatus ?? '').trim()
  const alarmLevelRaw = kv(statusRows, '车体_AlarmLevel', 'AlarmLevel')
  const alarmInfo = kv(statusRows, '车体_AlarmInfo', 'AlarmInfo').trim()
  const riskAlarm = kv(statusRows, '车体_RiskPositionAlarm', 'RiskPositionAlarm')
  const drive = kv(statusRows, '车体_driveStatus', 'driveStatus')
  const openCharge = kv(statusRows, '车体_OpenChargeByClumsy', 'OpenChargeByClumsy')

  const alarmLevel = Number(alarmLevelRaw)
  const hasAlarm =
    (Number.isFinite(alarmLevel) && alarmLevel > 0) ||
    (/true/i.test(riskAlarm)) ||
    (alarmInfo.length > 0 && !/^\/$|^-$|^none$/i.test(alarmInfo))

  // 明确健康：以「正常」开头（含「正常但未初始化」）→ 绝不是故障
  if (/^正常/.test(lstatus)) {
    if (/充电/.test(lstatus)) return 'charging'
    if (/暂停|挂起/.test(lstatus)) return 'paused'
    if (/离线/.test(lstatus)) return 'offline'
    if (hasAlarm) return 'fault'
    if (/charg|充电/i.test(openCharge) && /true/i.test(openCharge)) return 'charging'
    if (/Drive(Run|Move|Busy)|Running|运行/i.test(drive)) return 'running'
    if (/DriveStop|Idle|空闲|停止/i.test(drive)) return 'idle'
    // 未初始化但仍「正常」：视为空闲，而不是故障
    return 'idle'
  }

  if (/离线|失联/.test(lstatus)) return 'offline'
  if (/充电/.test(lstatus)) return 'charging'
  if (/暂停|挂起/.test(lstatus)) return 'paused'
  if (hasAlarm || (/故障|异常|检修/.test(lstatus) && !/正常/.test(lstatus))) return 'fault'
  if (/运行|工作|执行|忙/.test(lstatus)) return 'running'
  if (/空闲|待机/.test(lstatus)) return 'idle'

  // 有车体 status 时，别盲信投影里的 fault
  if (statusRows?.length) {
    if (hasAlarm) return 'fault'
    if (/Drive(Run|Move|Busy)|Running/i.test(drive)) return 'running'
    if (/DriveStop|Idle/i.test(drive)) return 'idle'
  }

  // 投影已给非 fault 时保留；fault 且无佐证则降为 idle，避免「全员故障」误报
  if (car.state && car.state !== 'fault') return car.state
  return 'idle'
}

export function applyRuntimeEnrichment(car: Car, statusRows?: Kv[] | null): Car {
  const socFromStatus = extractSocFromKv(statusRows)
  let batterySoc: number
  if (socFromStatus != null) {
    batterySoc = normalizeSocRatio(socFromStatus)
  } else if (statusRows != null) {
    // 已拉到 status 但无 Soc（如纯模拟车）→ 清掉投影写死的 0.8，避免假电量
    batterySoc = 0
  } else {
    batterySoc = parseSocNumber(car.batterySoc) ?? 0
  }

  return {
    ...car,
    batterySoc,
    state: deriveCarState(car, statusRows)
  }
}
