#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
image2ico.py
GUI로 선택한 이미지 → 16·32·48·64·128·192·256·512
 해상도별 PNG · ICO (개별)  +  통합 ICNS  생성
저장 구조 : <선택경로>/icon/app_icon_<size>.png|.ico  +  app_icon.icns
by DINKI'ssTyle
"""

import os
import sys
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image  # pip install --upgrade pillow

# === 출력 해상도 & 형식 설정 =========================================
SIZES      = [16, 32, 48, 64, 128, 192, 256, 512]  # 필요한 해상도
OUT_PNG    = True   # 해상도별 PNG
OUT_ICO    = True   # 해상도별 ICO
OUT_ICNS   = True   # 통합 ICNS 1개 (macOS)
# ====================================================================


def select_image() -> str | None:
    """원본 이미지를 선택한다."""
    filetypes = [
        ("이미지 파일", ("*.png", "*.jpg", "*.jpeg", "*.bmp", "*.tif", "*.tiff")),
        ("모든 파일", "*.*"),
    ]
    return filedialog.askopenfilename(title="아이콘에 쓸 이미지를 선택하세요",
                                      filetypes=filetypes)


def select_output_dir() -> str | None:
    """저장 위치(폴더)를 선택한다."""
    return filedialog.askdirectory(title="저장할 폴더를 선택하세요")


def generate_icons(src_path: str, out_dir: str) -> None:
    """PNG · ICO · ICNS 파일들을 생성한다."""
    img = Image.open(src_path).convert("RGBA")  # 알파 채널 보존
    icon_dir = os.path.join(out_dir, "icon")
    os.makedirs(icon_dir, exist_ok=True)

    # 1) PNG
    if OUT_PNG:
        for size in SIZES:
            img.resize((size, size), Image.LANCZOS).save(
                os.path.join(icon_dir, f"app_icon_{size}.png"),
                format="PNG",
            )

    # 2) ICO
    if OUT_ICO:
        for size in SIZES:
            img.resize((size, size), Image.LANCZOS).save(
                os.path.join(icon_dir, f"app_icon_{size}.ico"),
                format="ICO",
            )

    # 3) ICNS (한 파일에 다중 해상도)
    if OUT_ICNS:
        icns_path = os.path.join(icon_dir, "app_icon.icns")
        # Pillow 9.5+ 는 sizes 인자를 지원
        img.save(icns_path, format="ICNS",
                 sizes=[(s, s) for s in SIZES])

    messagebox.showinfo(
        "완료",
        f"PNG · ICO · ICNS 아이콘이 '{icon_dir}' 폴더에 저장되었습니다.",
    )


def main() -> None:
    root = tk.Tk()
    root.withdraw()  # 메인 윈도우 숨김

    src = select_image()
    if not src:
        messagebox.showwarning("취소됨", "이미지를 선택하지 않았습니다.")
        sys.exit()

    out_dir = select_output_dir()
    if not out_dir:
        messagebox.showwarning("취소됨", "저장 위치를 선택하지 않았습니다.")
        sys.exit()

    try:
        generate_icons(src, out_dir)
    except Exception as e:
        messagebox.showerror("오류", f"아이콘 생성 중 문제가 발생했습니다.\n\n{e}")


if __name__ == "__main__":
    main()
