export type InterfaceType = "ether" | "gre" | "wg" | "other"

export function mapRosInterfaceType(raw: string | undefined | null): InterfaceType {
  const t = String(raw ?? "").trim().toLowerCase()
  if (t === "ether" || t === "ethernet") return "ether"
  if (t === "gre") return "gre"
  if (t === "wg" || t === "wireguard") return "wg"
  return "other"
}

export interface ParsedRosIface {
  name: string
  type: InterfaceType
  running: boolean
  disabled: boolean
}

function asBool(raw: unknown): boolean {
  if (typeof raw === "boolean") return raw
  const s = String(raw ?? "").trim().toLowerCase()
  return s === "true" || s === "yes" || s === "1"
}

export function parseRawInterfaces(json: string | null | undefined): ParsedRosIface[] {
  if (!json) return []
  try {
    const parsed = JSON.parse(json) as unknown
    const arr = Array.isArray(parsed) ? parsed : []
    const out: ParsedRosIface[] = []
    for (const item of arr) {
      if (!item || typeof item !== "object") continue
      const rec = item as Record<string, unknown>
      const name = String(rec.name ?? "").trim()
      if (!name) continue
      out.push({
        name,
        type: mapRosInterfaceType(String(rec.type ?? "")),
        running: asBool(rec.running),
        disabled: asBool(rec.disabled),
      })
    }
    return out
  } catch {
    return []
  }
}

export function isUniqueConstraintError(err: unknown): boolean {
  if (!err || typeof err !== "object") return false
  const rec = err as { code?: unknown; message?: unknown }
  const code = String(rec.code ?? "")
  const msg = String(rec.message ?? "")
  return code.includes("SQLITE_CONSTRAINT") || /unique constraint/i.test(msg)
}
