from onefirewall_ai.agent import tools


def test_run_bash_treats_trailing_ampersand_as_background(monkeypatch):
    captured = {}

    def fake_popen(command, **kwargs):
        captured["command"] = command
        captured["kwargs"] = kwargs

        class DummyProcess:
            pass

        return DummyProcess()

    monkeypatch.setattr(tools.subprocess, "Popen", fake_popen)
    monkeypatch.setattr(
        tools.subprocess,
        "run",
        lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("subprocess.run should not be used")),
    )

    result = tools.run_bash("cd D:\\repo && npm run dev &", cwd="D:\\repo")

    assert "background" in result.lower()
    assert captured["command"] == "cd D:\\repo && npm run dev"


def test_normalize_background_command_preserves_sequential_and_operator():
    command, background = tools._normalize_background_command(
        "cd D:\\repo && npm run dev &",
        False,
    )

    assert background is True
    assert command == "cd D:\\repo && npm run dev"


def test_execute_tool_passes_run_in_background_to_run_bash(monkeypatch):
    captured = {}

    def fake_run_bash(command, timeout=120, cwd=None, run_in_background=False):
        captured["command"] = command
        captured["timeout"] = timeout
        captured["cwd"] = cwd
        captured["run_in_background"] = run_in_background
        return "ok"

    monkeypatch.setattr(tools, "run_bash", fake_run_bash)
    monkeypatch.setattr(tools, "_ask_permission", lambda _name, _display: True)

    result = tools.execute_tool(
        "bash",
        {
            "command": "npm run dev",
            "cwd": "D:\\repo",
            "timeout": 45,
            "run_in_background": True,
        },
    )

    assert result == "ok"
    assert captured == {
        "command": "npm run dev",
        "timeout": 45,
        "cwd": "D:\\repo",
        "run_in_background": True,
    }


def test_run_bash_blocks_duplicate_background_launches(monkeypatch):
    launches: list[str] = []

    def fake_popen(command, **kwargs):
        launches.append(command)

        class DummyProcess:
            pass

        return DummyProcess()

    monkeypatch.setattr(tools.subprocess, "Popen", fake_popen)
    monkeypatch.setattr(tools.time, "monotonic", lambda: 100.0)
    tools.reset_session_permissions()

    first = tools.run_bash("npm run dev", cwd="D:\\repo", run_in_background=True)
    second = tools.run_bash("npm run dev", cwd="D:\\repo", run_in_background=True)

    assert "background" in first.lower()
    assert second.startswith("[ERROR] Similar background command was already started recently.")
    assert launches == ["npm run dev"]
