"""Helper script for Robot Framework skill search tools smoke tests."""

from __future__ import annotations

import shutil
import sys
import tempfile
from pathlib import Path
from typing import Any

# Ensure src is importable when run from workspace root
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))

from cleveragents.skills.builtins.search_ops import register_skill_search_tools
from cleveragents.tool.registry import ToolRegistry
from cleveragents.tool.runner import ToolRunner


def _make_runner(sandbox: str) -> ToolRunner:
    registry = ToolRegistry()
    register_skill_search_tools(registry)
    return ToolRunner(registry)


def test_listdir() -> None:
    sandbox = tempfile.mkdtemp()
    try:
        (Path(sandbox) / "a.txt").write_text("a")
        (Path(sandbox) / "b.txt").write_text("b")
        runner = _make_runner(sandbox)
        result = runner.execute(
            "skill/list-dir",
            {"path": ".", "sandbox_root": sandbox},
        )
        assert result.success, f"Failed: {result.error}"
        assert result.output["total"] >= 2
        print("skill-listdir-ok")
    finally:
        shutil.rmtree(sandbox, ignore_errors=True)


def test_glob() -> None:
    sandbox = tempfile.mkdtemp()
    try:
        (Path(sandbox) / "main.py").write_text("code")
        (Path(sandbox) / "test.py").write_text("test")
        (Path(sandbox) / "readme.md").write_text("docs")
        runner = _make_runner(sandbox)
        result = runner.execute(
            "skill/glob",
            {"path": ".", "pattern": "*.py", "sandbox_root": sandbox},
        )
        assert result.success, f"Failed: {result.error}"
        assert result.output["total"] == 2
        print("skill-glob-ok")
    finally:
        shutil.rmtree(sandbox, ignore_errors=True)


def test_grep() -> None:
    sandbox = tempfile.mkdtemp()
    try:
        (Path(sandbox) / "data.txt").write_text("needle in haystack\n")
        runner = _make_runner(sandbox)
        result = runner.execute(
            "skill/grep",
            {"path": ".", "pattern": "needle", "sandbox_root": sandbox},
        )
        assert result.success, f"Failed: {result.error}"
        assert result.output["total"] >= 1
        print("skill-grep-ok")
    finally:
        shutil.rmtree(sandbox, ignore_errors=True)


def test_traversal() -> None:
    sandbox = tempfile.mkdtemp()
    try:
        runner = _make_runner(sandbox)
        result = runner.execute(
            "skill/list-dir",
            {"path": "../../etc", "sandbox_root": sandbox},
        )
        assert not result.success
        assert "traversal" in (result.error or "").lower()
        print("skill-search-traversal-ok")
    finally:
        shutil.rmtree(sandbox, ignore_errors=True)


if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else "listdir"
    dispatch: dict[str, Any] = {
        "listdir": test_listdir,
        "glob": test_glob,
        "grep": test_grep,
        "traversal": test_traversal,
    }
    fn = dispatch.get(cmd)
    if fn:
        fn()
    else:
        print(f"Unknown command: {cmd}", file=sys.stderr)
        sys.exit(1)
