"""Assistant UI avatar asset helpers."""

from __future__ import annotations

import logging
import shutil
import subprocess
from pathlib import Path
from threading import Lock

LOGGER = logging.getLogger("sentineledge.avatar_assets")

TAIL_SECONDS = 0.5
_TAIL_LOCK = Lock()


def _is_usable(path: Path) -> bool:
    """Return True when file exists and has non-zero size."""
    return path.exists() and path.is_file() and path.stat().st_size > 0


def _is_tail_fresh(final_gif: Path, final_tail: Path) -> bool:
    """Return True when tail exists and is at least as recent as source gif."""
    if not _is_usable(final_tail):
        return False
    return final_tail.stat().st_mtime_ns >= final_gif.stat().st_mtime_ns


def ensure_final_tail_gif(static_dir: Path) -> tuple[bool, str | None]:
    """Ensure final_tail.gif exists by extracting last ~0.5s from final.gif."""
    final_gif = static_dir / "final.gif"
    final_tail = static_dir / "final_tail.gif"

    if not _is_usable(final_gif):
        return False, f"missing source gif: {final_gif}"

    with _TAIL_LOCK:
        if _is_tail_fresh(final_gif, final_tail):
            return True, None

        ffmpeg_path = shutil.which("ffmpeg")
        if not ffmpeg_path:
            return False, "ffmpeg not available in PATH"

        temp_tail = static_dir / "final_tail.tmp.gif"
        command = [
            ffmpeg_path,
            "-hide_banner",
            "-loglevel",
            "error",
            "-y",
            "-sseof",
            f"-{TAIL_SECONDS}",
            "-t",
            f"{TAIL_SECONDS}",
            "-i",
            str(final_gif),
            "-loop",
            "0",
            str(temp_tail),
        ]

        try:
            subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30)
            if not _is_usable(temp_tail):
                raise RuntimeError("ffmpeg produced empty final_tail.gif")
            temp_tail.replace(final_tail)
            LOGGER.info("Generated final tail gif")
            return True, None
        except Exception as exc:  # pragma: no cover - runtime dependent on local ffmpeg
            LOGGER.warning("Could not generate final_tail.gif: %s", exc)
            if temp_tail.exists():
                try:
                    temp_tail.unlink()
                except OSError:
                    pass
            return False, str(exc)
