"""VidPuls – Wasserzeichen auf Gratis-Videos."""

from __future__ import annotations

import shutil
import subprocess
import tempfile
from pathlib import Path

from jam.jampulse_brand import PRODUCT_BRAND, PRODUCT_DOMAIN


def _ffmpeg() -> str | None:
    return shutil.which("ffmpeg")


def apply_watermark(src: Path, *, dest: Path | None = None) -> tuple[bool, str]:
    """VidPuls-Wasserzeichen auf fertiges MP4 (Ecke + dezent mittig)."""
    ff = _ffmpeg()
    if not ff or not src.is_file():
        return False, "ffmpeg oder Quelldatei fehlt"

    out = dest or src
    tmp = out
    if out.resolve() == src.resolve():
        tmp = Path(tempfile.gettempdir()) / f"vidpuls-wm-{src.stem}.mp4"

    brand = PRODUCT_BRAND.replace("'", "\\'")
    domain = PRODUCT_DOMAIN.replace("'", "\\'")
    vf = (
        f"drawtext=text='{brand}':fontsize=42:fontcolor=white@0.55:"
        f"borderw=2:bordercolor=black@0.45:x=w-text_w-36:y=h-text_h-36,"
        f"drawtext=text='{domain}':fontsize=28:fontcolor=white@0.4:"
        f"borderw=1:bordercolor=black@0.35:x=w-text_w-36:y=h-text_h-80,"
        f"drawtext=text='{brand}':fontsize=120:fontcolor=white@0.15:"
        f"x=(w-text_w)/2:y=(h-text_h)/2"
    )
    cmd = [ff, "-y", "-i", str(src), "-vf", vf, "-c:a", "copy", str(tmp)]
    try:
        subprocess.run(cmd, capture_output=True, timeout=300, check=True)
    except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError) as e:
        err = getattr(e, "stderr", b"")
        if isinstance(err, bytes):
            err = err.decode("utf-8", errors="replace")
        return False, str(err or e)[:160]

    if not tmp.is_file() or tmp.stat().st_size < 5000:
        return False, "Wasserzeichen-Export fehlgeschlagen"
    if tmp != out:
        shutil.move(str(tmp), str(out))
    return True, "Wasserzeichen gesetzt"
