"""Surch colour theme: purple/orange -> ink + pastels + sky blue.
Rules (by hue, lightness, saturation):
  purple family (hue 245-320)
    low saturation (<.30)            -> neutral grey, same lightness
    light (l >= .75) or bright (l >= .5) -> kept (lavender pastel / violet accents)
    mid and dark                     -> ink (#141414 for the old brand purple)
  orange family (hue 15-45, s >= .30)
    light (l >= .85)                 -> kept (peach pastel)
    otherwise                        -> sky blue (hue 207), same lightness
Usage: python3 retheme_colors.py FILE...   (rewrites in place, prints a summary)"""
import re,sys,colorsys
HEX=re.compile(r'(#|%23)([0-9a-fA-F]{6}|[0-9a-fA-F]{3})(?![0-9a-zA-Z_-])')
RGB=re.compile(r'rgb(a?)\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})')
def conv(r,g,b):
    h,l,s=colorsys.rgb_to_hls(r/255,g/255,b/255);hd=h*360
    if s>=.12 and 245<=hd<=320:
        if s<.30:return colorsys.hls_to_rgb(230/360,l,min(s,.05))
        if l>=.5:return None
        return colorsys.hls_to_rgb(0,l*.24,0)
    if s>=.30 and 15<=hd<=45:
        if l>=.85:return None
        return colorsys.hls_to_rgb(207/360,l,min(s,.86))
    return None
def to255(t):return tuple(max(0,min(255,round(v*255))) for v in t)
def run(text,log):
    def hx(m):
        p,c=m.group(1),m.group(2)
        full=''.join(x*2 for x in c) if len(c)==3 else c
        r,g,b=(int(full[i:i+2],16) for i in (0,2,4))
        n=conv(r,g,b)
        if n is None:return m.group(0)
        out=p+'%02x%02x%02x'%to255(n);log.append((m.group(0),out));return out
    def rg(m):
        a,r,g,b=m.group(1),*map(int,m.group(2,3,4));n=conv(r,g,b)
        if n is None:return m.group(0)
        R,G,B=to255(n);out=f'rgb{a}({R},{G},{B}';log.append((m.group(0),out));return out
    # leave base64 payloads alone
    parts=re.split(r'(data:[a-z/+.-]+;base64,[A-Za-z0-9+/=]+)',text)
    return ''.join(p if i%2 else RGB.sub(rg,HEX.sub(hx,p)) for i,p in enumerate(parts))
if __name__=="__main__":
    tot=0
    for f in sys.argv[1:]:
        s=open(f,encoding='utf8').read();log=[];o=run(s,log)
        if o!=s:open(f,'w',encoding='utf8').write(o)
        tot+=len(log)
        short=[a for a,b in log if len(a.lstrip('#%23'))==3 and not a.startswith('rgb')]
        print(f'{f}: {len(log)} colours'+(f'  3-digit: {sorted(set(short))}' if short else ''))
    print('total',tot)
