"""Helper script for Robot Framework tool runtime smoke tests."""

from __future__ import annotations

import sys
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.registry import ToolRegistry
from cleveragents.tool.runner import ToolRunner
from cleveragents.tool.runtime import ToolSpec


def _echo(inputs: dict[str, Any]) -> dict[str, Any]:
    return dict(inputs)


def _fail(inputs: dict[str, Any]) -> dict[str, Any]:
    raise RuntimeError("boom")


def test_register() -> None:
    registry = ToolRegistry()
    spec = ToolSpec(
        name="smoke/echo",
        description="Echo tool",
        handler=_echo,
    )
    registry.register(spec)
    found = registry.get("smoke/echo")
    assert found is not None
    assert found.name == "smoke/echo"
    print("registry-ok")


def test_lifecycle() -> None:
    registry = ToolRegistry()
    spec = ToolSpec(
        name="smoke/adder",
        description="Adder tool",
        handler=lambda inp: {"sum": inp.get("a", 0) + inp.get("b", 0)},
    )
    registry.register(spec)
    runner = ToolRunner(registry)
    discovered = runner.discover()
    assert len(discovered) == 1
    runner.activate("smoke/adder")
    result = runner.execute("smoke/adder", {"a": 1, "b": 2})
    assert result.success
    assert result.output["sum"] == 3
    runner.deactivate("smoke/adder")
    print("lifecycle-ok")


def test_error() -> None:
    registry = ToolRegistry()
    spec = ToolSpec(
        name="smoke/fail",
        description="Failing tool",
        handler=_fail,
    )
    registry.register(spec)
    runner = ToolRunner(registry)
    result = runner.execute("smoke/fail", {})
    assert not result.success
    assert result.error is not None
    assert "RuntimeError" in result.error
    print("error-ok")


if __name__ == "__main__":
    cmd = sys.argv[1] if len(sys.argv) > 1 else "register"
    if cmd == "register":
        test_register()
    elif cmd == "lifecycle":
        test_lifecycle()
    elif cmd == "error":
        test_error()
    else:
        print(f"Unknown command: {cmd}", file=sys.stderr)
        sys.exit(1)
