<?php
/**
 * Class Loco_Automatic_Translate_Addon_Pro\AI_Translate\Services\Services_Loader
 *
 * @var string $main_file Absolute path to the plugin main file.
 */

namespace Loco_Automatic_Translate_Addon_Pro\AI_Translate\Services;

use Felix_Arntz\WP_OOP_Plugin_Lib\Capabilities\Capability_Controller;
use Felix_Arntz\WP_OOP_Plugin_Lib\General\Contracts\With_Hooks;
use Felix_Arntz\WP_OOP_Plugin_Lib\General\Service_Container;
use Felix_Arntz\WP_OOP_Plugin_Lib\Assets\Script_Style_Loader;

/**
 * Loader class responsible for initializing the AI services functionality, including its public API.
 */
final class Services_Loader implements With_Hooks {

	/**
	 * Service container for the class's dependencies.
	 *
	 * @var Service_Container
	 */
	private $container;

	/**
	 * Constructor.
	 *
	 * @param string $main_file Absolute path to the plugin main file.
	 */
	public function __construct( string $main_file ) {
		$this->container = $this->set_up_container( $main_file );
		Services_API_Instance::set( $this->container['api'] );
	}

	/**
	 * Adds relevant WordPress hooks.
	 */
	public function add_hooks(): void {
		$this->load_capabilities();
		$this->load_options();

	}

	/**
	 * Loads the services capabilities and sets up the relevant filters.
	 */
	private function load_capabilities(): void {
		add_action(
			'plugins_loaded',
			function () {
				$this->container['capability_filters']->add_hooks();
			},
			0
		);
	}

	/**
	 * Loads the services options.
	 *
	 * The option container is populated with options dynamically based on registered AI services. Each of the relevant
	 * options will be registered here.
	 */
	private function load_options(): void {
		add_action(
			'init',
			function () {
				$registry = $this->container['option_registry'];
				foreach ( $this->container['option_container']->get_keys() as $key ) {
					$option = $this->container['option_container']->get( $key );
					$registry->register(
						$option->get_key(),
						$option->get_registration_args()
					);
				}
			},
			0
		);
	}

	/**
	 * Sets up the services service container.
	 *
	 * @param string $main_file Absolute path to the plugin main file.
	 * @return Service_Container The services service container.
	 */
	private function set_up_container( string $main_file ): Service_Container {
		$builder = new Services_Service_Container_Builder();

		return $builder->build_env( $main_file )
			->build_services()
			->get();
	}
}
