"""Unit tests for agent_diagnose_service."""

import json

from server.application.agent_diagnose_service import (
    build_diagnose_errors,
    central_status,
    has_agent_monitoring,
    parse_remote_probe,
)


class _Srv:
    def __init__(self, key: str = "", ver: str = "") -> None:
        self.agent_api_key = key
        self.agent_version = ver


def test_has_agent_monitoring():
    assert has_agent_monitoring(_Srv("nxs-x", "")) is True
    assert has_agent_monitoring(_Srv("", "2.0.0")) is True
    assert has_agent_monitoring(_Srv("", "")) is False


def test_central_status():
    hb = {"is_online": "True", "last_heartbeat": "2026-06-09T01:00:00+00:00"}
    assert central_status(True, hb) == "online"
    hb["is_online"] = "False"
    assert central_status(True, hb) == "offline"
    assert central_status(True, None) == "offline"
    assert central_status(False, None) == "unknown"


def test_parse_remote_probe():
    stdout = """
### systemctl ###
active
active running Mon 2026-06-08 16:50:46 CST
### config_redacted ###
{"api_key": "nxs-abcd..."}
### log_errors ###
--- /var/log/nexus-agent.log ---
401 Unauthorized
### central_health ###
http_code=200
""".strip()
    parsed = parse_remote_probe(stdout)
    assert parsed["systemctl_active"] == "active"
    assert parsed["config"]["api_key"] == "nxs-abcd..."
    assert "401" in parsed["log_errors"]
    assert parsed["central_health_http_code"] == 200


def test_build_diagnose_errors_offline():
    row = {
        "has_agent": True,
        "central_status": "offline",
        "remote": {"ssh_ok": True, "systemctl_active": "active", "log_errors": "(no matching lines)"},
    }
    errors = build_diagnose_errors(row)
    assert any("离线" in e for e in errors)


def test_build_diagnose_errors_401_log():
    row = {
        "has_agent": True,
        "central_status": "online",
        "remote": {
            "ssh_ok": True,
            "systemctl_active": "active",
            "log_errors": "401 Heartbeat rejected",
            "central_health_http_code": 200,
        },
    }
    errors = build_diagnose_errors(row)
    assert any("401" in e for e in errors)
