# -*- coding: utf-8 -*-
"""test_report_service.py — 报告管理测试"""

from service_monitor.services import report_service as rs


def _sample_modules():
    return [
        {"id": "01_system_basic", "name": "系统基础信息", "category": "system",
         "items": [
             {"key": "HOSTNAME", "name": "主机名", "value": "web-01", "threshold": "", "status": "正常"},
             {"key": "CPU_USAGE", "name": "CPU使用率", "value": "92%", "threshold": ">85%", "status": "严重"},
         ],
         "summary": {"正常": 1, "警告": 0, "严重": 1, "total": 2}},
    ]


def _sample_target():
    return {"id": "local", "name": "本机", "type": "local"}


def test_save_and_get(tmp_data):
    rid = rs.save(_sample_target(), "quick", _sample_modules(), "2026-07-16T10:00:00")
    r = rs.get_report(rid)
    assert r is not None
    assert r["target_name"] == "本机"
    assert r["summary"]["严重"] == 1
    assert r["summary"]["total"] == 2


def test_list_reports(tmp_data):
    rs.save(_sample_target(), "quick", _sample_modules(), "2026-07-16T10:00:00")
    rs.save(_sample_target(), "full", _sample_modules(), "2026-07-16T11:00:00")
    reports = rs.list_reports()
    assert len(reports) == 2
    # 摘要不含明细
    assert "modules" not in reports[0]


def test_delete_report(tmp_data):
    rid = rs.save(_sample_target(), "quick", _sample_modules(), "2026-07-16T10:00:00")
    assert rs.delete_report(rid) is True
    assert rs.get_report(rid) is None


def test_export_markdown(tmp_data):
    rid = rs.save(_sample_target(), "quick", _sample_modules(), "2026-07-16T10:00:00")
    md = rs.export_markdown(rid)
    assert "# 服务巡检报告" in md
    assert "CPU使用率" in md
    assert "异常项" in md   # 有严重项，异常区块存在


def test_export_json(tmp_data):
    rid = rs.save(_sample_target(), "quick", _sample_modules(), "2026-07-16T10:00:00")
    data = rs.export_json(rid)
    assert data["id"] == rid


def test_cleanup_expired(tmp_data):
    # 保存一个旧报告（finished_at 很久以前）
    rid = rs.save(_sample_target(), "quick", _sample_modules(),
                  "2020-01-01T10:00:00", "2020-01-01T10:05:00")
    removed = rs.cleanup_expired(retention_days=14)
    assert removed == 1
    assert rs.get_report(rid) is None
