"""AUR: pending updates via `paru -Qua` (oder yay als Fallback)."""
from __future__ import annotations

import re
import shutil
import subprocess

from taninux.update.types import UpdateItem

_PARU_LINE = re.compile(r"^(\S+)\s+(\S+)\s+->\s+(\S+)")


def _helper() -> str | None:
    for h in ("paru", "yay"):
        if shutil.which(h):
            return h
    return None


def fetch() -> list[UpdateItem]:
    helper = _helper()
    if not helper:
        return []
    try:
        r = subprocess.run(
            [helper, "-Qua"],
            capture_output=True, text=True, check=False, timeout=60,
        )
    except (FileNotFoundError, subprocess.TimeoutExpired):
        return []
    if r.returncode not in (0, 1):
        return []
    items: list[UpdateItem] = []
    for line in r.stdout.splitlines():
        line = line.strip()
        if not line or line.startswith(":"):  # paru status lines beginnen mit ::
            continue
        m = _PARU_LINE.match(line)
        if m:
            items.append(UpdateItem(
                source="aur",
                name=m.group(1),
                current_version=m.group(2),
                new_version=m.group(3),
                size_bytes=0,
                extra={"helper": helper},
            ))
    return items
