/** 从反射 KV / 投影数值解析电量，统一成 0–1 比例（未知返回 null）。 */

const SOC_KEY_RE = /(^|_)(Soc|SOC|batterySoc|BatterySoc|电量)$/i

export function parseSocNumber(raw: unknown): number | null {
  if (raw == null || raw === '') return null
  if (typeof raw === 'number') {
    if (!Number.isFinite(raw)) return null
    return normalizeSocRatio(raw)
  }
  const s = String(raw).trim().replace(/%$/, '')
  const n = Number(s)
  if (!Number.isFinite(n)) return null
  return normalizeSocRatio(n)
}

/** 接受 0–1 或 0–100，输出 0–1。 */
export function normalizeSocRatio(n: number): number {
  const ratio = n > 1 ? n / 100 : n
  return Math.max(0, Math.min(1, ratio))
}

export function socToPercent(ratio: number): number {
  return Math.max(0, Math.min(100, Math.round(ratio <= 1 ? ratio * 100 : ratio)))
}

export function extractSocFromKv(
  rows: Array<{ key?: string | null; value?: string | null }> | null | undefined
): number | null {
  if (!rows?.length) return null
  const preferred = ['车体_Soc', 'Soc', 'batterySoc', 'BatterySoc', '电量']
  for (const key of preferred) {
    const hit = rows.find((r) => r.key === key)
    const parsed = parseSocNumber(hit?.value)
    if (parsed != null) return parsed
  }
  for (const r of rows) {
    if (!r.key || !SOC_KEY_RE.test(r.key)) continue
    const parsed = parseSocNumber(r.value)
    if (parsed != null) return parsed
  }
  return null
}

export function extractSocFromFieldMap(map: Record<string, string> | null | undefined): number | null {
  if (!map) return null
  const preferred = ['车体_Soc', 'Soc', 'batterySoc', 'BatterySoc', '电量', 'battery']
  for (const key of preferred) {
    const parsed = parseSocNumber(map[key])
    if (parsed != null) return parsed
  }
  for (const [key, value] of Object.entries(map)) {
    if (!SOC_KEY_RE.test(key)) continue
    const parsed = parseSocNumber(value)
    if (parsed != null) return parsed
  }
  return null
}
