"""Filter PDF-extracted images: drop blank strips and white placeholders."""
from __future__ import annotations

from pathlib import Path


def is_usable_diagram(path: Path) -> bool:
    try:
        from PIL import Image
    except ImportError:
        return path.name != "page.png"

    try:
        with Image.open(path) as im:
            w, h = im.size
            if "page.png" in path.name:
                return False
            if w * h < 120 * 120:
                return False
            if h < 180:
                return False
            if w / max(h, 1) > 4.5:
                return False
            if h > 900 and h / max(w, 1) > 1.1:
                return False

            rgb = im.convert("RGB")
            data = rgb.getdata()
            step = max(1, len(data) // 10000)
            sample = [data[i] for i in range(0, len(data), step)]
            if not sample:
                return False

            white = sum(1 for p in sample if p[0] > 242 and p[1] > 242 and p[2] > 242)
            if white / len(sample) > 0.78:
                return False

            brightness = [sum(p) / 3 for p in sample]
            mean_b = sum(brightness) / len(brightness)
            var = sum((b - mean_b) ** 2 for b in brightness) / len(brightness)
            if var < 200:
                return False

            return True
    except Exception:
        return False


def filter_image_paths(images: list[str], root: Path) -> list[str]:
    kept = []
    for rel in images:
        if "page.png" in rel:
            continue
        path = root / rel
        if path.exists() and is_usable_diagram(path):
            kept.append(rel)
    return kept
