import platform
import sys

def detect_backend():
    """
    Auto-detects the best available backend.
    Returns ('mlx', mlx_module) or ('numpy', None)
    """
    system = platform.system()
    machine = platform.machine()

    if system == "Darwin" and machine == "arm64":
        try:
            import mlx.core as mx
            return "mlx", mx
        except ImportError:
            pass

    return "numpy", None


def get_hardware_report():
    """Returns a human-readable summary of what Kiri is running on."""
    import platform
    system = platform.system()
    machine = platform.machine()
    backend, mx = detect_backend()

    lines = ["╭─ Kiri 🌫️ ─────────────────────────────╮"]

    if backend == "mlx":
        import mlx.core as mx
        mem = "unknown"
        try:
            import subprocess
            result = subprocess.run(
                ["sysctl", "-n", "hw.memsize"],
                capture_output=True, text=True
            )
            bytes_val = int(result.stdout.strip())
            mem = f"{bytes_val // (1024**3)}GB unified memory"
        except Exception:
            pass
        lines.append(f"│  Backend  : Apple Silicon (MLX)        │")
        lines.append(f"│  Chip     : {machine:<28}│")
        lines.append(f"│  Memory   : {mem:<28}│")
        lines.append(f"│  Status   : ✓ Metal GPU + CPU active   │")
    else:
        import os
        cpu = platform.processor() or platform.machine()
        cpu = cpu[:28]
        lines.append(f"│  Backend  : CPU (NumPy)                │")
        lines.append(f"│  CPU      : {cpu:<28}│")
        lines.append(f"│  Status   : ✓ Running on CPU           │")
        lines.append(f"│  Tip      : Install on Apple Silicon   │")
        lines.append(f"│           : for 10x faster training    │")

    lines.append("╰────────────────────────────────────────╯")
    return "\n".join(lines)


BACKEND, _MX = detect_backend()
