#!/usr/bin/env python3
"""
BlindColour
------------
Move the pointer. When it stops, a small label pops up with a plain colour
name — primary, secondary or tertiary, plus light or dark — for one
second, then disappears.

Names use the 12-colour artist's wheel:
  primary   : Red, Yellow, Blue
  secondary : Orange, Green, Violet
  tertiary  : Red-Orange, Yellow-Orange, Yellow-Green,
              Blue-Green, Blue-Violet, Red-Violet
plus Light / Dark modifiers, and White / Grey / Black for near-neutral colours.
Very dark oranges are called Brown.

Setup (once):
    pip install pynput mss

Run:
    python colour_picker.py

Quit: press Esc, or close the small "running" window.

The name is printed in this terminal as well, in case the popup was too quick.
Timings are STILL_MS and SHOW_MS below.

macOS: the first run needs two permissions for your Terminal / Python app
in System Settings > Privacy & Security:
  - Accessibility (to follow the pointer, and for Esc)
  - Screen Recording (to read the pixel colour)
Restart the script after granting them.
"""

import colorsys
import queue
import sys
import time

# How long the pointer must rest before the name appears, and how long it stays.
STILL_MS = 200
SHOW_MS = 1000
JITTER_PX = 3

# Each entry: (hue in degrees where this name starts, name, kind)
# Hue boundaries are tuned to how people see colour, not equal 30° slices
# (e.g. yellow is a narrow band, green and blue are wide).
WHEEL = [
    (0, "Red", "primary"),
    (15, "Red-Orange", "tertiary"),
    (30, "Orange", "secondary"),
    (42, "Yellow-Orange", "tertiary"),
    (52, "Yellow", "primary"),
    (66, "Yellow-Green", "tertiary"),
    (90, "Green", "secondary"),
    (150, "Blue-Green", "tertiary"),
    (185, "Blue", "primary"),
    (245, "Blue-Violet", "tertiary"),
    (270, "Violet", "secondary"),
    (290, "Red-Violet", "tertiary"),
    (340, "Red", "primary"),
]


def hue_name(hue_deg):
    name, kind = WHEEL[0][1], WHEEL[0][2]
    for start, n, k in WHEEL:
        if hue_deg >= start:
            name, kind = n, k
    return name, kind


def colour_name(r, g, b):
    """Return (name, kind) for an RGB colour (0-255 each)."""
    h, l, s = colorsys.rgb_to_hls(r / 255, g / 255, b / 255)
    hue = h * 360

    # Neutrals: very low saturation, or so dark/light the hue doesn't show
    if l < 0.10:
        return "Black", "neutral"
    if l > 0.94:
        return "White", "neutral"
    if s < 0.12 or (s < 0.25 and (l < 0.2 or l > 0.85)):
        if l < 0.30:
            return "Dark Grey", "neutral"
        if l > 0.75:
            return "Light Grey", "neutral"
        return "Grey", "neutral"

    name, kind = hue_name(hue)

    # Dark oranges/yellows read as brown to most people
    if name in ("Orange", "Red-Orange", "Yellow-Orange") and l < 0.35:
        return "Brown", "secondary (dark)"

    if l < 0.32:
        name = "Dark " + name
    elif l > 0.70:
        name = "Light " + name

    # Washed-out colours
    if s < 0.35:
        name = "Greyish " + name

    return name, kind


def subtitle(name, kind):
    """Short classification line: Primary · Light, and so on."""
    if kind == "neutral":
        if name == "White" or name.startswith("Light "):
            return "Neutral · Light"
        if name == "Black" or name.startswith("Dark "):
            return "Neutral · Dark"
        return "Neutral"
    if kind == "secondary (dark)":
        return "Secondary · Dark"
    labels = {"primary": "Primary", "secondary": "Secondary", "tertiary": "Tertiary"}
    label = labels.get(kind, kind.title())
    rest = name
    greyish = False
    if rest.startswith("Greyish "):
        greyish = True
        rest = rest[len("Greyish ") :]
    parts = [label]
    if rest.startswith("Light "):
        parts.append("Light")
    elif rest.startswith("Dark "):
        parts.append("Dark")
    if greyish:
        parts.append("Greyish")
    return " · ".join(parts)


