"""Retire runtime_paths.compat_link() once no process still references that name."""

from __future__ import annotations

import os
import subprocess
import sys
from collections.abc import Callable, Iterator
from pathlib import Path

from runtime_paths import compat_link, runtime_dir

TIMER_UNIT = "systray-runtime-compat-retire.timer"


def _cmdlines(proc_root: Path) -> Iterator[tuple[int, str]]:
    for entry in proc_root.iterdir():
        if not entry.name.isdigit():
            continue
        try:
            raw = (entry / "cmdline").read_bytes()
        except OSError:
            continue
        yield int(entry.name), raw.replace(b"\0", b" ").decode("utf-8", "replace")


def holders(link: Path, proc_root: Path = Path("/proc")) -> list[int]:
    needle = str(link)
    self_pid = os.getpid()
    try:
        entries = list(_cmdlines(proc_root))
    except OSError:
        return [self_pid]
    return sorted(pid for pid, cmdline in entries if pid != self_pid and needle in cmdline)


def _disable_timer() -> None:
    subprocess.run(
        ["systemctl", "--user", "disable", "--now", TIMER_UNIT],
        check=False,
        capture_output=True,
    )


def retire(
    link: Path | None = None,
    proc_root: Path = Path("/proc"),
    disable_timer: Callable[[], None] = _disable_timer,
) -> str:
    target = link if link is not None else compat_link()
    if not target.is_symlink():
        disable_timer()
        return "absent"
    if target.resolve() != runtime_dir().resolve():
        return "foreign-target"
    remaining = holders(target, proc_root)
    if remaining:
        return f"held:{len(remaining)}"
    target.unlink()
    disable_timer()
    return "retired"


def main(argv: list[str]) -> int:
    if len(argv) != 1:
        return 2
    print(retire())
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
