import os
import platform
import subprocess
from typing import Optional
import briefcase_ai as bf

def detect_hardware() -> bf.HardwareMetadata:
    """
    Automatically detects local hardware capabilities.
    Normalizes between Metal (Apple) and CUDA (NVIDIA).
    """
    system = platform.system().lower()
    machine = platform.machine().lower()
    
    if system == "darwin" and "arm" in machine:
        # Apple Silicon
        hw = bf.HardwareMetadata("metal", "Apple Silicon GPU")
        hw.with_provider("local")
        return hw
        
    try:
        # Check for NVIDIA
        res = subprocess.check_output(["nvidia-smi", "--query-gpu=name,memory.total", "--format=csv,noheader,nounits"])
        name, memory = res.decode().strip().split(",")
        hw = bf.HardwareMetadata("cuda", name.strip())
        hw.with_vram(float(memory) / 1024.0)
        hw.with_provider("local")
        return hw
    except Exception:
        pass
        
    return bf.HardwareMetadata("cpu", "Standard CPU")
