"""Ascend NPU hardware detection."""

from __future__ import annotations

import os
import subprocess
import sys


def check_ascend_available() -> tuple[bool, str]:
    """Check if Ascend NPU is available."""
    try:
        probe = (
            "import torch, torch_npu; "
            "ok = hasattr(torch, 'npu') and torch.npu.is_available(); "
            "cnt = torch.npu.device_count() if ok else 0; "
            "print(cnt)"
        )
        env = os.environ.copy()
        env["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0"
        result = subprocess.run(
            [sys.executable, "-c", probe],
            capture_output=True,
            text=True,
            timeout=20,
            env=env,
        )
        if result.returncode != 0:
            stderr = (result.stderr or "").strip()
            if "No module named" in stderr and "torch_npu" in stderr:
                return False, "❌ torch_npu not installed"
            reason = stderr or (result.stdout or "Ascend probe failed").strip()
            return (
                False,
                f"❌ Error: {reason.splitlines()[-1] if reason else 'Ascend probe failed'}",
            )

        output = (result.stdout or "").strip()
        try:
            device_count = int(output.splitlines()[-1]) if output else 0
        except ValueError:
            device_count = 0
        if device_count > 0:
            return True, "✅ Ascend NPU ready"
        return False, "❌ Ascend NPU not detected"
    except subprocess.TimeoutExpired:
        return False, "❌ Error: Ascend probe timeout"
    except Exception as e:
        return False, f"❌ Error: {e}"
