"""Platform-specific screenshot backends (Win GDI/PIL, macOS screencapture).

Used by desktop_screenshot_capture before/alongside Linux tools.
"""

from __future__ import annotations

import shutil
import subprocess
from pathlib import Path
from typing import Callable

from .detect import os_family


def capture_raw_for_platform(
    output_path: Path,
    *,
    runner: Callable[..., subprocess.CompletedProcess[str]],
) -> tuple[str, Path] | None:
    """Try OS-native capture. Return (backend, path) or None to fall through."""
    family = os_family()
    if family == "windows":
        return _capture_windows(output_path)
    if family == "macos":
        return _capture_macos(output_path, runner=runner)
    return None


def _capture_windows(output_path: Path) -> tuple[str, Path] | None:
    # 1) mss (works on many Windows installs when display is available)
    try:
        import mss  # type: ignore

        png_path = output_path.with_suffix(".png")
        with mss.mss() as grabber:
            monitor = grabber.monitors[0]
            shot = grabber.grab(monitor)
            mss.tools.to_png(shot.rgb, shot.size, output=str(png_path))
        if png_path.is_file() and png_path.stat().st_size > 0:
            return "mss_windows", png_path
    except Exception:
        pass

    # 2) Pillow ImageGrab (GDI)
    try:
        from PIL import ImageGrab  # type: ignore

        png_path = output_path.with_suffix(".png")
        image = ImageGrab.grab(all_screens=True)
        image.save(str(png_path), format="PNG")
        if png_path.is_file() and png_path.stat().st_size > 0:
            return "pil_imagegrab", png_path
    except Exception:
        pass

    return None


def _capture_macos(
    output_path: Path,
    *,
    runner: Callable[..., subprocess.CompletedProcess[str]],
) -> tuple[str, Path] | None:
    tool = shutil.which("screencapture") or "/usr/sbin/screencapture"
    png_path = output_path.with_suffix(".png")
    if Path(tool).exists() or shutil.which("screencapture"):
        completed = runner(
            [tool, "-x", "-t", "png", str(png_path)],
            capture_output=True,
            text=True,
            check=False,
        )
        if completed.returncode == 0 and png_path.is_file() and png_path.stat().st_size > 0:
            return "screencapture", png_path

    try:
        import mss  # type: ignore

        with mss.mss() as grabber:
            monitor = grabber.monitors[0]
            shot = grabber.grab(monitor)
            mss.tools.to_png(shot.rgb, shot.size, output=str(png_path))
        if png_path.is_file() and png_path.stat().st_size > 0:
            return "mss_macos", png_path
    except Exception:
        pass

    return None
