<?php
/**
 * The main KimaAI plugin file.
 *
 * @class KimaAI
 * @package KimaAI
 * @since 1.0.0
 */

declare(strict_types=1);

namespace KimaAI;

use Exception;
use KimaAI\Addons\AddonManager;
use RuntimeException;

defined('ABSPATH') || exit;

final class KimaAI {

  /**
   * The plugin prefix.
   *
   * @var string
   */
  public const PREFIX = 'kimaai';

  public const API_VERSION = 'v1';

  /**
   * KimaAI constructor.
   */
  private function __construct() {
    add_action('plugins_loaded', [$this, 'pluginsLoaded']);
  }

  /**
   * Initializes the plugin.
   * - Loads the text domain.
   * - Creates the DI container.
   *
   * @hook plugins_loaded
   * @throws Exception If the DI container cannot be created.
   * @throws RuntimeException If the DI container cannot be created.
   */
  public function pluginsLoaded(): void {
    Schema::registerHooks();

    // Load the KimaAI Pro features.
    // Use can_use_premium_code__premium_only() directly (not Helper::isPremium()) to avoid
    // a bootstrap chicken-and-egg problem: Helper::isPremium() requires KIMAAI_PRO_PLUGIN_FILE
    // to be defined, but that constant is only defined inside premium-loader.php itself.
    $premium_loader_file_path = KIMAAI_PLUGIN_PATH . 'premium/premium-loader.php';
    if (
      \function_exists(__NAMESPACE__ . '\\kimaai_fs')
      && kimaai_fs()->can_use_premium_code__premium_only()
      && file_exists($premium_loader_file_path)
    ) {
      require_once $premium_loader_file_path;
    }

    // Boot DI + Loader.
    $main = KimaAI();
    $classes = $main->classes;
    $addon_manager = $classes->get(AddonManager::class);

    /**
     * Give external plugins a chance to register add-ons.
     *
     * Example:
     *   add_action('kimaai_register_addons', function (AddonManager $manager, Main $main, ClassesSurface $classes) {
     *       $manager->register(new \MyVendor\KimaAIAddon\MyAddon());
     *   });
     */
    do_action('kimaai_register_addons', $addon_manager, $main, $classes);

    // Boot all registered add-ons.
    $addon_manager->boot($main, $classes);

    /**
     * Signal that KimaAI (and its add-ons) are fully loaded.
     *
     * This is useful for simple integrations that don’t implement AddonInterface
     * but still want a “ready” hook.
     */
    do_action('kimaai_loaded', $main, $classes, $addon_manager);

    add_action('admin_init', function () {
      // Only notify site admins, and only if no key is set.
      if (current_user_can('manage_options') && !Helper::hasApiKey()) {
        add_action('admin_notices', [$this, 'adminNoticeNoApiKey']);
      }
    });

    Logger::init('kimaai_log_path', 'KimaAI', true);
  }

  /**
   * Displays an admin notice if no API key is set.
   */
  public function adminNoticeNoApiKey(): void {
    // Adjust this if your settings page slug is different.
    $settings_url = admin_url('admin.php?page=kimaai#/ai-envs');
    // Direct link to OpenAI's API key page.
    $openai_url = 'https://platform.openai.com/api-keys';
    $msg = sprintf(
    /* translators: 1: settings URL, 2: OpenAI API key URL */
      __('KimaAI needs an AI provider API key before it can run. We recommend starting with OpenAI. Create an account and generate an API Key by visiting the <a href="%1$s" target="_blank" rel="noopener noreferrer">OpenAI</a> website. Once obtained, navigate to the "AI Services" tab and input your OpenAI API Key in the <a href="%2$s">AI Environments</a> section.', 'kimaai'),
      esc_url($openai_url),
      esc_url($settings_url),
    );

    echo '<div class="notice notice-error kimaai-notice"><p>'
    . wp_kses($msg, [
      'a' => [
        'href' => [],
        'target' => [],
        'rel' => [],
      ],
    ])
    . '</p></div>';
  }

  /**
   * Returns the single instance of the class.
   *
   * @return self
   */
  public static function instance(): self {
    static $instance = null;
    if ($instance === null) {
      $instance = new self();
    }
    return $instance;
  }
}
