"""图片工具：PDF 转图片、证照照片归一化（EXIF 转正 + 可配置旋转）。"""
from __future__ import annotations

import io
from pathlib import Path

from app.core.logger import get_logger

logger = get_logger(__name__)


def normalize_image_bytes(path: str | Path, rotation: int = 0) -> bytes:
    """把图片归一化为直立、无 EXIF 方向信息的 PNG 字节。

    - 先按 EXIF Orientation 自动转正（修复手机/相机拍摄照片的横竖颠倒）；
    - 再按 ``rotation`` 顺时针旋转额外角度（无 EXIF 的扫描件需手动指定）；
    - 统一转为 RGB PNG，保证写回 docx 后内容类型一致。

    :param rotation: 顺时针旋转角度（度），0 表示不额外旋转。
    """
    from PIL import Image, ImageOps

    im = Image.open(path)
    im = ImageOps.exif_transpose(im)
    if rotation:
        # Pillow 的 rotate 正角度为逆时针，故顺时针用负角度
        im = im.rotate(-rotation, expand=True)
    buf = io.BytesIO()
    im.convert("RGB").save(buf, format="PNG")
    return buf.getvalue()


def pdf_to_images(pdf_path: str | Path, output_dir: str | Path | None = None) -> list[Path]:
    """把 PDF 每一页转成 PNG，返回图片路径列表。"""
    import pymupdf  # PyMuPDF，延迟导入

    pdf_path = Path(pdf_path)
    output_dir = Path(output_dir) if output_dir else pdf_path.parent
    output_dir.mkdir(parents=True, exist_ok=True)
    stem = pdf_path.stem

    images: list[Path] = []
    doc = pymupdf.open(str(pdf_path))
    try:
        for i, page in enumerate(doc, start=1):
            out = output_dir / f"{stem}_page{i}.png"
            page.get_pixmap(dpi=200).save(str(out))
            images.append(out)
    finally:
        doc.close()
    logger.debug("PDF 转图片 %s -> %d 页", pdf_path.name, len(images))
    return images
