#!/usr/bin/env python3
# colorpick - pick and convert colors (hex/rgb/hsl) and show a terminal swatch
# Usage: colorpick [COLOR] [--random] [--no-swatch]
#   COLOR is #rrggbb, rgb(r,g,b) or hsl(h,s%,l%). With no COLOR, picks a random one.
#   Prints hex, rgb, hsl, and a terminal color swatch (ANSI background block).
import argparse, colorsys, random, re, sys

def parse_color(s):
    s = s.strip()
    m = re.fullmatch(r"#?([0-9a-fA-F]{6})", s)
    if m:
        h = m.group(1)
        return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
    m = re.fullmatch(r"#?([0-9a-fA-F]{3})", s)
    if m:
        return tuple(int(c * 2, 16) for c in m.group(1))
    m = re.fullmatch(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)", s, re.I)
    if m:
        rgb = tuple(int(x) for x in m.groups())
        if all(0 <= x <= 255 for x in rgb):
            return rgb
    m = re.fullmatch(r"hsl\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)%\s*,\s*(\d+(?:\.\d+)?)%\s*\)", s, re.I)
    if m:
        h, sat, li = float(m.group(1)), float(m.group(2)) / 100, float(m.group(3)) / 100
        r, g, b = colorsys.hls_to_rgb((h % 360) / 360, li, sat)
        return tuple(round(x * 255) for x in (r, g, b))
    raise ValueError(f"cannot parse color {s!r} (try #ff8800, rgb(255,136,0), hsl(32,100%,50%))")

def to_hsl(r, g, b):
    h, li, sat = colorsys.rgb_to_hls(r / 255, g / 255, b / 255)
    return round(h * 360), round(sat * 100), round(li * 100)

def selftest():
    assert parse_color("#ff8800") == (255, 136, 0)
    assert parse_color("f80") == (255, 136, 0)
    assert parse_color("rgb(255,136,0)") == (255, 136, 0)
    assert parse_color("hsl(0,100%,50%)") == (255, 0, 0)
    assert to_hsl(255, 0, 0) == (0, 100, 50)
    assert to_hsl(255, 255, 255) == (0, 0, 100)
    print("colorpick selftest: ok (hex/3-digit/rgb/hsl parsing, hsl round-trip)")
    return 0

def main():
    p = argparse.ArgumentParser(prog="colorpick",
        description="Pick and convert colors (hex/rgb/hsl) and show a terminal swatch.")
    p.add_argument("color", nargs="?", help="color like #ff8800, rgb(255,136,0) or hsl(32,100,50)")
    p.add_argument("--random", action="store_true", help="pick a random color")
    p.add_argument("--no-swatch", action="store_true", help="do not print the swatch block")
    p.add_argument("--seed", type=int, help="seed for --random")
    p.add_argument("--selftest", action="store_true", help="run built-in checks and exit")
    a = p.parse_args()
    if a.selftest:
        return selftest()
    if a.color and a.random:
        print("colorpick: give a COLOR or --random, not both", file=sys.stderr); return 2
    if a.random or not a.color:
        rng = random.Random(a.seed) if a.seed is not None else random.SystemRandom()
        rgb = tuple(rng.randint(0, 255) for _ in range(3))
    else:
        try:
            rgb = parse_color(a.color)
        except ValueError as e:
            print(f"colorpick: {e}", file=sys.stderr); return 2
    r, g, b = rgb
    h, s, li = to_hsl(r, g, b)
    print(f"hex: #{r:02x}{g:02x}{b:02x}")
    print(f"rgb: rgb({r},{g},{b})")
    print(f"hsl: hsl({h},{s}%,{li}%)")
    if not a.no_swatch:
        print(f"swatch: \x1b[48;2;{r};{g};{b}m      \x1b[0m  #{r:02x}{g:02x}{b:02x}")
    return 0

if __name__ == "__main__":
    sys.exit(main())
