from __future__ import annotations
from typing import Optional, Set

from ..core.agent import BaseAgent
from ..core.decorators import agent_role
from ..core.events import BusEvent
from ..tools.python_sandbox import PythonSandbox
from ..tools.container_sandbox import DockerPythonSandbox

@agent_role("tool_smith")
class ToolSmithAgent(BaseAgent):
    def topics(self) -> Optional[Set[str]]:
        return {"task.code", "task.refine"}

    def filter_event(self, event: BusEvent) -> bool:
        return event.topic in {"task.code", "task.refine"} and event.type in {"TASK", "RESULT"}

    async def handle(self, event: BusEvent) -> None:
        await self.emit_confidence(parent=event, score=0.75, rationale="tool_smith ready")

        use_container = bool(self.config.extra.get("tool_smith_container", False))
        code_example = """result = 2 + 2
"""

        if use_container:
            sandbox = DockerPythonSandbox()
            res = await sandbox.run(code_example)
            out = f"container_ok={res.ok} exit={res.exit_code} stdout={res.stdout!r} stderr={res.stderr!r}"
        else:
            sandbox = PythonSandbox()
            res = await sandbox.run(code_example)
            out = f"sandbox_ok={res.ok} result={res.result_repr} stderr={res.stderr!r}"

        draft = (
            "### Implementation Draft\n"
            "- Execute code in a sandbox (local or container)\n"
            f"- Sandbox smoke test: {out}\n"
            "- Add module `solution.py`\n"
            "- Add tests `test_solution.py`\n"
            "- Add docs + type hints\n"
        )
        await self.report(parent=event, topic="result.draft", text=draft, confidence=0.75)
