from __future__ import annotations

from pathlib import Path
from unittest.mock import patch

from jarvis_finance.services.system_ops import restart_system_component


def _make_repo(tmp_path: Path) -> Path:
    repo = tmp_path / "repo"
    scripts = repo / "scripts"
    scripts.mkdir(parents=True)
    for name in ["restart_backend.sh", "restart_frontend.sh", "restart_dashboard.sh"]:
        path = scripts / name
        path.write_text("#!/usr/bin/env bash\necho ok\n", encoding="utf-8")
        path.chmod(0o755)
    return repo


def test_restart_backend_is_detached_so_http_response_can_return(tmp_path):
    repo = _make_repo(tmp_path)
    runtime = tmp_path / "runtime"
    runtime.mkdir()
    popen_calls = []

    class DummyPopen:
        def __init__(self, *args, **kwargs):
            popen_calls.append((args, kwargs))
            self.pid = 12345

    with patch("jarvis_finance.services.system_ops.subprocess.Popen", DummyPopen), patch("jarvis_finance.services.system_ops.subprocess.run") as run_mock:
        result = restart_system_component("backend", runtime_dir=runtime, repo_root=repo)

    assert result["status"] == "scheduled"
    assert result["message"].startswith("Backend-Restart")
    assert popen_calls
    assert "sleep 1" in popen_calls[0][0][0][3]
    run_mock.assert_not_called()


def test_restart_dashboard_writes_restart_worker_log(tmp_path):
    repo = _make_repo(tmp_path)
    runtime = tmp_path / "runtime"
    runtime.mkdir()

    class DummyPopen:
        def __init__(self, *args, **kwargs):
            self.args = args
            self.kwargs = kwargs
            self.pid = 67890

    with patch("jarvis_finance.services.system_ops.subprocess.Popen", DummyPopen):
        result = restart_system_component("dashboard", runtime_dir=runtime, repo_root=repo)

    assert result["status"] == "scheduled"
    assert result["worker_pid"] == 67890
    assert (runtime / "logs" / "restart_dashboard.log").parent.exists()
    assert "worker_pid" in (runtime / "logs" / "ops_actions.jsonl").read_text(encoding="utf-8")
