from __future__ import annotations

import sys
import tkinter as tk
from pathlib import Path

from PIL import Image, ImageTk


WINDOW_ICON_PNG = Path(__file__).resolve().parent.parent / "assets" / "sunny_erp_app.png"
WINDOW_ICON_ICO = Path(__file__).resolve().parent.parent / "assets" / "sunny_erp_app.ico"
WINDOW_ICON_SIZES = (16, 24, 32, 48, 64)


def resolve_runtime_asset(relative_path: str) -> Path:
    if getattr(sys, "frozen", False):
        base_dir = Path(getattr(sys, "_MEIPASS", Path(sys.executable).resolve().parent))
    else:
        base_dir = Path(__file__).resolve().parent.parent
    return base_dir / relative_path


def apply_window_icon(window: tk.Misc, *, default: bool = False) -> None:
    icon_photos: list[ImageTk.PhotoImage] = []
    try:
        icon_png = resolve_runtime_asset("assets/sunny_erp_app.png")
        if icon_png.exists():
            source = Image.open(icon_png).convert("RGBA")
            for size in WINDOW_ICON_SIZES:
                icon_photos.append(ImageTk.PhotoImage(source.resize((size, size), Image.Resampling.LANCZOS)))
    except Exception:
        icon_photos = []

    if icon_photos:
        try:
            setattr(window, "_sunny_erp_icon_photos", icon_photos)
            window.iconphoto(bool(default), *icon_photos)
        except Exception:
            pass

    if sys.platform == "win32":
        try:
            icon_ico = resolve_runtime_asset("assets/sunny_erp_app.ico")
            if icon_ico.exists():
                window.iconbitmap(str(icon_ico))
        except Exception:
            pass
