<?php

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

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Site\Settings;

/**
 * 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_form_FORM_ID_alter() for ai_settings_form.
 */
function ai_form_ai_settings_alter(&$form, FormStateInterface $form_state) {
  if (!empty(Settings::get('ai_output')['full_trust_mode'])) {
    $form['advanced_settings']['allowed_host_wrapper']['allowed_hosts_rewrite_links']['rewrite']['#attributes']['disabled'] = 'disabled';
    $form['advanced_settings']['allowed_host_wrapper']['allowed_hosts_rewrite_links']['delete']['#attributes']['disabled'] = 'disabled';
  }
  else {
    $form['advanced_settings']['allowed_host_wrapper']['allowed_hosts_rewrite_links']['full_trust']['#attributes']['disabled'] = 'disabled';
  }
}
