#!/usr/bin/env python3
"""Checks a podcast cover image against the rules quoted on the Koldflux guide (Apple Show Cover page, Spotify file-format page).
Usage: python3 check-cover.py cover.png   (needs Pillow: pip install pillow)
Exit code: 0 = no FAIL, 1 = at least one FAIL, 2 = file missing or not an image."""
import os, sys
from PIL import Image

if len(sys.argv) != 2:
    print("usage: check-cover.py <image>"); sys.exit(2)
path = sys.argv[1]
if not os.path.isfile(path):
    print("no such file: " + path); sys.exit(2)
try:
    im = Image.open(path); im.load()
except Exception as e:
    print("not an image Pillow can read: " + str(e)); sys.exit(2)

w, h = im.size
fmt = im.format
mode = im.mode
ext = os.path.splitext(path)[1].lower().lstrip(".")
size = os.path.getsize(path)
print(f"file: {path} | {w} x {h} | content type {fmt} | mode {mode} | {size:,} bytes")

rows = []
rows.append(("PASS" if w == h else "FAIL", "square (Apple and Spotify)", f"{w} x {h}"))
rows.append(("PASS" if 1400 <= min(w, h) and max(w, h) <= 3000 else "FAIL", "1400 to 3000 px (Apple, RSS feed)", f"{w} x {h}"))
rows.append(("PASS" if fmt in ("PNG", "JPEG") else "FAIL", "PNG or JPEG (Apple, Spotify)", str(fmt)))
if (w, h) != (3000, 3000) and w == h and 1400 <= w <= 3000:
    rows.append(("INFO", "Apple's stated Show Cover size is 3000 x 3000; the RSS range is 1400 to 3000", f"{w} x {h}"))
ok_ext = {"PNG": ("png",), "JPEG": ("jpg", "jpeg")}.get(fmt, ())
if fmt in ("PNG", "JPEG") and ext not in ok_ext:
    rows.append(("WARN", "file name matches content", f"name says .{ext}, content is {fmt}"))
has_alpha = mode in ("RGBA", "LA", "PA") or "transparency" in im.info
rows.append(("FAIL" if has_alpha else "PASS", "no alpha channel (Apple)", f"mode {mode}"))
if mode not in ("RGB", "L", "RGBA", "P"):
    rows.append(("WARN", "color mode (not stated in the official pages read)", f"mode {mode}; export as RGB to be safe"))
for status, rule, got in rows:
    print(f"{status:4} | {rule} | {got}")
sys.exit(1 if any(r[0] == "FAIL" for r in rows) else 0)
