import json

from api.services.tool_executor import ToolExecutor


def test_grep_skips_venv_and_node_modules_by_default(tmp_path):
    (tmp_path / "src").mkdir()
    (tmp_path / "venv").mkdir()
    (tmp_path / "node_modules").mkdir()

    (tmp_path / "src" / "a.txt").write_text("hello NEEDLE world", encoding="utf-8")
    (tmp_path / "venv" / "b.txt").write_text("hello NEEDLE from venv", encoding="utf-8")
    (tmp_path / "node_modules" / "c.txt").write_text("hello NEEDLE from node_modules", encoding="utf-8")

    te = ToolExecutor(workspace_root=str(tmp_path))
    out = te.execute_tool("Grep", {"pattern": "NEEDLE", "path": "."})
    assert isinstance(out, dict)
    matches = out.get("matches") or []
    paths = sorted({m.get("path") for m in matches if isinstance(m, dict)})
    assert paths == ["src/a.txt"]


def test_glob_skips_venv_and_node_modules_by_default(tmp_path):
    (tmp_path / "src").mkdir()
    (tmp_path / "venv").mkdir()
    (tmp_path / "node_modules").mkdir()

    (tmp_path / "src" / "a.py").write_text("print('ok')", encoding="utf-8")
    (tmp_path / "venv" / "b.py").write_text("print('no')", encoding="utf-8")
    (tmp_path / "node_modules" / "c.py").write_text("print('no')", encoding="utf-8")

    te = ToolExecutor(workspace_root=str(tmp_path))
    out = te.execute_tool("Glob", {"pattern": "**/*.py"})
    assert out == ["src/a.py"]


def test_include_ignored_allows_searching_venv(tmp_path):
    (tmp_path / "venv").mkdir()
    (tmp_path / "venv" / "x.txt").write_text("NEEDLE", encoding="utf-8")

    te = ToolExecutor(workspace_root=str(tmp_path))
    out = te.execute_tool("Grep", {"pattern": "NEEDLE", "path": ".", "include_ignored": True})
    matches = out.get("matches") or []
    assert any((m.get("path") == "venv/x.txt") for m in matches if isinstance(m, dict))

