"""Where the light is: the centroid of the brightest 3% of the sky (S21's sky region), against the ruin's x-centre."""
import json, sys, numpy as np
sys.path.insert(0, '../..')
from studywall import measure
SPEC = json.load(open('handoff/SEL2-easel/proposition.json'))['chosen']['spec']

def light(png):
    L = measure._lum(png); H, W = L.shape
    g = measure.region_masks(SPEC, W, H)
    sky, ruin = g['sky'], g['ruin']
    ys, xs = np.mgrid[0:H, 0:W]
    v = L[sky]; thr = np.quantile(v, 0.97)
    m = sky & (L >= thr)
    cx, cy = xs[m].mean() / W, ys[m].mean() / H
    rx = xs[ruin].mean() / W
    m2 = measure.measure(png, SPEC)
    d = abs(cx - rx)
    return {"light_x": round(cx, 3), "light_y": round(cy, 3), "ruin_x": round(rx, 3), "dx": round(d, 3),
            "peak": round(float(thr), 3), "glow": bool(m2['relations']['glow_at_horizon']),
            "sun_at_ruin": bool(d <= 0.15)}

if __name__ == '__main__':
    for p in sys.argv[1:]:
        print(p.split('/')[1], light(p))
