from core.constants import BANDS

HF_BANDS = [b for b in BANDS if b.is_ham_hf]


def _latest(d) -> float | None:
    """Given a map where the key is a timestamp and the value is a number represented as a string, find the latest
    timestamp and return the corresponding value as a float."""

    val = str(d[max(d.keys())]) if d else None
    return float(val) if (val is not None and val != "None") else None


def compute_band_states(fof2_dict, muf_dict, luf_dict):
    """Compute HF band states from the latest foF2, MUF and LUF values.

    Returns a map where the keys are HF bands and the values are as follows:
      "Closed" if band frequency is above MUF or below LUF (if known)
      "Short" if band frequency is >= LUF and < foF2 (good for NVIS)
      "Long" if band frequency is >= foF2 and < MUF (good for DX)
    """

    fof2 = _latest(fof2_dict)
    muf = _latest(muf_dict)
    luf = _latest(luf_dict) if luf_dict else None
    if fof2 is None or muf is None:
        return {}
    band_states = {}
    for band in HF_BANDS:
        freq = band.start_freq / 1_000_000
        if freq > muf or (luf is not None and freq < luf):
            band_states[band.name] = "Closed"
        elif freq < fof2:
            band_states[band.name] = "Short"
        else:
            band_states[band.name] = "Long"
    return band_states
