#!/usr/bin/env python3
"""昇腾 NPU 环境检查:硬件卡数/显存、CANN 版本、rank_table 校验、HCCL 冒烟。
用法:
  python3 env_check.py --cards 8
  python3 env_check.py --cards 8 --hccl-smoke
  python3 env_check.py --cards 8 --rank-table ./rank_table.json
输出: env_report.json(JSON 报告),退出码 0=全部通过。
"""
import argparse, json, os, re, subprocess, sys


def run(cmd, timeout=60):
    """执行命令并返回 (ok, stdout)。找不到可执行文件不算致命错误。"""
    try:
        r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
        return r.returncode == 0, r.stdout
    except (subprocess.TimeoutExpired, FileNotFoundError):
        return False, ""


def check_npu_smi(expected_cards):
    """npu-smi info 解析卡数与每卡 HBM。"""
    ok, out = run("npu-smi info")
    if not ok:
        return False, {"error": "npu-smi 不可用,请检查昇腾驱动"}, 0, 0
    cards = re.findall(r"\|(\d+)\s+\|", out)
    card_count = len(set(cards)) if cards else 0
    mem_match = re.search(r"(\d+)\s*GB", out)
    mem_gb = int(mem_match.group(1)) if mem_match else 0
    health = "Health" not in out or "OK" in out
    passed = card_count >= expected_cards and health
    return passed, {"card_count": card_count, "expected": expected_cards,
                    "mem_gb_per_card": mem_gb, "health_ok": health}, card_count, mem_gb


def check_torch_npu():
    """检查 torch/torch_npu 可用性。"""
    code = (
        "import torch, torch_npu; "
        "print(torch.__version__, torch_npu.__version__, torch.npu.is_available())"
    )
    ok, out = run(f"python3 -c \"{code}\"")
    if not ok:
        return False, {"error": "torch_npu 不可用", "output": out.strip()[:200]}
    parts = out.split()
    return True, {"torch": parts[0] if parts else "", "torch_npu": parts[1] if len(parts) > 1 else "",
                  "npu_available": len(parts) > 2 and parts[2] == "True"}


def check_rank_table(path):
    """校验 rank_table.json 结构:device 数量、rank_id 唯一性。"""
    if not path or not os.path.exists(path):
        return False, {"error": f"rank_table 不存在: {path}"}
    try:
        with open(path, encoding="utf-8") as f:
            data = json.load(f)
    except (json.JSONDecodeError, OSError) as e:
        return False, {"error": f"rank_table 解析失败: {e}"}
    devices = []
    def walk(node):
        if isinstance(node, dict):
            if "devices" in node:
                devices.extend(node["devices"])
            for v in node.values():
                walk(v)
        elif isinstance(node, list):
            for v in node:
                walk(v)
    walk(data)
    rank_ids = [d.get("rank_id") for d in devices if isinstance(d, dict) and "rank_id" in d]
    unique = len(rank_ids) == len(set(rank_ids))
    return unique, {"device_count": len(devices), "rank_ids": rank_ids, "rank_unique": unique}


def hccl_smoke(cards):
    """纯通信冒烟:8 卡 AllReduce 之和应为 n*(n+1)/2。"""
    code = (
        "import torch, torch_npu, torch.distributed as dist;"
        "from torch.nn.parallel import DistributedDataParallel as DDP;"
        "dist.init_process_group(backend='hccl');"
        "rank = dist.get_rank(); torch.npu.set_device(rank);"
        "t = torch.full([1024], 1.0, dtype=torch.float32, device='npu');"
        "dist.all_reduce(t);"
        "s = int(t[0].item()); dist.barrier();"
        "expected = int(dist.get_world_size());"
        "print('SUM', s, 'EXPECTED', expected, 'OK' if s == expected else 'FAIL')"
    )
    ok, out = run(f"python3 -c \"{code}\"", timeout=300)
    return ok and "OK" in out, {"output": out.strip()[:300]}


def main():
    ap = argparse.ArgumentParser(description="昇腾 NPU 并行切分环境检查")
    ap.add_argument("--cards", type=int, default=8, help="期望可用卡数")
    ap.add_argument("--hccl-smoke", action="store_true", help="执行 HCCL 通信冒烟测试")
    ap.add_argument("--rank-table", default=None, help="rank_table.json 路径")
    ap.add_argument("--output", default="env_report.json", help="输出报告文件")
    args = ap.parse_args()

    report = {"checks": {}, "passed": True}
    passed, info, card_count, mem_gb = check_npu_smi(args.cards)
    report["checks"]["npu_smi"] = {"passed": passed, **info}
    report["passed"] = report["passed"] and passed

    passed, info = check_torch_npu()
    report["checks"]["torch_npu"] = {"passed": passed, **info}
    report["passed"] = report["passed"] and passed

    if args.rank_table:
        passed, info = check_rank_table(args.rank_table)
        report["checks"]["rank_table"] = {"passed": passed, **info}
        report["passed"] = report["passed"] and passed

    if args.hccl_smoke:
        passed, info = hccl_smoke(args.cards)
        report["checks"]["hccl_smoke"] = {"passed": passed, **info}
        report["passed"] = report["passed"] and passed

    with open(args.output, "w", encoding="utf-8") as f:
        json.dump(report, f, ensure_ascii=False, indent=2)
    print(json.dumps(report, ensure_ascii=False, indent=2))
    sys.exit(0 if report["passed"] else 1)


if __name__ == "__main__":
    main()