"""
cortex/hippo/tools/common.py — Shared tool utilities.

Port of tools/common.ts from lossless-claw.
Issues: #1118, #1120
"""

from __future__ import annotations

import json
from typing import Any, Optional


def json_result(payload: Any) -> dict[str, Any]:
    """Render structured payloads as deterministic text tool results."""
    return {
        "content": [
            {
                "type": "text",
                "text": json.dumps(payload, indent=2, default=str),
            },
        ],
        "details": payload,
    }


def read_string_param(
    params: dict[str, Any],
    key: str,
    *,
    required: bool = False,
    trim: bool = True,
    allow_empty: bool = False,
    label: Optional[str] = None,
) -> Optional[str]:
    """Read a string param with optional trimming/required checks.

    Returns the cleaned string value, or None if absent/empty.
    Raises ValueError on validation failures.
    """
    display = label or key
    raw = params.get(key)

    if raw is None:
        if required:
            raise ValueError(f"{display} is required.")
        return None

    if not isinstance(raw, str):
        raise ValueError(f"{display} must be a string.")

    value = raw.strip() if trim else raw

    if not allow_empty and len(value) == 0:
        if required:
            raise ValueError(f"{display} is required.")
        return None

    return value
