import os, getpass, netrc
from typing import Optional
from rich.console import Console

console = Console()

def get_current_user() -> str:
    """Returns the current username, robustly on Linux environments."""
    try:
        return os.environ['USER']
    except KeyError:
        return getpass.getuser()

def get_wandb_api_key() -> Optional[str]:
    """
    Attempts to read the W&B API key from the local ~/.netrc file.
    """
    try:
        login_info = netrc.netrc().authenticators("api.wandb.ai")
        if login_info:
            username, _, api_key = login_info
            console.print(f"[dim]Found W&B API key for user: {username}[/dim]")
            return api_key
        else:
            return None
    except FileNotFoundError:
        return None
    except Exception as e:
        console.print(f"[dim bold red]Warning: Could not read W&B credentials: {e}[/dim]")
        return None