#!/usr/bin/env python3
"""Reinstall uv tools whose venv targets a Python version that no longer
matches the system Python (e.g. after 3.14 -> 3.15), preserving package
versions. Runs from a pacman post-upgrade hook on the 'python' package; the
hook runs it with the new interpreter, so sys.version_info is the current
version.

Each user's uv runs via their login shell (runuser -l), so UV_TOOL_DIR /
XDG_DATA_HOME resolve as they would over ssh/login. We only reinstall tools
already present; a user we can't resolve is skipped."""

import configparser, os, pwd, subprocess, sys

system_version = "%d.%d" % sys.version_info[:2]


def as_user(user, command):
    return subprocess.run(
        ["runuser", "-l", user, "-c", command],
        stdin=subprocess.DEVNULL,
        capture_output=True,
        text=True,
    )


for account in pwd.getpwall():
    if account.pw_shell.endswith(("/nologin", "/false")):
        continue
    tools_dir = as_user(account.pw_name, "uv tool dir").stdout.strip()
    if not os.path.isdir(tools_dir):
        continue
    for tool_name in sorted(os.listdir(tools_dir)):
        # pyvenv.cfg is sectionless (allow_unnamed_section: Python 3.13+).
        config = configparser.ConfigParser(allow_unnamed_section=True)
        config.read(os.path.join(tools_dir, tool_name, "pyvenv.cfg"))
        full_version = config.get(
            configparser.UNNAMED_SECTION, "version_info", fallback=None
        )
        venv_version = full_version and ".".join(full_version.split(".")[:2])
        if not venv_version or venv_version == system_version:
            continue
        print(f"Reinstalling {tool_name} for {account.pw_name}")
        as_user(account.pw_name, f"uv tool install --reinstall {tool_name}")
