"""Tool call validation against JSON Schema."""

from __future__ import annotations

import copy
import json
from typing import Any

import jsonschema

from pi_agents.ai.types import Tool, ToolCall


def validate_tool_call(tools: list[Tool], tool_call: ToolCall) -> Any:
    """Find the matching tool and validate the tool call arguments.

    Raises:
        ValueError: If tool not found or validation fails.
    """
    tool = next((t for t in tools if t.name == tool_call.name), None)
    if not tool:
        raise ValueError(f'Tool "{tool_call.name}" not found')
    return validate_tool_arguments(tool, tool_call)


def validate_tool_arguments(tool: Tool, tool_call: ToolCall) -> Any:
    """Validate tool call arguments against the tool's JSON Schema.

    Raises:
        ValueError: If validation fails.
    """
    args = copy.deepcopy(tool_call.arguments)

    try:
        jsonschema.validate(instance=args, schema=tool.parameters)
    except jsonschema.ValidationError as e:
        path = ".".join(str(p) for p in e.absolute_path) if e.absolute_path else "root"
        error_msg = f'Validation failed for tool "{tool_call.name}":\n  - {path}: {e.message}'
        error_msg += f"\n\nReceived arguments:\n{json.dumps(tool_call.arguments, indent=2)}"
        raise ValueError(error_msg) from e

    return args
