"""Flatpak: pending updates via `flatpak remote-ls --updates`."""
from __future__ import annotations

import subprocess

from taninux.update.types import UpdateItem


def _installed_versions() -> dict[str, str]:
    try:
        r = subprocess.run(
            ["flatpak", "list", "--columns=application,version"],
            capture_output=True, text=True, check=False, timeout=10,
        )
    except (FileNotFoundError, subprocess.TimeoutExpired):
        return {}
    versions: dict[str, str] = {}
    for line in r.stdout.splitlines():
        s = line.strip()
        if not s or s.startswith("Application"):
            continue
        parts = s.split("\t")
        if len(parts) >= 2:
            versions[parts[0]] = parts[1]
    return versions


def fetch() -> list[UpdateItem]:
    try:
        r = subprocess.run(
            ["flatpak", "remote-ls", "--updates",
             "--columns=application,version,download-size"],
            capture_output=True, text=True, check=False, timeout=60,
        )
    except (FileNotFoundError, subprocess.TimeoutExpired):
        return []
    if r.returncode != 0:
        return []

    current = _installed_versions()
    items: list[UpdateItem] = []
    for line in r.stdout.splitlines():
        s = line.strip()
        if not s or s.startswith("Application"):
            continue
        parts = s.split("\t")
        if len(parts) < 2:
            continue
        app, new_ver = parts[0], parts[1]
        size = 0
        if len(parts) >= 3:
            # download-size column is human-readable like "12.3 MB"
            size_str = parts[2]
            try:
                from taninux.maintain.scanners.pacman import _parse_size
                size = _parse_size(size_str)
            except Exception:
                size = 0
        items.append(UpdateItem(
            source="flatpak",
            name=app,
            current_version=current.get(app, "?"),
            new_version=new_ver,
            size_bytes=size,
        ))
    return items
