"""Header, integer, and color parsing helpers."""from__future__importannotationsfromcollections.abcimportMapping,SequenceimportrefromtypingimportAnyfrom.textimportnormalize_for_matching__all__=["choose_preferred_column","value_to_int","color_from_row"]_RGB_COLUMN_ALIASES=(("R","RED"),("G","GREEN"),("B","BLUE"))
[docs]defchoose_preferred_column(header:Sequence[str],preferred_candidates:Sequence[str])->str|None:"""Return the first preferred candidate present in a header list."""header_lookup={column.upper():columnforcolumninheader}forcandidateinpreferred_candidates:ifcandidate.upper()inheader_lookup:returnheader_lookup[candidate.upper()]returnNone
[docs]defvalue_to_int(value:Any)->int|None:"""Convert text-like numeric values into ints, returning None when unavailable."""text=normalize_for_matching(NoneifvalueisNoneelsestr(value))ifnottext:returnNonetry:returnint(float(text))except(ValueError,OverflowError):returnNone
[docs]defcolor_from_row(row:Mapping[str,Any])->str:"""Parse '#RRGGBB' or RGB triplets from a row and return uppercase hex."""hex_value=normalize_for_matching(Noneifrow.get("HEX")isNoneelsestr(row.get("HEX")))ifhex_value:color=hex_value.lstrip("#").upper()ifre.fullmatch(r"[0-9A-F]{6}",color):returnf"#{color}"channels:list[int]=[]foraliasesin_RGB_COLUMN_ALIASES:raw_value=next((row.get(alias)foraliasinaliasesifrow.get(alias)isnotNone),None)ifraw_valueisNone:raiseValueError("Could not determine color from source CSV row.")try:channel=int(float(str(raw_value)))except(ValueError,OverflowError)asexc:raiseValueError(f"Invalid RGB color value: {raw_value!r}")fromexcchannels.append(channel)ifnotall(0<=component<=255forcomponentinchannels):raiseValueError(f"RGB color out of range: {tuple(channels)}")r,g,b=channelsreturnf"#{r:02X}{g:02X}{b:02X}"