from __future__ import annotations

from pathlib import Path
from PIL import Image
import sys


ROOT = Path(__file__).resolve().parents[1]
ASSETS = ROOT / "assets"
EXPECTED_SIZES = [16, 20, 24, 30, 32, 40, 48, 60, 64, 72, 80, 96, 128, 256]


def verify_icons() -> tuple[bool, list[str]]:
    messages: list[str] = []
    ok = True

    ico_path = ASSETS / "nexaoffice.ico"
    if not ico_path.exists():
        ok = False
        messages.append("missing assets/nexaoffice.ico")
    else:
        try:
            ico = Image.open(ico_path)
            sizes = set(ico.ico.sizes()) if getattr(ico, "ico", None) else set()
            missing = [s for s in EXPECTED_SIZES if (s, s) not in sizes]
            if missing:
                ok = False
                messages.append("ico missing sizes: " + ",".join(map(str, missing)))
            else:
                messages.append("ico sizes OK")
        except Exception as exc:
            ok = False
            messages.append(f"ico unreadable: {exc}")

    for size in EXPECTED_SIZES:
        p = ASSETS / f"nexaoffice_icon_{size}.png"
        if not p.exists():
            ok = False
            messages.append(f"missing {p.name}")
            continue
        try:
            img = Image.open(p).convert("RGBA")
            if img.size != (size, size):
                ok = False
                messages.append(f"{p.name} wrong size {img.size}")
            alpha = img.getchannel("A")
            hist = alpha.histogram()
            opaque = sum(hist[221:])
            coverage = opaque / float(size * size)
            if coverage < 0.24:
                ok = False
                messages.append(f"{p.name} too sparse for crisp Windows taskbar/titlebar coverage={coverage:.2f}")
            if size <= 32:
                # Small icon center should be visibly occupied, not only a thin edge.
                center = alpha.crop((size//4, size//4, size - size//4, size - size//4))
                if max(i for i, n in enumerate(center.histogram()) if n) < 180:
                    ok = False
                    messages.append(f"{p.name} weak center alpha for small icon")
        except Exception as exc:
            ok = False
            messages.append(f"{p.name} unreadable: {exc}")

    if ok:
        messages.append("all icon assets verified")
    return ok, messages


if __name__ == "__main__":
    ok, messages = verify_icons()
    for line in messages:
        print(line)
    sys.exit(0 if ok else 1)
