export interface FlowTupleRow {
  serverId: number
  src: string
  dst: string
  proto: number
  srcPort: number
  dstPort: number
  inIface: string
  bytes: number
  packets: number
}

export function flowTupleKey(r: Pick<FlowTupleRow, "serverId" | "src" | "dst" | "proto" | "srcPort" | "dstPort">): string {
  return `${r.serverId}|${r.src}|${r.dst}|${r.proto}|${r.srcPort}|${r.dstPort}`
}

function ifaceKey(r: FlowTupleRow): string {
  return `${flowTupleKey(r)}|${r.inIface}`
}

/**
 * Один 5-tuple на двух ifIndex — это один поток: сначала сумма по бакетам/iface,
 * затем max байт между интерфейсами (не sum).
 */
export function dedupFlowRowsMaxBytes<T extends FlowTupleRow>(rows: T[]): T[] {
  const byIface = new Map<string, T>()
  for (const row of rows) {
    const key = ifaceKey(row)
    const prev = byIface.get(key)
    if (!prev) {
      byIface.set(key, { ...row })
      continue
    }
    prev.bytes += row.bytes
    prev.packets += row.packets
  }
  const byTuple = new Map<string, T>()
  for (const row of byIface.values()) {
    const key = flowTupleKey(row)
    const prev = byTuple.get(key)
    if (!prev || row.bytes > prev.bytes) byTuple.set(key, row)
  }
  return [...byTuple.values()]
}
