from __future__ import annotations

import hashlib
import os
import platform
import subprocess
import uuid
from pathlib import Path


def _safe_run(cmd: list[str]) -> str:
    try:
        out = subprocess.check_output(cmd, stderr=subprocess.DEVNULL, text=True, timeout=3)
        return (out or '').strip()
    except Exception:
        return ''


def _windows_machine_guid() -> str:
    try:
        import winreg  # type: ignore
        with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Cryptography") as key:
            val, _ = winreg.QueryValueEx(key, "MachineGuid")
            return str(val or '').strip()
    except Exception:
        return ''


def _disk_serial() -> str:
    system = platform.system().lower()
    if system == 'windows':
        txt = _safe_run(['wmic', 'diskdrive', 'get', 'SerialNumber'])
        lines = [ln.strip() for ln in txt.splitlines() if ln.strip() and 'serial' not in ln.lower()]
        return lines[0] if lines else ''
    return ''


def build_raw_fingerprint() -> str:
    pieces = [
        _windows_machine_guid(),
        _disk_serial(),
        os.environ.get('COMPUTERNAME', ''),
        platform.node(),
        hex(uuid.getnode()),
    ]
    raw = '|'.join(p for p in pieces if p)
    if not raw:
        raw = f"fallback|{platform.platform()}|{Path.home()}"
    return raw


def get_device_code() -> str:
    raw = build_raw_fingerprint().encode('utf-8', 'ignore')
    digest = hashlib.sha256(raw).hexdigest().upper()
    parts = [digest[i:i+4] for i in range(0, 16, 4)]
    return 'MSM-' + '-'.join(parts)
