"""Stable machine identifier for license activation."""

from __future__ import annotations

import hashlib
import platform
import subprocess
import uuid
from functools import lru_cache


def _hardware_uuid_macos() -> str:
    try:
        result = subprocess.run(
            ["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"],
            capture_output=True,
            text=True,
            check=False,
            timeout=5,
        )
        for line in result.stdout.splitlines():
            if "IOPlatformUUID" in line:
                parts = line.split('"')
                if len(parts) >= 4:
                    return parts[3].strip()
    except (OSError, subprocess.SubprocessError):
        pass
    return ""


@lru_cache(maxsize=1)
def get_machine_id() -> str:
    raw = _hardware_uuid_macos()
    if not raw:
        raw = f"{uuid.getnode()}:{platform.node()}:{platform.machine()}"
    return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32]


def get_device_name() -> str:
    return platform.node() or "Mac"
