VALID_FIRST_DIGITS = {"1", "2", "3", "5", "6", "7", "8", "9"}


def is_valid_nif(nif: str) -> bool:
    """Portuguese NIF mod-11 checksum.

    First digit must be in the known-entity-type set; sum of first 8 digits
    weighted 9..2 mod 11 determines the check digit.
    """
    if not (isinstance(nif, str) and nif.isdigit() and len(nif) == 9):
        return False
    if nif[0] not in VALID_FIRST_DIGITS:
        return False
    total = sum(int(d) * w for d, w in zip(nif[:8], range(9, 1, -1)))
    check = 11 - (total % 11)
    if check >= 10:
        check = 0
    return check == int(nif[8])
