"""The action vocabulary the model may use, and strict parsing of its JSON output."""

from __future__ import annotations

import json
import re
from dataclasses import dataclass, field
from typing import Any, Dict

ACTION_SPECS: Dict[str, Dict[str, type]] = {
    "goto": {"url": str},
    "click": {"index": int},
    "type": {"index": int, "text": str},
    "select": {"index": int, "option": str},
    "scroll": {"direction": str},
    "back": {},
    "wait": {"seconds": (int, float)},
    "extract": {"what": str},
    "ask_human": {"question": str},
    "done": {"answer": str},
}


class ActionError(ValueError):
    pass


@dataclass
class Action:
    name: str
    args: Dict[str, Any] = field(default_factory=dict)
    thought: str = ""

    def __str__(self) -> str:
        a = ", ".join(f"{k}={v!r}" for k, v in self.args.items())
        return f"{self.name}({a})"


_FENCE = re.compile(r"^```(?:json)?\s*|\s*```$", re.MULTILINE)


def parse_action(raw: str) -> Action:
    """Parse {"thought": "...", "action": "click", "args": {"index": 3}}.

    Tolerates a Markdown code fence around the JSON, nothing else.
    """
    text = _FENCE.sub("", raw.strip())
    try:
        obj = json.loads(text)
    except json.JSONDecodeError as e:
        raise ActionError(f"not valid JSON: {e.msg}") from None
    if not isinstance(obj, dict):
        raise ActionError("expected a JSON object")
    name = obj.get("action")
    if name not in ACTION_SPECS:
        raise ActionError(f"unknown action {name!r}; allowed: {sorted(ACTION_SPECS)}")
    args = obj.get("args") or {}
    if not isinstance(args, dict):
        raise ActionError("args must be an object")
    spec = ACTION_SPECS[name]
    for key, typ in spec.items():
        if key not in args:
            raise ActionError(f"{name} requires {key!r}")
        if isinstance(args[key], bool) or not isinstance(args[key], typ):
            raise ActionError(f"{name}.{key} has wrong type")
    extra = set(args) - set(spec)
    if extra:
        raise ActionError(f"unexpected args for {name}: {sorted(extra)}")
    if name == "scroll" and args["direction"] not in ("up", "down"):
        raise ActionError("scroll.direction must be 'up' or 'down'")
    return Action(name, args, str(obj.get("thought", ""))[:500])
