# -*- coding: utf-8 -*-
"""test_parser.py — 模块输出解析与状态判定测试"""

from service_monitor.utils.parser import (
    parse_module_output, summarize, _should_skip,
    NORMAL, WARNING, CRITICAL,
)


def test_parse_basic_kv():
    raw = "HOSTNAME:web-01\nCPU_CORES:8\nOS_VERSION:CentOS 7"
    items = parse_module_output(raw, "01_system_basic", "system")
    assert len(items) == 3
    assert items[0].key == "HOSTNAME"
    assert items[0].value == "web-01"
    assert items[0].name == "主机名"


def test_filter_log_and_error_lines():
    raw = (
        "[INFO] 开始检测...\n"
        "HOSTNAME:web-01\n"
        "grep: 警告: 找不到文件\n"
        "需要整数表达式\n"
        "01_system_basic.sh: 行 88: 语法错误\n"
        "ERROR:某某异常\n"
        "CPU_CORES:4\n"
        "[INFO] 完成"
    )
    items = parse_module_output(raw, "01_system_basic", "system")
    keys = [it.key for it in items]
    assert keys == ["HOSTNAME", "CPU_CORES"]


def test_level_field_authoritative():
    # 模块自带 _LEVEL 优先
    raw = "CPU_USAGE:50%\nCPU_USAGE_LEVEL:严重"
    items = parse_module_output(raw, "02_cpu_check", "system")
    cpu = [it for it in items if it.key == "CPU_USAGE"][0]
    assert cpu.status == CRITICAL
    # _LEVEL 字段本身不作为独立项
    assert all(not it.key.endswith("_LEVEL") for it in items)


def test_value_status_word_mapping():
    raw = "MYSQL_CONNECTED:是\nDOCKER_SERVICE_STATUS:运行中"
    items = parse_module_output(raw, "22_mysql_basic", "service")
    for it in items:
        assert it.status == NORMAL


def test_threshold_numeric_judgement():
    # 无 _LEVEL 时用阈值表：CPU_USAGE 阈值 >85%
    raw = "CPU_USAGE:92%"
    items = parse_module_output(raw, "02_cpu_check", "system")
    assert items[0].status in (WARNING, CRITICAL)

    raw2 = "CPU_USAGE:30%"
    items2 = parse_module_output(raw2, "02_cpu_check", "system")
    assert items2[0].status == NORMAL


def test_summarize():
    raw = "CPU_USAGE:92%\nCPU_USAGE_LEVEL:严重\nMEMORY_USAGE:50%\nHOSTNAME:x"
    items = parse_module_output(raw, "m", "system")
    s = summarize(items)
    assert s["total"] == 3
    assert s[CRITICAL] == 1


def test_should_skip():
    assert _should_skip("[INFO] xxx")
    assert _should_skip("# comment")
    assert _should_skip("command not found: free")
    assert not _should_skip("HOSTNAME:web-01")
