<?php

declare(strict_types=1);

namespace Drupal\ai\Entity;

use Drupal\ai\Plugin\AiPlatform\AiPlatformInterface;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Component\Plugin\PluginInspectionInterface;
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\Core\Entity\Attribute\ConfigEntityType;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\ai\Form\AiPlatformEntityForm;
use Drupal\ai\Form\AiPlatformDeleteForm;
use Drupal\ai\AiPlatformListBuilder;

/**
 * Defines the AI Platform configuration entity.
 */
#[ConfigEntityType(
  id: 'ai_platform',
  label: new TranslatableMarkup('AI Platform'),
  label_collection: new TranslatableMarkup('AI Platforms'),
  label_singular: new TranslatableMarkup('AI platform'),
  label_plural: new TranslatableMarkup('AI platforms'),
  label_count: [
    'singular' => '@count AI platform',
    'plural' => '@count AI platforms',
  ],
  handlers: [
    'list_builder' => AiPlatformListBuilder::class,
    'form' => [
      'add' => AiPlatformEntityForm::class,
      'edit' => AiPlatformEntityForm::class,
      'delete' => AiPlatformDeleteForm::class,
    ],
  ],
  config_prefix: 'platform',
  entity_keys: [
    'id' => 'id',
    'label' => 'label',
  ],
  config_export: [
    'id',
    'label',
    'plugin',
    'configuration',
  ],
  admin_permission: 'administer ai platforms',
  links: [
    'collection' => '/admin/config/ai/platforms',
    'add-form' => '/admin/config/ai/platforms/add',
    'edit-form' => '/admin/config/ai/platforms/manage/{ai_platform}',
    'delete-form' => '/admin/config/ai/platforms/manage/{ai_platform}/delete',
  ],
)]
final class AiPlatformConfig extends ConfigEntityBase implements AiPlatformConfigInterface {

  /**
   * The machine name of the AI platform configuration.
   */
  protected string $id;

  /**
   * The label of the AI platform configuration.
   */
  protected string $label;

  /**
   * The plugin ID.
   */
  protected string $plugin;

  /**
   * The plugin configuration.
   */
  protected array $configuration = [];

  /**
   * The AiPlatform plugin instance.
   *
   * @var \Drupal\ai\Plugin\AiPlatform\AiPlatformInterface|null
   */
  protected ?AiPlatformInterface $platformInstance = NULL;

  /**
   * {@inheritdoc}
   */
  public function getPlatformId(): string {
    return $this->plugin;
  }

  /**
   * {@inheritdoc}
   */
  public function getPlatformName(): string|\Stringable {
    $definition = $this->getPluginDefinition();

    return $definition ? $definition['label'] : $this->t('Missing plugin: @id', ['@id' => $this->getPlatformId()]);
  }

  /**
   * {@inheritdoc}
   */
  public function getPlatformInstance(): ?AiPlatformInterface {
    if (!$this->platformInstance && $this->plugin) {
      try {
        $this->platformInstance = \Drupal::service('plugin.manager.ai_platform')->createInstance($this->plugin, $this->configuration);
      }
      catch (PluginException) {
        return NULL;
      }
    }
    return $this->platformInstance;
  }

  /**
   * Gets the plugin definition.
   *
   * @return array|null
   *   The plugin definition, or NULL if the plugin is not set or not found.
   */
  private function getPluginDefinition(): ?array {
    if ($this->plugin) {
      $plugin_manager = \Drupal::service('plugin.manager.ai_platform');
      if ($plugin_manager->hasDefinition($this->plugin)) {
        return $plugin_manager->getDefinition($this->plugin);
      }
    }
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function postSave($storage, $update = TRUE): void {
    parent::postSave($storage, $update);
    // Invalidate the AI provider plugin cache so that the BC bridge deriver
    // picks up the new/updated platform configuration.
    \Drupal::service('ai.provider')->clearCachedDefinitions();
  }

  /**
   * {@inheritdoc}
   */
  public static function postDelete($storage, array $entities): void {
    parent::postDelete($storage, $entities);
    \Drupal::service('ai.provider')->clearCachedDefinitions();
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies(): static {
    parent::calculateDependencies();

    if ($this->plugin) {
      $plugin_manager = \Drupal::service('plugin.manager.ai_platform');
      $definition = $plugin_manager->getDefinition($this->plugin);
      $this->addDependency('module', $definition['provider']);

      // Do not use the cached instance for calculation because it could
      // have been built from the previous configuration.
      $instance = $this->platformInstance = \Drupal::service('plugin.manager.ai_platform')->createInstance($this->plugin, $this->configuration);
      if ($instance instanceof PluginInspectionInterface) {
        $this->addDependencies($this->getPluginDependencies($instance));
      }
    }

    return $this;
  }

}
