# frozen_string_literal: true
require 'net_cat'

module NetCatScript
# 示例：网络设备健康检查脚本
# 展示如何使用检查点功能
class ExampleHealthCheck < NetCat::DeviceScript
  def run(connection)
    record_start!
    log_info("开始设备健康检查...")

    # === 检查点1: 检查设备基本信息 ===
    checkpoint :device_info, "获取设备信息" do |c|
      c.description = "获取设备主机名和版本信息"
      c.expected = "成功获取设备信息"
      c.actual = connection.cli("show version")
      c.passed = c.actual.include?("Version")
      c.reason = "无法获取设备版本信息" unless c.passed
    end

    # === 检查点2: 检查CPU利用率 ===
    checkpoint :cpu_check, "检查CPU利用率" do |c|
      c.description = "验证CPU利用率不超过阈值"
      c.expected = "CPU利用率 < 70%"
      c.actual = connection.cli("show cpu usage")

      # 假设输出包含 "CPU utilization: 45%"
      if c.actual.match(/CPU utilization[:\s]+(\d+)%/i)
        cpu_percent = Regexp.last_match(1).to_i
        c.passed = cpu_percent < 70
        c.reason = "CPU利用率过高: #{cpu_percent}%" unless c.passed
        c.suggestion = "检查是否有异常进程占用CPU资源" unless c.passed
      else
        c.passed = false
        c.reason = "无法解析CPU利用率输出"
        c.suggestion = "检查命令输出格式是否正确"
      end
    end

    # === 检查点3: 检查风扇状态（依赖CPU检查通过） ===
    checkpoint :fan_check, "检查风扇状态" do |c|
      c.description = "检查所有风扇运行状态"
      c.expected = "所有风扇状态为Normal"

      # 如果CPU检查失败，跳过此检查
      skip_if_failed(:cpu_check, "CPU检查未通过，跳过风扇检查")
      next if c.skipped

      c.actual = connection.cli("show fan")
      c.passed = c.actual.include?("Normal") && !c.actual.include?("Fault")

      unless c.passed
        c.reason = "检测到风扇异常"
        c.suggestion = "检查风扇硬件，必要时安排更换"
      end
    end

    log_info("健康检查完成")
    build_script_result
  end
end
end