# retoor <retoor@molodetz.nl>

from __future__ import annotations

import json
import logging
from typing import Any

from devplacepy.services.devii.errors import ToolInputError

logger = logging.getLogger("devii.behavior")


class BehaviorController:
    def __init__(self, store: Any) -> None:
        self._store = store

    async def dispatch(self, name: str, arguments: dict[str, Any]) -> str:
        if name == "update_behavior":
            return self._update(arguments)
        raise ToolInputError(f"Unknown behavior tool: {name}")

    def _update(self, arguments: dict[str, Any]) -> str:
        behavior = arguments.get("behavior")
        if behavior is None:
            raise ToolInputError("'behavior' is required.")
        self._store.set(str(behavior))
        return json.dumps(
            {
                "status": "success",
                "saved": True,
                "note": "Updated your '# TRUTH RULES AND BEHAVIOR' section; it applies from your next turn.",
            },
            ensure_ascii=False,
        )
