import type { TempStat } from '$lib/api/admin';

/** Pick the sensor that best represents the CPU die/package temperature
 *  from a heterogeneous component list. Intel exposes
 *  `coretemp Package id 0`; AMD exposes `k10temp Tctl`/`Tdie`. When neither
 *  is present we fall back to the hottest individual core, then to any
 *  CPU-ish sensor, and finally `null` (nothing CPU-related — e.g. only NVMe
 *  / chipset sensors are exposed). Used to keep the System tab focused on
 *  the one reading operators care about, with the rest tucked away. */
export function pickCpuTemp(temps: TempStat[]): TempStat | null {
    const byLabel = (re: RegExp) => temps.find((t) => re.test(t.label)) ?? null;
    return (
        byLabel(/package/i) ??
        byLabel(/tctl|tdie|k10temp/i) ??
        hottestCore(temps) ??
        byLabel(/cpu|coretemp/i) ??
        null
    );
}

function hottestCore(temps: TempStat[]): TempStat | null {
    const cores = temps.filter((t) => /core\s*\d+/i.test(t.label));
    if (cores.length === 0) return null;
    return cores.reduce((a, b) => (b.celsius > a.celsius ? b : a));
}
