<?php

/**
 * @file
 * AI module file.
 */

use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Implements hook_modules_installed().
 */
function ai_modules_installed(array $modules) {
  // Clear the provider cache when a module is installed.
  \Drupal::cache('discovery')->delete('ai_provider_plugins');
}

/**
 * Helper function to check if the current route is an admin route.
 *
 * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
 *   The route match interface.
 *
 * @return bool
 *   TRUE if the route is an admin route, FALSE otherwise.
 */
function ai_is_admin_route(RouteMatchInterface $route_match) {
  $route = $route_match->getRouteObject();
  if ($route && $route->hasOption('_admin_route') && $route->getOption('_admin_route') == TRUE) {
    return TRUE;
  }

  // Check if the route path starts with '/admin'.
  $path = $route_match->getRouteObject()->getPath();
  if (strpos($path, '/admin') === 0) {
    return TRUE;
  }

  return FALSE;
}

/**
 * Implements hook_module_preuninstall().
 */
function ai_module_preuninstall($module) {
  // Check if the module has an ai provider plugin.
  $plugin_manager = \Drupal::service('ai.provider');
  $plugins = $plugin_manager->getDefinitions();
  foreach ($plugins as $plugin) {
    if ($plugin['provider'] == $module) {
      \Drupal::service('ai.provider')->providerDisabled($plugin['id']);
    }
  }
}

/**
 * Implements hook_theme().
 *
 * Overrides the core html theme to use a custom template for iframes.
 */
function ai_theme() {
  return [
    'html__admin__config__ai__tools' => [
      'template' => 'html--admin--config--ai--tools',
      'render element' => 'html',
      'preprocess functions' => ['template_preprocess_html'],
    ],
    'page__admin__config__ai__tools' => [
      'template' => 'page--admin--config--ai--tools',
      'render element' => 'html',
      'preprocess functions' => ['template_preprocess_page'],
    ],
    'ai_tools_library_item' => [
      'variables' => [
        'title' => '',
        'description' => '',
        'tool_id' => '',
        'widget_id' => '',
        'buttons' => [],
      ],
    ],
    'ai_tools_library_wrapper' => [
      'variables' => [
        'menu' => [],
        'content' => [],
      ],
    ],
  ];
}

/**
 * Implements hook_preprocess_links__ai_tools_library_menu().
 *
 * This targets the menu of available ai tools group in the ai tools library's
 * modal dialog.
 *
 * @todo Do this in the relevant template once
 *   https://www.drupal.org/project/drupal/issues/3088856 is resolved.
 */
function ai_preprocess_links__ai_tools_library_menu(array &$variables): void {
  foreach ($variables['links'] as &$link) {
    // Add a class to the AI Tools Library menu items.
    $link['attributes']->addClass('ai-tools-library-menu__item');
    $link['link']['#options']['attributes']['class'][] = 'ai-tools-library-menu__link';
  }
}
