from __future__ import annotations

import os
from pathlib import Path

PROC_ROOT: Path = Path("/proc")


def account_has_live_session(account_home: Path, proc_root: Path | None = None) -> bool:
    """Whether any running process was launched against this account's config dir.

    A live Claude CLI session holds the account's refresh grant in memory and rotates
    it itself; rotating the on-disk grant underneath it revokes the whole chain.
    Fail-closed: an unreadable process table counts as live."""
    root = PROC_ROOT if proc_root is None else proc_root
    try:
        target = Path(os.path.realpath(account_home))
    except OSError:
        return True
    try:
        entries = os.listdir(root)
    except OSError:
        return True
    for entry in entries:
        if not entry.isdigit():
            continue
        try:
            environ = (root / entry / "environ").read_bytes()
        except OSError:
            continue
        for item in environ.split(b"\x00"):
            if not item.startswith(b"CLAUDE_CONFIG_DIR="):
                continue
            value = item.split(b"=", 1)[1].decode("utf-8", errors="surrogateescape")
            if not value:
                continue
            try:
                if Path(os.path.realpath(value)) == target:
                    return True
            except OSError:
                return True
    return False


__all__ = ["PROC_ROOT", "account_has_live_session"]
