"""Pattern: memory as a tool the model controls.

The model decides what to save and read through file operations on a virtual
`/memories` directory. This handler implements the command set used by
Anthropic's client-side memory tool (view, create, str_replace, insert,
delete, rename) on a real directory, with strict path containment. It does not
call any API; plug `FileMemoryTool.handle(tool_input)` into your tool-use loop.
"""
from __future__ import annotations

import shutil
from pathlib import Path
from urllib.parse import unquote

VIRTUAL_ROOT = "/memories"
MAX_FILE_BYTES = 200_000


class MemoryPathError(ValueError):
    pass


def _human(n: int) -> str:
    for unit in ("", "K", "M", "G"):
        if n < 1024 or unit == "G":
            return f"{n:.1f}{unit}" if unit else f"{n}"
        n /= 1024
    return str(n)


class FileMemoryTool:
    def __init__(self, base_dir: str | Path, max_file_bytes: int = MAX_FILE_BYTES):
        self.base = Path(base_dir).resolve()
        self.base.mkdir(parents=True, exist_ok=True)
        self.max_file_bytes = max_file_bytes

    # -- path safety -----------------------------------------------------
    def resolve(self, virtual: str) -> Path:
        if not isinstance(virtual, str) or not virtual:
            raise MemoryPathError("path is required")
        decoded = unquote(virtual).replace("\\", "/")
        if decoded != VIRTUAL_ROOT and not decoded.startswith(VIRTUAL_ROOT + "/"):
            raise MemoryPathError(f"path must be inside {VIRTUAL_ROOT}: {virtual}")
        parts = [p for p in decoded[len(VIRTUAL_ROOT):].split("/") if p]
        if any(p in ("..", ".") for p in parts):
            raise MemoryPathError(f"path traversal is not allowed: {virtual}")
        real = self.base.joinpath(*parts).resolve()
        if real != self.base and self.base not in real.parents:
            raise MemoryPathError(f"path escapes the memory directory: {virtual}")
        return real

    def _virtual(self, real: Path) -> str:
        rel = real.relative_to(self.base).as_posix()
        return VIRTUAL_ROOT if rel == "." else f"{VIRTUAL_ROOT}/{rel}"

    # -- dispatcher ------------------------------------------------------
    def handle(self, tool_input: dict) -> tuple[str, bool]:
        """Run one command. Returns (text for tool_result, is_error)."""
        command = tool_input.get("command")
        try:
            method = getattr(self, f"cmd_{command}", None)
            if method is None:
                return f"Error: unknown command {command}", True
            return method(tool_input), False
        except MemoryPathError as exc:
            return f"Error: {exc}", True
        except _ToolError as exc:
            return str(exc), True

    # -- commands --------------------------------------------------------
    def cmd_view(self, inp: dict) -> str:
        path = self.resolve(inp.get("path", ""))
        vpath = inp.get("path")
        if path.is_dir():
            lines = [f"{_human(self._size(path))}\t{self._virtual(path)}"]
            for child in sorted(self._walk(path, depth=2)):
                lines.append(f"{_human(self._size(child))}\t{self._virtual(child)}")
            return (f"Here're the files and directories up to 2 levels deep in {vpath}, "
                    "excluding hidden items and node_modules:\n" + "\n".join(lines))
        if not path.is_file():
            raise _ToolError(f"The path {vpath} does not exist. Please provide a valid path.")
        text_lines = path.read_text(encoding="utf-8").splitlines() or [""]
        start, end = 1, len(text_lines)
        rng = inp.get("view_range")
        if rng:
            start = max(1, int(rng[0]))
            end = len(text_lines) if int(rng[1]) == -1 else min(len(text_lines), int(rng[1]))
        body = "\n".join(f"{i:6d}\t{text_lines[i - 1]}" for i in range(start, end + 1))
        return f"Here's the content of {vpath} with line numbers:\n{body}"

    def cmd_create(self, inp: dict) -> str:
        path = self.resolve(inp.get("path", ""))
        if path == self.base:
            raise _ToolError("Error: cannot create the memory root")
        text = inp.get("file_text", "")
        self._check_size(text)
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(text, encoding="utf-8")  # overwrite is allowed
        return f"File created successfully at: {inp['path']}"

    def cmd_str_replace(self, inp: dict) -> str:
        path = self.resolve(inp.get("path", ""))
        vpath = inp["path"]
        if not path.is_file():
            raise _ToolError(f"Error: The path {vpath} does not exist. Please provide a valid path.")
        old, new = inp.get("old_str", ""), inp.get("new_str", "")
        text = path.read_text(encoding="utf-8")
        count = text.count(old) if old else 0
        if count == 0:
            raise _ToolError(f"No replacement was performed, old_str `{old}` did not appear verbatim in {vpath}.")
        if count > 1:
            lines = [str(i + 1) for i, line in enumerate(text.splitlines()) if old in line]
            raise _ToolError(f"No replacement was performed. Multiple occurrences of old_str `{old}` "
                             f"in lines: {', '.join(lines)}. Please ensure it is unique")
        updated = text.replace(old, new, 1)
        self._check_size(updated)
        path.write_text(updated, encoding="utf-8")
        return "The memory file has been edited."

    def cmd_insert(self, inp: dict) -> str:
        path = self.resolve(inp.get("path", ""))
        vpath = inp["path"]
        if not path.is_file():
            raise _ToolError(f"Error: The path {vpath} does not exist")
        lines = path.read_text(encoding="utf-8").split("\n")
        at = int(inp.get("insert_line", -1))
        if at < 0 or at > len(lines):
            raise _ToolError(f"Error: Invalid `insert_line` parameter: {at}. "
                             f"It should be within the range of lines of the file: [0, {len(lines)}]")
        lines.insert(at, str(inp.get("insert_text", "")).rstrip("\n"))
        updated = "\n".join(lines)
        self._check_size(updated)
        path.write_text(updated, encoding="utf-8")
        return f"The file {vpath} has been edited."

    def cmd_delete(self, inp: dict) -> str:
        path = self.resolve(inp.get("path", ""))
        vpath = inp["path"]
        if path == self.base:
            raise _ToolError("Error: cannot delete the memory root")
        if path.is_dir():
            shutil.rmtree(path)
        elif path.is_file():
            path.unlink()
        else:
            raise _ToolError(f"Error: The path {vpath} does not exist")
        return f"Successfully deleted {vpath}"

    def cmd_rename(self, inp: dict) -> str:
        src = self.resolve(inp.get("old_path", ""))
        dst = self.resolve(inp.get("new_path", ""))
        if src == self.base:
            raise _ToolError("Error: cannot rename the memory root")
        if not src.exists():
            raise _ToolError(f"Error: The path {inp['old_path']} does not exist")
        if dst.exists():
            raise _ToolError(f"Error: The destination {inp['new_path']} already exists")
        dst.parent.mkdir(parents=True, exist_ok=True)
        src.rename(dst)
        return f"Successfully renamed {inp['old_path']} to {inp['new_path']}"

    # -- helpers ---------------------------------------------------------
    def _check_size(self, text: str) -> None:
        if len(text.encode("utf-8")) > self.max_file_bytes:
            raise _ToolError(f"Error: memory files are limited to {self.max_file_bytes} bytes")

    @staticmethod
    def _walk(root: Path, depth: int):
        for child in root.iterdir():
            if child.name.startswith(".") or child.name == "node_modules":
                continue
            yield child
            if child.is_dir() and depth > 1:
                yield from FileMemoryTool._walk(child, depth - 1)

    @staticmethod
    def _size(p: Path) -> int:
        if p.is_file():
            return p.stat().st_size
        return sum(f.stat().st_size for f in p.rglob("*") if f.is_file())


class _ToolError(Exception):
    pass
