"""Worker credential helpers for issuing and validating machine tokens."""

from __future__ import annotations

import hashlib
import secrets


def mint_worker_token() -> tuple[str, str, str]:
    """Return raw token, persisted hash, and a short operator-visible suffix."""
    token = f"wk_{secrets.token_urlsafe(24)}"
    return token, hash_worker_token(token), token[-4:]


def hash_worker_token(token: str) -> str:
    """Hash a worker bearer token before persistence or comparison."""
    return hashlib.sha256(token.encode()).hexdigest()


def is_hashed_worker_token(value: str | None) -> bool:
    """Best-effort detection for already-migrated worker token hashes."""
    if not value or len(value) != 64:
        return False
    return all(ch in "0123456789abcdef" for ch in value.lower())
