"""PNG 메타데이터 임베딩 유틸리티.

Pillow의 PngInfo를 사용하여 tEXt 청크에 생성 정보를 기록합니다.
"""

import logging
from pathlib import Path
from typing import Dict, Optional, Union

from PIL import Image
from PIL.PngImagePlugin import PngInfo

logger = logging.getLogger(__name__)


def embed_png_metadata(
    file_path: Union[str, Path],
    metadata: Dict[str, Optional[str]],
) -> bool:
    """PNG 파일에 tEXt 메타데이터를 삽입합니다.

    Args:
        file_path: PNG 파일 경로
        metadata: 키-값 메타데이터 딕셔너리 (None 값은 건너뜀)

    Returns:
        성공 여부
    """
    file_path = Path(file_path)
    if not file_path.exists() or file_path.suffix.lower() != ".png":
        logger.warning("PNG metadata skip: not a PNG or missing — %s", file_path)
        return False

    try:
        img = Image.open(file_path)
        png_info = PngInfo()

        for key, value in metadata.items():
            if value is not None:
                png_info.add_text(key, str(value))

        img.save(file_path, pnginfo=png_info)
        logger.debug("PNG metadata embedded: %s (%d keys)", file_path.name, len(metadata))
        return True
    except Exception as exc:
        logger.warning("PNG metadata embedding failed for %s: %s", file_path, exc)
        return False
