"""Tests for NodeAgent._ship_events_to_vps rsync command construction.

Covers the fix for the false "Event shipping failed" warning: the remote
per-node events dir on VPS is owned by aerbot:aerbot, so the ssh user (a
group member, not the owner) can write files into it but cannot touch the
dir's own mtime. -a implies -t (preserve times), which rsync also applies to
directories, so without --omit-dir-times rsync returns a non-zero exit code
on every run even though the file transfer itself succeeded.
"""
from __future__ import annotations

from unittest.mock import MagicMock

import node_agent


def test_omits_dir_times_flag(agent, monkeypatch):
    captured = {}

    def fake_run(cmd, **kwargs):
        captured["cmd"] = cmd
        return MagicMock(returncode=0, stderr="")

    monkeypatch.setattr(node_agent.subprocess, "run", fake_run)
    agent._ship_events_to_vps()

    assert "--omit-dir-times" in captured["cmd"]


def test_skips_when_vps_host_not_set(agent, monkeypatch):
    monkeypatch.setattr(node_agent, "VPS_EVENTS_HOST", "")
    fake_run = MagicMock()
    monkeypatch.setattr(node_agent.subprocess, "run", fake_run)

    agent._ship_events_to_vps()

    fake_run.assert_not_called()


def test_skips_on_vps_node(agent, monkeypatch):
    agent.node_name = node_agent.VPS_NODE_NAME
    fake_run = MagicMock()
    monkeypatch.setattr(node_agent.subprocess, "run", fake_run)

    agent._ship_events_to_vps()

    fake_run.assert_not_called()


def test_nonzero_returncode_logs_warning(agent, monkeypatch, caplog):
    def fake_run(cmd, **kwargs):
        return MagicMock(returncode=23, stderr="rsync: some partial transfer error")

    monkeypatch.setattr(node_agent.subprocess, "run", fake_run)

    with caplog.at_level("WARNING"):
        agent._ship_events_to_vps()

    assert "Event shipping failed" in caplog.text
