# -*- coding: utf-8 -*-
# 本机设备标识（login 等接口 key/maxoror）。

from __future__ import annotations

import os
import re
import subprocess
import sys
import uuid


def _cache_path() -> str:
    base = os.path.expanduser("~/.bsphp_python_demo")
    os.makedirs(base, exist_ok=True)
    return os.path.join(base, "machine_code.txt")


def _read_persisted() -> str | None:
    p = _cache_path()
    if os.path.isfile(p):
        try:
            s = open(p, "r", encoding="utf-8").read().strip()
            if s:
                return s
        except OSError:
            pass
    return None


def _write_persisted(s: str) -> None:
    try:
        with open(_cache_path(), "w", encoding="utf-8") as f:
            f.write(s)
    except OSError:
        pass


def _darwin_ioreg_uuid() -> str | None:
    try:
        out = subprocess.check_output(
            ["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"],
            stderr=subprocess.DEVNULL,
            text=True,
            timeout=5,
        )
    except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):
        return None
    m = re.search(r'"IOPlatformUUID"\s*=\s*"([^"]+)"', out)
    if m:
        return m.group(1).strip()
    return None


def get_machine_code() -> str:
    if sys.platform == "darwin":
        u = _darwin_ioreg_uuid()
        if u:
            return u
    cached = _read_persisted()
    if cached:
        return cached
    s = uuid.uuid4().hex.lower()
    _write_persisted(s)
    return s
