"""Convert logo_sekolah.png ke logo_sekolah.ico multi-size untuk PyInstaller."""
import os
import numpy as np
from PIL import Image, ImageEnhance, ImageFilter


def _trim_content(image, tolerance=18):
    """Crop area kosong/warna latar agar simbol utama lebih dominan saat jadi ikon kecil."""
    rgba = image.convert("RGBA")
    arr = np.array(rgba)

    alpha = arr[:, :, 3]
    rgb = arr[:, :, :3].astype(np.int16)

    corners = np.array([
        rgb[0, 0],
        rgb[0, -1],
        rgb[-1, 0],
        rgb[-1, -1],
    ], dtype=np.int16)
    bg = np.median(corners, axis=0)

    dist = np.max(np.abs(rgb - bg), axis=2)
    mask = (alpha > 10) & (dist > tolerance)

    if not np.any(mask):
        mask = alpha > 10
    if not np.any(mask):
        return rgba

    ys, xs = np.where(mask)
    left, right = int(xs.min()), int(xs.max()) + 1
    top, bottom = int(ys.min()), int(ys.max()) + 1
    return rgba.crop((left, top, right, bottom))


def _prepare_square_icon(image):
    """Trim margin lalu pasang ke canvas persegi tanpa mengubah warna/detail logo asli."""
    image = _trim_content(image)
    image = image.convert("RGBA")

    # Penajaman ringan agar tetap asli namun lebih jelas di ukuran kecil.
    alpha = image.split()[-1]
    rgb = image.convert("RGB")
    rgb = rgb.filter(ImageFilter.UnsharpMask(radius=1.2, percent=115, threshold=2))
    rgb = ImageEnhance.Contrast(rgb).enhance(1.06)
    image = rgb.convert("RGBA")
    image.putalpha(alpha)

    canvas_size = 1024
    canvas = Image.new("RGBA", (canvas_size, canvas_size), (0, 0, 0, 0))

    max_dim = int(canvas_size * 0.985)
    image.thumbnail((max_dim, max_dim), Image.Resampling.LANCZOS)

    x = (canvas_size - image.width) // 2
    y = (canvas_size - image.height) // 2
    canvas.paste(image, (x, y), image)
    return canvas


def main():
    img_dir = "img"
    png_file = os.path.join(img_dir, "logo_sekolah.png")
    ico_file = os.path.join(img_dir, "logo_sekolah.ico")

    if not os.path.exists(png_file):
        print(f"[INFO] File tidak ditemukan: {png_file}. Konversi dilewati.")
        return 0

    try:
        img = Image.open(png_file)
        square_img = _prepare_square_icon(img)
        sizes = [
            (16, 16), (20, 20), (24, 24), (32, 32), (40, 40),
            (48, 48), (64, 64), (72, 72), (96, 96), (128, 128), (256, 256),
        ]
        square_img.save(ico_file, format="ICO", sizes=sizes)
        print(f"[OK] Berhasil convert: {png_file} -> {ico_file}")
        return 0
    except Exception as exc:
        print(f"[ERROR] Gagal convert logo: {exc}")
        return 1


if __name__ == "__main__":
    raise SystemExit(main())
