"""Firmware: pending updates via `fwupdmgr get-updates --json`."""
from __future__ import annotations

import json
import subprocess

from taninux.update.types import UpdateItem


def fetch() -> list[UpdateItem]:
    try:
        r = subprocess.run(
            ["fwupdmgr", "get-updates", "--json"],
            capture_output=True, text=True, check=False, timeout=30,
        )
    except (FileNotFoundError, subprocess.TimeoutExpired):
        return []
    if r.returncode != 0 or not r.stdout.strip():
        return []
    try:
        data = json.loads(r.stdout)
    except json.JSONDecodeError:
        return []
    items: list[UpdateItem] = []
    for dev in data.get("Devices", []):
        releases = dev.get("Releases", [])
        if not releases:
            continue
        rel = releases[0]
        items.append(UpdateItem(
            source="fwupd",
            name=dev.get("Name", "?"),
            current_version=dev.get("Version", "?"),
            new_version=rel.get("Version", "?"),
            size_bytes=int(rel.get("Size", 0) or 0),
            extra={"device_id": dev.get("DeviceId", "")},
        ))
    return items
