"""
Action registry — loads from protocol/actions.json for translator and llm_parser.
Same source as Hub actionRegistry; protocol/actions.json is the single config.
"""
from __future__ import annotations

import json
from pathlib import Path

# In monorepo: gateway/agentworld_gateway/action_registry.py -> repo root = parents[2]
_REPO_ROOT = Path(__file__).resolve().parents[2]
_PROTOCOL_ACTIONS = _REPO_ROOT / "protocol" / "actions.json"

# Fallback when protocol/actions.json is missing (keep in sync with protocol/actions.json)
_FALLBACK_ACTIONS = [
    {"type": "move", "descriptionForLLM": "move to coords [x, z]", "parametersHint": "[x, z]"},
    {"type": "run", "descriptionForLLM": "faster move to [x, z]", "parametersHint": "[x, z]"},
    {"type": "attack", "descriptionForLLM": "attack target id (if combat allowed)", "parametersHint": "target_agent_id"},
    {"type": "speak", "descriptionForLLM": "say something (visible to others)", "parametersHint": "string"},
    {"type": "think", "descriptionForLLM": "think in internal_monologue only", "parametersHint": "string"},
    {"type": "idle", "descriptionForLLM": "wait/idle briefly", "parametersHint": None},
    {"type": "help", "descriptionForLLM": "ask or answer: { mode: ask|answer, content, help_id?, to? }", "parametersHint": "HelpParameters"},
    {"type": "eat", "descriptionForLLM": "start eating for a few seconds (no params)", "parametersHint": None},
    {"type": "cook", "descriptionForLLM": "start cooking for a few seconds (no params)", "parametersHint": None},
]


def _load_actions() -> list[dict]:
    if _PROTOCOL_ACTIONS.exists():
        try:
            with open(_PROTOCOL_ACTIONS, "r", encoding="utf-8") as f:
                data = json.load(f)
            actions = data.get("actions")
            if isinstance(actions, list):
                return actions
        except Exception:
            pass
    return _FALLBACK_ACTIONS


_ACTIONS: list[dict] | None = None


def get_actions() -> list[dict]:
    global _ACTIONS
    if _ACTIONS is None:
        _ACTIONS = _load_actions()
    return _ACTIONS


def get_description_map() -> dict[str, str]:
    """Return type -> descriptionForLLM for use in translator."""
    return {a["type"]: a.get("descriptionForLLM", "") or "" for a in get_actions()}


def get_allowed_action_types() -> tuple[str, ...]:
    """Return tuple of allowed action types for llm_parser."""
    return tuple(a["type"] for a in get_actions())
