"""Hermes Digital Pet plugin registration."""
from __future__ import annotations

import logging
from pathlib import Path

from .commands import handle_pet_command
from .state import apply_event

_LOG = logging.getLogger(__name__)


def _on_session_start(session_id=None, model=None, platform=None, **kwargs):
    try:
        apply_event("session_started", persist=True)
    except Exception as exc:
        _LOG.debug("digital-pet session hook ignored failure: %s", exc)


def _on_post_tool_call(tool_name=None, args=None, result=None, task_id=None, duration_ms=None, **kwargs):
    try:
        failed = False
        if isinstance(result, dict):
            failed = bool(result.get("error") or result.get("success") is False)
        elif isinstance(result, str):
            failed = '"error"' in result.lower() or "traceback" in result.lower()
        apply_event(
            "tool_call_failed" if failed else "tool_call_succeeded",
            metadata={"tool_name": tool_name or "unknown"},
            persist=True,
        )
    except Exception as exc:
        _LOG.debug("digital-pet tool hook ignored failure: %s", exc)


def register(ctx):
    """Register the digital pet plugin with Hermes."""
    ctx.register_command(
        "pet",
        handle_pet_command,
        description="Summon, hide, wake, sleep, or inspect the Hermes digital pet.",
        args_hint="[summon|hide|wake|sleep|status|click]",
    )
    ctx.register_hook("on_session_start", _on_session_start)
    ctx.register_hook("post_tool_call", _on_post_tool_call)

    skills_dir = Path(__file__).parent / "skills"
    if skills_dir.is_dir():
        for child in sorted(skills_dir.iterdir()):
            skill_md = child / "SKILL.md"
            if child.is_dir() and skill_md.exists():
                ctx.register_skill(child.name, skill_md)
