from __future__ import annotations

import json

from digital_pet_import import load_module


def test_register_adds_pet_command_and_observer_hooks():
    plugin = load_module("__init__.py", "digital_pet_pkg", package=True)

    class Ctx:
        def __init__(self):
            self.commands = []
            self.hooks = []
            self.skills = []

        def register_command(self, *args, **kwargs):
            self.commands.append((args, kwargs))

        def register_hook(self, *args, **kwargs):
            self.hooks.append((args, kwargs))

        def register_skill(self, *args, **kwargs):
            self.skills.append((args, kwargs))

    ctx = Ctx()
    plugin.register(ctx)

    assert ctx.commands[0][0][0] == "pet"
    assert ctx.commands[0][1]["description"].startswith("Summon")
    assert ctx.commands[0][1]["args_hint"] == "[summon|hide|wake|sleep|status|click]"
    assert [entry[0][0] for entry in ctx.hooks] == ["on_session_start", "post_tool_call"]


def test_pet_command_status_and_unknown_do_not_throw(monkeypatch, tmp_path):
    monkeypatch.setenv("HERMES_DIGITAL_PET_STATE", str(tmp_path / "state.json"))
    commands = load_module("commands.py", "digital_pet_pkg", package=True)

    status = json.loads(commands.handle_pet_command("status"))
    unknown = json.loads(commands.handle_pet_command("nonsense"))

    assert status["ok"] is True
    assert status["state"]["mode"] == "hidden"
    assert unknown == {
        "ok": False,
        "error": "unknown pet command",
        "usage": "/pet [summon|hide|wake|sleep|status|click]",
    }


def test_pet_command_persists_summon_and_hide(monkeypatch, tmp_path):
    monkeypatch.setenv("HERMES_DIGITAL_PET_STATE", str(tmp_path / "state.json"))
    commands = load_module("commands.py", "digital_pet_pkg", package=True)

    summoned = json.loads(commands.handle_pet_command("summon"))
    hidden = json.loads(commands.handle_pet_command("hide"))

    assert summoned["ok"] is True
    assert summoned["state"]["mode"] == "idle"
    assert hidden["ok"] is True
    assert hidden["state"]["mode"] == "hidden"
    assert (tmp_path / "state.json").exists()
