# SPDX-License-Identifier: Apache-2.0
"""
Machine fingerprinting for GPU/CUDA platforms.

Extends the core fingerprinting with GPU-specific functionality.
"""

from typing import Optional, List

# Import from lightr_vllm_core
from lightr_vllm_core import FingerprintPolicy
from lightr_vllm_core.cli.get_fingerprint import (
    get_cpu_id,
    get_mac_addresses,
    get_machine_fingerprint as _core_get_machine_fingerprint,
    get_fingerprint_info as _core_get_fingerprint_info,
)


def get_gpu_uuids() -> List[str]:
    """Get GPU UUIDs (NVIDIA only for now)."""
    uuids = []

    try:
        import subprocess
        result = subprocess.run(
            ["nvidia-smi", "--query-gpu=uuid", "--format=csv,noheader"],
            capture_output=True,
            text=True,
            check=True
        )
        uuids = [line.strip() for line in result.stdout.strip().split("\n") if line.strip()]
    except Exception:
        pass

    return uuids


def get_machine_fingerprint(
    include_gpu: bool = False,
    salt: Optional[str] = None
) -> str:
    """
    Generate a unique machine fingerprint.

    Args:
        include_gpu: Whether to include GPU UUIDs (may cause issues in containers)
        salt: Optional salt for hashing

    Returns:
        Hex-encoded SHA-256 hash of machine characteristics
    """
    return _core_get_machine_fingerprint(include_gpu=include_gpu, salt=salt)


def get_fingerprint_info() -> dict:
    """
    Get detailed fingerprint information for debugging.

    Returns:
        Dictionary with fingerprint components
    """
    return _core_get_fingerprint_info()


def verify_fingerprint(
    expected: str,
    include_gpu: bool = False,
    salt: Optional[str] = None
) -> bool:
    """
    Verify if current machine matches expected fingerprint.

    Args:
        expected: Expected fingerprint hash
        include_gpu: Whether GPU was included in original fingerprint
        salt: Salt used in original fingerprint

    Returns:
        True if fingerprints match
    """
    current = get_machine_fingerprint(include_gpu=include_gpu, salt=salt)
    return current == expected
