"""Minimal RFC 6902 JSON Patch (add/remove/replace/move/copy/test) for draft autosave (TZ I13)."""

from __future__ import annotations

import copy
from typing import Any


class PatchError(ValueError):
    pass


def _tokens(pointer: str) -> list[str]:
    if pointer == "":
        return []
    if not pointer.startswith("/"):
        raise PatchError(f"Invalid pointer {pointer!r}")
    return [t.replace("~1", "/").replace("~0", "~") for t in pointer[1:].split("/")]


def _walk(doc: Any, tokens: list[str]) -> Any:
    cur = doc
    for t in tokens:
        if isinstance(cur, list):
            try:
                cur = cur[int(t)]
            except (ValueError, IndexError) as exc:
                raise PatchError(f"Bad index {t!r}") from exc
        elif isinstance(cur, dict):
            if t not in cur:
                raise PatchError(f"Missing key {t!r}")
            cur = cur[t]
        else:
            raise PatchError("Cannot traverse a scalar")
    return cur


def _get(doc: Any, pointer: str) -> Any:
    return _walk(doc, _tokens(pointer))


def _add(doc: Any, pointer: str, value: Any) -> Any:
    tokens = _tokens(pointer)
    if not tokens:
        return value
    parent = _walk(doc, tokens[:-1])
    last = tokens[-1]
    if isinstance(parent, list):
        idx = len(parent) if last == "-" else int(last)
        if idx < 0 or idx > len(parent):
            raise PatchError("Index out of range")
        parent.insert(idx, value)
    elif isinstance(parent, dict):
        parent[last] = value
    else:
        raise PatchError("Cannot add to a scalar")
    return doc


def _remove(doc: Any, pointer: str) -> tuple[Any, Any]:
    tokens = _tokens(pointer)
    if not tokens:
        raise PatchError("Cannot remove the root")
    parent = _walk(doc, tokens[:-1])
    last = tokens[-1]
    try:
        if isinstance(parent, list):
            return doc, parent.pop(int(last))
        return doc, parent.pop(last)
    except (KeyError, IndexError, ValueError) as exc:
        raise PatchError(f"Nothing to remove at {pointer!r}") from exc


def apply_patch(document: Any, ops: list[dict[str, Any]]) -> Any:
    doc = copy.deepcopy(document)
    for op in ops:
        kind = op.get("op")
        path = op.get("path", "")
        if kind == "add":
            doc = _add(doc, path, copy.deepcopy(op.get("value")))
        elif kind == "remove":
            doc, _ = _remove(doc, path)
        elif kind == "replace":
            doc, _ = _remove(doc, path) if path else (doc, None)
            doc = _add(doc, path, copy.deepcopy(op.get("value")))
        elif kind == "move":
            doc, value = _remove(doc, op["from"])
            doc = _add(doc, path, value)
        elif kind == "copy":
            doc = _add(doc, path, copy.deepcopy(_get(doc, op["from"])))
        elif kind == "test":
            if _get(doc, path) != op.get("value"):
                raise PatchError(f"Test failed at {path!r}")
        else:
            raise PatchError(f"Unsupported op {kind!r}")
    return doc
