def pending_validation_ids(requests: list[dict], responses: list[dict]) -> set[str]:
    request_ids = {request.get("id") for request in requests if request.get("id")}
    response_ids = {
        response.get("validationRequestId") for response in responses if response.get("validationRequestId")
    }
    return request_ids - response_ids


def add_validation_response(requests: list[dict], responses: list[dict], response: dict) -> list[dict] | None:
    """Append a valid response, or return None when it was already recorded."""
    response_id = response.get("validationRequestId") if isinstance(response, dict) else None
    request_ids = {request.get("id") for request in requests if request.get("id")}
    if not response_id or response_id not in request_ids:
        raise ValueError("Invalid tool validation response")
    if any(item.get("validationRequestId") == response_id for item in responses):
        return None
    return [*responses, response]


def find_pending_validation_message(messages, message_id: str | None):
    """Return the latest message only when it has the requested pending validation."""
    if not messages:
        return None
    message = messages[-1]
    if message_id and message.id != message_id:
        return None
    requests = message.tool_validation_requests or []
    responses = message.tool_validation_responses or []
    return message if requests and pending_validation_ids(requests, responses) else None
