from __future__ import annotations

import json
from typing import Any, TypedDict

JsonValue = str | int | float | bool | None | list["JsonValue"] | dict[str, "JsonValue"]
JsonObject = dict[str, JsonValue]


class ToolArgsSummary(TypedDict):
    length: int
    parse_ok: bool
    head: str
    tail: str


def parse_tool_arguments_with_status(arg_str: str) -> tuple[JsonObject, bool]:
    text = (arg_str or "").strip()
    if not text:
        return {}, True
    try:
        parsed = json.loads(text)
        if isinstance(parsed, dict):
            return parsed, True
        return {}, False
    except Exception:
        return {}, False


def parse_tool_arguments(arg_str: str) -> JsonObject:
    parsed, _ = parse_tool_arguments_with_status(arg_str)
    return parsed


def summarize_tool_arguments(arg_str: str, preview_chars: int = 120) -> ToolArgsSummary:
    text = str(arg_str or "")
    _, parse_ok = parse_tool_arguments_with_status(text)
    head = text[:preview_chars]
    tail = text[-preview_chars:] if len(text) > preview_chars else ""
    return {"length": len(text), "parse_ok": parse_ok, "head": head, "tail": tail}

