<?php

declare(strict_types=1);

namespace Drupal\flowdrop_ai_context\Hook;

use Drupal\Core\Hook\Attribute\Hook;

/**
 * Hook implementations for the FlowDrop AI Context module.
 *
 * @internal
 */
final class AiContextHooks {

  /**
   * The extension whose library pulls in our custom field widgets.
   */
  private const FIELD_WIDGET_TARGET_EXTENSION = 'flowdrop_ui_components';

  /**
   * The library within self::FIELD_WIDGET_TARGET_EXTENSION to extend.
   *
   * Every FlowDrop surface (editor, playground, standalone schema forms)
   * depends on this base library, so one dependency reaches all of them.
   */
  private const FIELD_WIDGET_TARGET_LIBRARY = 'flowdrop';

  /**
   * Implements hook_library_info_alter().
   *
   * Attaches the context selector / scope / agent context field widgets so they
   * can register with the FlowDrop field registry. This has to ride along on a
   * FlowDrop library rather than use hook_page_attachments(): the workflow
   * editor and playground render through BareHtmlPageRenderer, which never
   * invokes the page attachment hooks — so gating a page attachment on the
   * editor route, as this hook previously did, meant the widgets never loaded
   * anywhere at all.
   *
   * @param array<string, array<string, mixed>> $libraries
   *   Libraries defined by $extension, by reference.
   * @param string $extension
   *   The module/theme providing the libraries.
   */
  #[Hook('library_info_alter')]
  public function libraryInfoAlter(array &$libraries, string $extension): void {
    if ($extension !== self::FIELD_WIDGET_TARGET_EXTENSION
      || !isset($libraries[self::FIELD_WIDGET_TARGET_LIBRARY])
    ) {
      return;
    }

    $libraries[self::FIELD_WIDGET_TARGET_LIBRARY]['dependencies'][] = 'flowdrop_ai_context/context-selector-field';
  }

}
