#!/usr/bin/env python3
"""Look at a wallpaper and decide the editorial layout:
   - which side is calm (widgets go there, the subject keeps the other side)
   - whether that side is bright (-> dark text)
   - a portrait crop of the subject for fastfetch / the profile widget
writes ~/.local/state/chroma/layout.json and subject.png"""
import json, os, sys
from PIL import Image, ImageFilter, ImageStat

src = sys.argv[1]
state = os.path.expanduser("~/.local/state/chroma")
img = Image.open(src).convert("RGB")
W, H = img.size

small = img.resize((192, 108)).convert("L")
edges = small.filter(ImageFilter.FIND_EDGES)
px = edges.load()
cols = [sum(px[x, y] for y in range(108)) for x in range(192)]

left, right = sum(cols[:64]), sum(cols[128:])
side = "left" if left <= right else "right"
# manual overrides: lines like "wallhaven-1qod3w.jpg = right" in ~/.config/chroma/layout-overrides,
# optionally followed by the subject's horizontal center as a fraction ("= right 0.68")
subject_x = None
try:
    for line in open(os.path.expanduser("~/.config/chroma/layout-overrides")):
        k, _, v = line.partition("=")
        v = v.split()
        if k.strip() == os.path.basename(src) and v and v[0] in ("left", "right"):
            side = v[0]
            if len(v) > 1:
                subject_x = float(v[1])
except FileNotFoundError:
    pass
calm = small.crop((0, 0, 80, 108) if side == "left" else (112, 0, 192, 108))
bright = ImageStat.Stat(calm).mean[0] > 140

# subject: edge-energy centroid on the busy side
busy = range(64, 192) if side == "left" else range(0, 128)
tot = sum(cols[x] for x in busy) or 1
cx = subject_x * W if subject_x is not None else sum(x * cols[x] for x in busy) / tot / 192 * W
ch = int(H * 0.86)
cw = int(ch * 0.92)
x0 = int(min(max(cx - cw / 2, 0), W - cw))
y0 = int(H * 0.02)
img.crop((x0, y0, x0 + cw, y0 + ch)).resize((560, int(560 * ch / cw))).save(f"{state}/subject.png")

json.dump({"side": side, "bright": bright, "image": src}, open(f"{state}/layout.json", "w"))
print(side, "bright" if bright else "dark")
