"""Pixel block scanner for inner page layout diagnostics.

Scans an inner page PNG to find contiguous content regions and measure
gaps between them. Use this when scores show high overload_rows or low
density — it reveals whether blocks are merging into giant walls of text.

Usage:
    python3 block-pixel-scan.py inner-01.png inner-02.png
"""
from PIL import Image
import numpy as np
import sys

for path in sys.argv[1:]:
    img = Image.open(path)
    arr = np.array(img)
    h, w = arr.shape[:2]

    print(f'=== {path} ({w}x{h}) ===')

    # Scan row by row to find text blocks and empty gaps
    # Uses 80px side margins to avoid brand-bar edge noise
    blocks = []
    in_block = False
    start = 0
    for y in range(h):
        row = arr[y, 80:w-80, :]
        non_white = np.sum(np.max(row.astype(int), axis=1) < 240)
        if non_white > 20 and not in_block:
            start = y
            in_block = True
        elif non_white <= 20 and in_block:
            blocks.append((start, y-1, y-1-start+1))
            in_block = False
    if in_block:
        blocks.append((start, h-1, h-1-start+1))

    for i, (t, b, hp) in enumerate(blocks):
        mid = t + hp//2
        row = arr[mid, 80:w-80, :]
        green = np.sum((row[:,0] < 80) & (row[:,1] > 60))
        orange = np.sum((row[:,0] > 180) & (row[:,1] > 60) & (row[:,1] < 180))
        dense = np.sum(np.max(row.astype(int), axis=1) < 200)
        label = 'HEADER' if hp < 100 else ('CONTENT' if hp < 500 else 'LARGE')
        print(f'  Block {i}: y={t}-{b} (h={hp}px) [{label}] green={green} orange={orange} dense={dense}')

    gaps = []
    for i in range(len(blocks)-1):
        gap = blocks[i+1][0] - blocks[i][1] - 1
        gaps.append(gap)
    if gaps:
        print(f'  Gaps: {gaps}')
        print(f'  Avg gap: {sum(gaps)/len(gaps):.0f}px, Min: {min(gaps)}px')

    # Overload rows (>65% non-white across content width)
    overload = 0
    for y in range(h):
        row = arr[y, 80:w-80, :]
        non_white = np.sum(np.max(row.astype(int), axis=1) < 240)
        if non_white / (w-160) > 0.65:
            overload += 1
    print(f'  Overload rows: {overload}')

    # Brand bar check (top ~72px should be dark green)
    top_bar = arr[0:72, :, :]
    dark_green = np.sum((top_bar[:,:,0] < 60) & (top_bar[:,:,1] > 30) & (top_bar[:,:,1] < 120))
    print(f'  Brand bar green px: {dark_green} (expected >5000)')

    # Footer check
    footer = arr[h-80:h, :, :]
    footer_text = np.sum(np.max(footer.astype(int), axis=2) < 200)
    print(f'  Footer text px: {footer_text} (expected >500)')

    # Orange anchor points
    orange_total = np.sum((arr[:,:,0] > 180) & (arr[:,:,1] > 60) & (arr[:,:,1] < 180) & (arr[:,:,2] < 100))
    print(f'  Orange px: {orange_total}')

    # Content density by vertical zone
    zones = [(0,200,'top_margin'), (200,400,'upper'), (400,800,'mid'), (800,1200,'lower'), (1200,1660,'bottom')]
    for t,b,label in zones:
        zone = arr[t:b, 80:w-80, :]
        content_px = np.sum(np.max(zone.astype(int), axis=2) < 240)
        zone_px = (b-t) * (w-160)
        density = content_px / zone_px * 100
        print(f'  Zone [{label}] y={t}-{b}: density={density:.1f}%')

    print()
