"""Image utilities for the pipeline."""

import logging
import shutil
from pathlib import Path
from typing import Optional

logger = logging.getLogger(__name__)


def scale_down_references(
    image_paths: list[str],
    output_dir: Path,
    max_pixels: int = 2048,
    quality: int = 85,
) -> list[str]:
    """Scale down large reference images, copy small ones as-is.

    Args:
        image_paths: List of absolute image paths.
        output_dir: Directory to write scaled images into.
        max_pixels: Max dimension (width or height). Images smaller
                    than this on both axes are copied unchanged.
        quality: JPEG save quality (1-100).

    Returns:
        List of paths (same length) pointing to output_dir copies.
    """
    try:
        from PIL import Image
    except ImportError:
        logger.warning("Pillow not installed — returning original paths")
        return image_paths

    output_dir.mkdir(parents=True, exist_ok=True)
    result = []

    # Pre-scan for duplicate filenames to avoid collisions
    # e.g. tom_morrison/sheet.jpg + eddie/sheet.jpg → tom_morrison_sheet.jpg, eddie_sheet.jpg
    raw_names = [Path(p).name for p in image_paths]
    duplicated = {n for n in raw_names if raw_names.count(n) > 1}

    for img_path_str in image_paths:
        src = Path(img_path_str)
        if src.name in duplicated:
            base_name = f"{src.parent.name}_{src.name}"
        else:
            base_name = src.name
        dst = output_dir / base_name

        try:
            with Image.open(src) as img:
                w, h = img.size
                if w <= max_pixels and h <= max_pixels:
                    # Small enough — just copy
                    shutil.copy2(src, dst)
                    result.append(str(dst))
                    continue

                # Scale down preserving aspect ratio
                if w >= h:
                    new_w = max_pixels
                    new_h = int(h * max_pixels / w)
                else:
                    new_h = max_pixels
                    new_w = int(w * max_pixels / h)

                resized = img.resize((new_w, new_h), Image.LANCZOS)

                # Save as JPEG (convert RGBA→RGB if needed)
                if resized.mode in ("RGBA", "P"):
                    resized = resized.convert("RGB")

                dst_jpg = dst.with_suffix(".jpg")
                resized.save(dst_jpg, "JPEG", quality=quality)

                src_kb = src.stat().st_size // 1024
                dst_kb = dst_jpg.stat().st_size // 1024
                logger.info(
                    f"Scaled {src.name}: {w}x{h} → {new_w}x{new_h} "
                    f"({src_kb}KB → {dst_kb}KB)"
                )
                result.append(str(dst_jpg))

        except Exception as e:
            logger.warning(f"Failed to scale {src.name}: {e} — using original")
            result.append(img_path_str)

    return result