def main():
    # Windows: use real pixel coordinates when display scaling is on.
    if sys.platform == "win32":
        try:
            import ctypes

            ctypes.windll.shcore.SetProcessDpiAwareness(2)
        except Exception:
            pass

    try:
        import tkinter as tk
    except ImportError:
        print("tkinter is missing. Install it (on Linux: the python3-tk package).", file=sys.stderr)
        sys.exit(1)

    try:
        import mss
        from pynput import keyboard, mouse
    except ImportError:
        print("Install the two dependencies, then run this again:", file=sys.stderr)
        print("    pip install pynput mss", file=sys.stderr)
        sys.exit(1)

    moves = queue.Queue()
    sct = mss.mss()
    state = {
        "x": None,
        "y": None,
        "moved_at": 0.0,
        "popped": False,
        "hide_job": None,
        "closed": False,
    }

    root = tk.Tk()
    root.title("BlindColour")
    root.configure(bg="#f3efe6")
    root.resizable(False, False)
    root.attributes("-topmost", True)

    tk.Label(
        root,
        text="BlindColour is running",
        bg="#f3efe6",
        fg="#1c1916",
        font=("Helvetica", 12, "bold"),
    ).pack(anchor="w", padx=12, pady=(10, 0))
    tk.Label(
        root,
        text="Rest the pointer. The name shows for one second.\nPress Esc to quit.",
        bg="#f3efe6",
        fg="#6f685f",
        font=("Helvetica", 10),
        justify="left",
    ).pack(anchor="w", padx=12, pady=(2, 10))

    popup = tk.Toplevel(root)
    popup.overrideredirect(True)
    popup.attributes("-topmost", True)
    popup.configure(bg="#fffdf8")
    try:
        popup.attributes("-type", "tooltip")
    except tk.TclError:
        pass

    shell = tk.Frame(popup, bg="#fffdf8", highlightbackground="#e0d8cc", highlightthickness=1)
    shell.pack()
    swatch = tk.Frame(shell, width=18, bg="#808080")
    swatch.pack(side="left", fill="y")
    swatch.pack_propagate(False)
    text = tk.Frame(shell, bg="#fffdf8")
    text.pack(side="left", padx=12, pady=8)
    name_var = tk.StringVar(value="")
    kind_var = tk.StringVar(value="")
    tk.Label(
        text,
        textvariable=name_var,
        bg="#fffdf8",
        fg="#1c1916",
        font=("Helvetica", 18, "bold"),
    ).pack(anchor="w")
    tk.Label(
        text,
        textvariable=kind_var,
        bg="#fffdf8",
        fg="#6f685f",
        font=("Helvetica", 11),
    ).pack(anchor="w")
    popup.withdraw()

    def read_pixel(x, y):
        shot = sct.grab({"left": int(x), "top": int(y), "width": 1, "height": 1})
        px = shot.pixel(0, 0)
        return px[0], px[1], px[2]

    def hide_popup():
        state["hide_job"] = None
        try:
            popup.withdraw()
        except tk.TclError:
            pass

    def show_popup(x, y):
        try:
            r, g, b = read_pixel(x, y)
        except Exception:
            return
        name, kind = colour_name(r, g, b)
        sub = subtitle(name, kind)
        hexcode = f"#{r:02X}{g:02X}{b:02X}"
        name_var.set(name)
        kind_var.set(sub)
        swatch.configure(bg=hexcode)
        popup.deiconify()
        popup.update_idletasks()
        w = popup.winfo_width()
        h = popup.winfo_height()
        sw = popup.winfo_screenwidth()
        sh = popup.winfo_screenheight()
        px = x + 28
        py = y + 28
        if px + w > sw - 8:
            px = x - w - 20
        if py + h > sh - 8:
            py = y - h - 20
        popup.geometry(f"+{max(0, int(px))}+{max(0, int(py))}")
        try:
            popup.attributes("-topmost", True)
            popup.lift()
        except tk.TclError:
            pass
        print(f"{name}  —  {sub}  {hexcode}")
        if state["hide_job"] is not None:
            root.after_cancel(state["hide_job"])
        state["hide_job"] = root.after(SHOW_MS, hide_popup)

    def poll():
        if state["closed"]:
            return
        latest = None
        try:
            while True:
                latest = moves.get_nowait()
        except queue.Empty:
            pass
        if latest is not None:
            x, y = latest
            prev_x, prev_y = state["x"], state["y"]
            moved = prev_x is None or abs(x - prev_x) >= JITTER_PX or abs(y - prev_y) >= JITTER_PX
            if moved:
                state["x"], state["y"] = x, y
                state["moved_at"] = time.monotonic()
                state["popped"] = False
                if state["hide_job"] is not None:
                    root.after_cancel(state["hide_job"])
                    state["hide_job"] = None
                hide_popup()
        if (
            state["x"] is not None
            and not state["popped"]
            and (time.monotonic() - state["moved_at"]) * 1000 >= STILL_MS
        ):
            state["popped"] = True
            show_popup(state["x"], state["y"])
        root.after(40, poll)

    def on_move(x, y):
        moves.put((int(x), int(y)))

    def on_key(key):
        if key == keyboard.Key.esc:
            root.after(0, shutdown)

    def shutdown():
        if state["closed"]:
            return
        state["closed"] = True
        try:
            listener.stop()
        except Exception:
            pass
        try:
            if key_listener is not None:
                key_listener.stop()
        except Exception:
            pass
        try:
            root.quit()
            root.destroy()
        except tk.TclError:
            pass

    listener = mouse.Listener(on_move=on_move)
    listener.daemon = True
    listener.start()

    key_listener = None
    try:
        key_listener = keyboard.Listener(on_press=on_key)
        key_listener.daemon = True
        key_listener.start()
    except Exception:
        print("Global Esc is unavailable. Focus the small window and press Esc to quit.")

    root.bind("<Escape>", lambda _event: shutdown())
    root.protocol("WM_DELETE_WINDOW", shutdown)

    root.update_idletasks()
    sw = root.winfo_screenwidth()
    sh = root.winfo_screenheight()
    root.geometry(f"+{max(0, sw - root.winfo_width() - 24)}+{max(0, sh - root.winfo_height() - 72)}")

    print("BlindColour is running.")
    print("Rest the pointer — the name appears for one second, then goes.")
    print("Esc quits. Each name is also printed here.")
    poll()
    root.mainloop()


if __name__ == "__main__":
    main()
