<?php

declare(strict_types=1);

namespace Drupal\flowdrop\DTO\Tool;

/**
 * Derives model-facing tool names from node labels.
 *
 * Centralized so compile-time validation and runtime projection slug labels
 * identically — otherwise a name that validates at compile time could differ
 * from the one a model is shown at runtime.
 *
 * @api
 */
final class ToolName {

  /**
   * Slugs a node label into a schema-safe tool name.
   *
   * Produces a token matching ^[a-zA-Z0-9_-]{1,64}$. Uniqueness within a
   * consumer's tool set is the site builder's responsibility.
   *
   * @param string $label
   *   The node label.
   *
   * @return string
   *   The tool name.
   */
  public static function fromLabel(string $label): string {
    $slug = strtolower($label);
    // Canonicalize every separator (spaces, dashes, punctuation) to "_" so
    // visually-distinct labels that differ only in separators ("Web Search" vs
    // "web-search") resolve to the same name and are caught as collisions.
    $slug = preg_replace("/[^a-z0-9]+/", "_", $slug) ?? "";
    $slug = trim($slug, "_");
    if ($slug === "") {
      $slug = "tool";
    }
    return substr($slug, 0, 64);
  }

}
