"""Helper script for Robot Framework built-in file 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.tool.builtins import register_file_tools
from cleveragents.tool.registry import ToolRegistry
from cleveragents.tool.runner import ToolRunner


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


def test_read() -> None:
    sandbox = tempfile.mkdtemp()
    try:
        (Path(sandbox) / "test.txt").write_text("hello robot")
        runner = _make_runner(sandbox)
        result = runner.execute(
            "builtin/file-read",
            {"path": "test.txt", "sandbox_root": sandbox},
        )
        assert result.success
        assert result.output["content"] == "hello robot"
        print("file-read-ok")
    finally:
        shutil.rmtree(sandbox, ignore_errors=True)


def test_write() -> None:
    sandbox = tempfile.mkdtemp()
    try:
        runner = _make_runner(sandbox)
        result = runner.execute(
            "builtin/file-write",
            {"path": "new.txt", "content": "written", "sandbox_root": sandbox},
        )
        assert result.success
        assert result.output["created"] is True
        assert (Path(sandbox) / "new.txt").read_text() == "written"
        print("file-write-ok")
    finally:
        shutil.rmtree(sandbox, ignore_errors=True)


def test_edit() -> None:
    sandbox = tempfile.mkdtemp()
    try:
        (Path(sandbox) / "edit.txt").write_text("foo bar foo")
        runner = _make_runner(sandbox)
        result = runner.execute(
            "builtin/file-edit",
            {
                "path": "edit.txt",
                "old_text": "foo",
                "new_text": "baz",
                "sandbox_root": sandbox,
            },
        )
        assert result.success
        assert result.output["replacements"] == 1
        print("file-edit-ok")
    finally:
        shutil.rmtree(sandbox, ignore_errors=True)


def test_delete() -> None:
    sandbox = tempfile.mkdtemp()
    try:
        (Path(sandbox) / "bye.txt").write_text("gone")
        runner = _make_runner(sandbox)
        result = runner.execute(
            "builtin/file-delete",
            {"path": "bye.txt", "sandbox_root": sandbox},
        )
        assert result.success
        assert result.output["existed"] is True
        assert not (Path(sandbox) / "bye.txt").exists()
        print("file-delete-ok")
    finally:
        shutil.rmtree(sandbox, ignore_errors=True)


def test_list() -> 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(
            "builtin/file-list",
            {"path": ".", "sandbox_root": sandbox},
        )
        assert result.success
        assert len(result.output["files"]) >= 2
        print("file-list-ok")
    finally:
        shutil.rmtree(sandbox, ignore_errors=True)


def test_search() -> None:
    sandbox = tempfile.mkdtemp()
    try:
        (Path(sandbox) / "data.txt").write_text("needle in haystack\n")
        runner = _make_runner(sandbox)
        result = runner.execute(
            "builtin/file-search",
            {"path": ".", "pattern": "needle", "sandbox_root": sandbox},
        )
        assert result.success
        assert len(result.output["matches"]) >= 1
        print("file-search-ok")
    finally:
        shutil.rmtree(sandbox, ignore_errors=True)


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


if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else "read"
    dispatch: dict[str, Any] = {
        "read": test_read,
        "write": test_write,
        "edit": test_edit,
        "delete": test_delete,
        "list": test_list,
        "search": test_search,
        "traversal": test_traversal,
    }
    fn = dispatch.get(cmd)
    if fn:
        fn()
    else:
        print(f"Unknown command: {cmd}", file=sys.stderr)
        sys.exit(1)
