"""Hardware fingerprint generation for SaaS thin client.

Replaces the daemon's bind-time fingerprint with host-derived identity.
Generates a stable, deterministic fingerprint from available host identifiers.
"""

import hashlib
import os
import socket
import uuid


def generate_fingerprint() -> str:
    """Generate a stable hardware fingerprint from host identifiers.

    Collects identifiers in priority order:
    1. RunPod pod ID (RUNPOD_POD_ID env var)
    2. Container ID (from /proc/self/cgroup for Docker/Podman)
    3. Hostname + MAC address (fallback)

    Returns:
        64-character hex string (SHA256 of concatenated identifiers)
    """
    parts = []

    # RunPod pod ID
    pod_id = os.environ.get("RUNPOD_POD_ID")
    if pod_id:
        parts.append(f"runpod:{pod_id}")

    # Container ID from cgroup
    try:
        with open("/proc/self/cgroup", "r") as f:
            for line in f:
                if "docker" in line or "kubepods" in line:
                    parts.append(f"container:{line.strip().split('/')[-1][:64]}")
                    break
    except (FileNotFoundError, PermissionError):
        pass

    # Fallback: hostname + MAC
    parts.append(f"host:{socket.gethostname()}")
    parts.append(f"mac:{uuid.getnode():012x}")

    return hashlib.sha256("|".join(parts).encode()).hexdigest()
