<?php

declare(strict_types=1);

namespace KimaAI\Addons;

use KimaAI\Main;
use KimaAI\Surfaces\ClassesSurface;

final class AddonManager {

  /**
   * Registered add-ons.
   *
   * @var AddonInterface[]
   */
  private array $addons = [];

  /**
   * Register an add-on instance.
   *
   * Typically called by external plugins on the `kimaai_register_addons` action.
   */
  public function register(AddonInterface $addon): void {
    $this->addons[] = $addon;
  }

  /**
   * Boot all registered add-ons.
   *
   * Called once, after all add-ons had a chance to call ->register().
   */
  public function boot(Main $main, ClassesSurface $classes): void {
    foreach ($this->addons as $addon) {
      $addon->register($main, $classes);
    }

    if (!defined('WP_CLI') || !WP_CLI) {
      return;
    }

    add_action('cli_init', function () use ($main, $classes) {
      foreach ($this->addons as $addon) {
        if (is_object($addon) && method_exists($addon, 'registerCommands')) {
          $addon->registerCommands($main, $classes);
        }
      }
    });
  }
}
