#!/usr/bin/env python3
"""First-pass survey of a mockup: palette, structure, and where everything sits.

The first ten minutes of every build are spent working out what is on the page and
where. This prints all of it at once, so the layout can be written from numbers
instead of from impressions of a thumbnail.

  python3 tools/survey.py --mock mock.jpg
  python3 tools/survey.py --mock mock.jpg --region 0,0,1536,500   # one area only

Output:
  * the size, and whether the ground is light or dark (which decides every
    threshold used later, including `measure.py --invert`)
  * dominant colours and their share, so panels and fills can be sampled exactly
  * horizontal ink bands, each with its x extent and height, top to bottom
  * for each band taller than --min-band, the same broken into columns, which
    separates a left text column from a right image or a row's cells
"""
import argparse
from collections import Counter

import numpy as np
from PIL import Image


def palette(arr, n=8):
    q = (arr // 16 * 16).reshape(-1, 3)
    c = Counter(map(tuple, q))
    total = sum(c.values())
    out = []
    for rgb, k in c.most_common(n):
        # report the true mean of the pixels in this bucket, not the bucket edge
        m = np.all((arr // 16 * 16) == np.array(rgb), axis=2)
        mean = arr[m].mean(axis=0).round().astype(int)
        out.append((tuple(int(v) for v in mean), 100 * k / total))
    return out


def runs(flags, min_gap=4):
    """[(start, end)] runs of True, merging gaps shorter than min_gap."""
    idx = np.where(flags)[0]
    if len(idx) == 0:
        return []
    out, start, prev = [], idx[0], idx[0]
    for i in idx[1:]:
        if i - prev > min_gap:
            out.append((int(start), int(prev)))
            start = i
        prev = i
    out.append((int(start), int(prev)))
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--mock", default="mock.jpg")
    ap.add_argument("--region", default=None, help="x0,y0,x1,y1 (default: whole image)")
    ap.add_argument("--min-band", type=int, default=14,
                    help="bands at least this tall get a column breakdown")
    ap.add_argument("--min-ink", type=float, default=0.004,
                    help="fraction of the row that must be ink for it to count")
    a = ap.parse_args()

    im = Image.open(a.mock).convert("RGB")
    W, H = im.size
    arr = np.asarray(im, dtype=np.float32)
    if a.region:
        x0, y0, x1, y1 = [int(v) for v in a.region.split(",")]
    else:
        x0, y0, x1, y1 = 0, 0, W - 1, H - 1
    sub = arr[y0:y1 + 1, x0:x1 + 1]
    lum = sub.mean(axis=2)
    print(f"{a.mock}  {W}x{H}  region {x0},{y0},{x1},{y1}")

    corners = np.concatenate([lum[:8, :8].ravel(), lum[:8, -8:].ravel(),
                              lum[-8:, :8].ravel(), lum[-8:, -8:].ravel()])
    light = corners.mean() > 127
    mid = (np.percentile(lum, 2) + np.percentile(lum, 98)) / 2
    print(f"ground: {'LIGHT -> ink is dark' if light else 'DARK -> ink is light'} "
          f"(corner mean {corners.mean():.0f}, midpoint {mid:.0f})")

    print("\npalette (top 8, true means):")
    for rgb, pct in palette(sub):
        print(f"  #{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}  rgb{rgb}  {pct:5.1f}%")

    ink = (lum < mid) if light else (lum > mid)
    cover = ink.mean(axis=1)
    bands = [(s, e) for s, e in runs(cover > a.min_ink, min_gap=3)]
    print(f"\n{len(bands)} ink bands (rows >{100 * a.min_ink:.1f}% ink):")
    for s, e in bands:
        row = ink[s:e + 1]
        cols = np.where(row.any(axis=0))[0]
        h = e - s + 1
        print(f"  y{y0 + s:4d}-{y0 + e:4d}  h{h:3d}  x{x0 + cols.min()}-{x0 + cols.max()}"
              f"  fill {100 * row.mean():4.1f}%")
        if h >= a.min_band:
            colcover = ink[s:e + 1].mean(axis=0)
            blocks = runs(colcover > 0.01, min_gap=max(6, (x1 - x0) // 90))
            if len(blocks) > 1:
                desc = ", ".join(f"{x0 + bs}-{x0 + be}" for bs, be in blocks[:10])
                print(f"        columns: {desc}")


if __name__ == "__main__":
    main()
