#!/usr/bin/env python3
"""scan.py: measure the bars of a padded image. Usage: scan.py image.png [R G B]
Use a PNG: JPEG compression changes the bar pixels and the counts come out too low.
Prints: WxH top bottom left right (rows/columns that are entirely the bar colour; white unless R G B is given)."""
import os, subprocess, sys

def load(path):
    data = subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-i", path, "-f", "image2pipe", "-vcodec", "ppm", "-"], capture_output=True, check=True).stdout
    parts = data.split(b"\n", 3); w, h = map(int, parts[1].split()); return w, h, parts[3]

def scan(path, color=(255, 255, 255)):
    w, h, px = load(path); bar = bytes(color)
    row = lambda y: px[y*w*3:(y+1)*w*3]
    barrow = bar * w
    top = 0
    while top < h and row(top) == barrow: top += 1
    if top == h: return w, h, h, 0, 0, 0   # all bar
    bot = 0
    while row(h-1-bot) == barrow: bot += 1
    def colbar(x): return all(px[(y*w+x)*3:(y*w+x)*3+3] == bar for y in range(top, h-bot))
    left = 0
    while left < w and colbar(left): left += 1
    right = 0
    while colbar(w-1-right): right += 1
    return w, h, top, bot, left, right

def main(argv):
    if len(argv) < 2:
        print("usage: scan.py image.png [R G B]", file=sys.stderr); return 2
    path = argv[1].replace("\r", "")
    if not os.path.isfile(path):
        print("image not found: " + path, file=sys.stderr); return 2
    if os.path.getsize(path) == 0:
        print("image is empty: " + path, file=sys.stderr); return 2
    try:
        col = tuple(int(v.replace("\r", "")) for v in argv[2:5]) if len(argv) >= 5 else (255, 255, 255)
    except ValueError:
        print("R G B must be whole numbers 0 to 255", file=sys.stderr); return 2
    if any(not 0 <= c <= 255 for c in col):
        print("R G B must be whole numbers 0 to 255", file=sys.stderr); return 2
    try:
        print(*scan(path, col))
    except (subprocess.CalledProcessError, ValueError, IndexError):
        print("could not read an image from: " + path, file=sys.stderr); return 2
    return 0

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