from unittest.mock import MagicMock, patch

from lib.instance.instance_pm2_lib import restart_instance_pm2, schedule_pm2_restart


@patch("lib.instance.instance_pm2_lib.sys.platform", "linux")
@patch("lib.instance.instance_pm2_lib.subprocess.Popen")
def test_schedule_pm2_restart_returns_before_pm2(mock_popen):
    result = schedule_pm2_restart("crypto_okx")

    assert result["ok"] is True
    assert result["deferred"] is True
    mock_popen.assert_called_once()


@patch("lib.instance.instance_pm2_lib.sys.platform", "linux")
@patch("lib.instance.instance_pm2_lib.schedule_pm2_restart")
def test_restart_instance_pm2_defer_uses_schedule(mock_schedule):
    mock_schedule.return_value = {"ok": True, "app": "crypto_okx", "deferred": True}

    result = restart_instance_pm2("okx", defer=True)

    mock_schedule.assert_called_once_with("crypto_okx")
    assert result["deferred"] is True


@patch("lib.instance.instance_pm2_lib.sys.platform", "linux")
@patch("lib.instance.instance_pm2_lib.subprocess.run")
def test_restart_instance_pm2_sync_runs_pm2(mock_run):
    mock_run.return_value = MagicMock(returncode=0, stdout="ok", stderr="")

    result = restart_instance_pm2("okx", defer=False)

    mock_run.assert_called_once()
    assert result["ok"] is True
