"""Helper script for Robot Framework skill file ops 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.file_ops import register_skill_file_tools
from cleveragents.tool.registry import ToolRegistry
from cleveragents.tool.runner import ToolRunner


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


def test_read() -> None:
    sandbox = tempfile.mkdtemp()
    try:
        (Path(sandbox) / "test.txt").write_text("hello skill robot")
        runner = _make_runner(sandbox)
        result = runner.execute(
            "skill/file-read",
            {"path": "test.txt", "sandbox_root": sandbox},
        )
        assert result.success, f"Failed: {result.error}"
        assert result.output["content"] == "hello skill robot"
        print("skill-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(
            "skill/file-write",
            {"path": "new.txt", "content": "atomic write", "sandbox_root": sandbox},
        )
        assert result.success, f"Failed: {result.error}"
        assert result.output["created"] is True
        assert (Path(sandbox) / "new.txt").read_text() == "atomic write"
        print("skill-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(
            "skill/file-edit",
            {
                "path": "edit.txt",
                "old_text": "foo",
                "new_text": "baz",
                "sandbox_root": sandbox,
            },
        )
        assert result.success, f"Failed: {result.error}"
        assert result.output["replacements"] == 1
        print("skill-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(
            "skill/file-delete",
            {"path": "bye.txt", "sandbox_root": sandbox},
        )
        assert result.success, f"Failed: {result.error}"
        assert result.output["existed"] is True
        assert not (Path(sandbox) / "bye.txt").exists()
        print("skill-file-delete-ok")
    finally:
        shutil.rmtree(sandbox, ignore_errors=True)


def test_binary() -> None:
    sandbox = tempfile.mkdtemp()
    try:
        (Path(sandbox) / "image.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 100)
        runner = _make_runner(sandbox)
        result = runner.execute(
            "skill/file-read",
            {"path": "image.png", "sandbox_root": sandbox},
        )
        assert not result.success
        assert "binary" in (result.error or "").lower()
        print("skill-binary-ok")
    finally:
        shutil.rmtree(sandbox, ignore_errors=True)


def test_traversal() -> None:
    sandbox = tempfile.mkdtemp()
    try:
        runner = _make_runner(sandbox)
        result = runner.execute(
            "skill/file-read",
            {"path": "../../etc/passwd", "sandbox_root": sandbox},
        )
        assert not result.success
        assert "traversal" in (result.error or "").lower()
        print("skill-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,
        "binary": test_binary,
        "traversal": test_traversal,
    }
    fn = dispatch.get(cmd)
    if fn:
        fn()
    else:
        print(f"Unknown command: {cmd}", file=sys.stderr)
        sys.exit(1)
