from __future__ import annotations

import shutil
import subprocess
from dataclasses import dataclass
from pathlib import Path

from src.errors import UserError


@dataclass(frozen=True)
class Cwebp:
    exe: str

    def run(self, *, input_path: Path, output_path: Path, quality: int) -> None:
        cmd = [self.exe, "-q", str(int(quality)), str(input_path), "-o", str(output_path)]
        try:
            subprocess.run(
                cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True
            )
        except FileNotFoundError as exc:
            raise UserError("Missing dependency: cwebp (not found on PATH).") from exc
        except subprocess.CalledProcessError as exc:
            msg = (exc.stderr or "").strip() or "cwebp failed"
            raise UserError(f"cwebp failed: {msg}") from exc


def find_cwebp() -> Cwebp | None:
    exe = shutil.which("cwebp")
    if not exe:
        return None
    return Cwebp(exe=exe)


def require_cwebp() -> Cwebp:
    tool = find_cwebp()
    if tool is None:
        raise UserError(
            "Missing dependency: cwebp (install WebP tools and ensure cwebp is on PATH)."
        )
    return tool
