<?php

namespace Limb_Chatbot\Includes\Services;

use Limb_Chatbot\Includes\Data_Objects\Chat;
use Limb_Chatbot\Includes\Traits\SingletonTrait;

/**
 * Centralized context manager for the currently active chat session.
 *
 * This class provides a shared point of reference for services that require
 * access to the active chat instance during request execution. Once a chat
 * is assigned via {@see Chat_Context::init()}, the context becomes available
 * globally (per request) through the singleton accessor.
 *
 * Responsibilities:
 *  - Store and expose the active Chat instance.
 *  - Register per-chat hooks that depend on knowing which chat is active.
 *  - Provide the Chat_Language_Service used by language-related filters.
 *
 * @since 1.0.8
 */
class Chat_Context {
	use SingletonTrait;

	/**
	 * Service responsible for language metadata handling and directive generation.
	 *
	 * @var Chat_Language_Service
	 */
	public Chat_Language_Service $chat_language_service;

	/**
	 * The currently active chat instance.
	 *
	 * @var Chat|null
	 */
	private ?Chat $chat = null;

	/**
	 * Constructor.
	 *
	 * Initializes service dependencies but does not register hooks or assign a chat.
	 * Hooks are attached only when {@see Chat_Context::init()} is called.
	 *
	 * @since 1.0.8
	 */
	public function __construct() {
		$this->chat_language_service = new Chat_Language_Service();
	}

	/**
	 * Initializes the chat context for the current request.
	 *
	 * This assigns the active chat and registers the hooks that rely on knowing
	 * which chat is being processed. Calling this method multiple times within
	 * the same request overwrites the stored chat but still only registers hooks once.
	 *
	 * @param Chat|null $chat  The chat instance for the current execution context.
	 *
	 * @return void
	 * @since 1.0.8
	 */
	public function init(?Chat $chat = null): void {
		$this->chat = $chat;
		$this->register_hooks();
	}

	/**
	 * Registers WordPress filters that require access to the active chat.
	 *
	 * These hooks extend system messages by injecting language directives,
	 * enabling consistent language behavior across copilots and internal systems.
	 *
	 * @return void
	 * @internal This method should only be invoked by {@see Chat_Context::init()}.
	 * @since 1.0.8
	 */
	private function register_hooks(): void {
//		add_filter(
//			'lbaic_copilot_system_message',
//			[ $this->chat_language_service, 'add_language_directive' ]
//		);
//
//		add_filter(
//			'lbaic_internal_system_message',
//			[ $this->chat_language_service, 'add_main_language_directive' ]
//		);
	}

	/**
	 * Retrieve the currently active chat.
	 *
	 * @return Chat|null The chat instance assigned for this request, or null if unset.
	 * @since 1.0.8
	 */
	public function get_chat(): ?Chat {
		return $this->chat;
	}
}
