import uuid
from pathlib import Path

_PULI_DIR = Path.home() / ".puli"
_MACHINE_ID_FILE = _PULI_DIR / "machine_id"
_TOKEN_FILE = _PULI_DIR / "token"


def _ensure_dir() -> None:
    _PULI_DIR.mkdir(mode=0o700, exist_ok=True)


def get_machine_id() -> str:
    _ensure_dir()
    if _MACHINE_ID_FILE.exists():
        return _MACHINE_ID_FILE.read_text().strip()
    machine_id = str(uuid.uuid4())
    _MACHINE_ID_FILE.write_text(machine_id)
    return machine_id


def read_token() -> str | None:
    if _TOKEN_FILE.exists():
        token = _TOKEN_FILE.read_text().strip()
        return token or None
    return None


def write_token(token: str) -> None:
    _ensure_dir()
    _TOKEN_FILE.write_text(token)


def clear_token() -> None:
    if _TOKEN_FILE.exists():
        _TOKEN_FILE.unlink()
