<?php

declare( strict_types=1 );

namespace Limb_Chatbot\Includes\Services\System_Message\Chunks;

use Limb_Chatbot\Includes\Services\User_Manager;
use Limb_Chatbot\Includes\Utilities\Chatbot_Utility;

/**
 * User Information Chunk
 *
 * Provides contextual information about the current user.
 * This allows the AI to personalize responses and address users appropriately.
 *
 * Extensible for additional fields (email, roles, segments, etc.).
 *
 * @since 1.1.1
 */
class User_Information_Chunk extends System_Message_Chunk {

	/**
	 * User information data to inject.
	 *
	 * @var array
	 */
	private array $user_data = [];

	/**
	 * Constructor.
	 *
	 * @param  Chatbot_Utility  $utility
	 */
	public function __construct( Chatbot_Utility $utility ) {
		$this->user_data = $this->get_user_data( $utility );
	}

	private function get_user_data( Chatbot_Utility $utility ) {
		return array();
	}

	public function get_title(): string {
		return 'User Information';
	}

	public function get_content(): array {
		$lines = [
			'The following describes the user you are currently interacting with in this conversation.',
		];

		// Try to get user info from manager
		if ( empty( $this->user_data ) ) {
			try {
				$user = User_Manager::instance()->get_current_user();
				if ( $user && $name = $user->name() ) {
					$lines[] = "- Name: {$name} (address them by name when appropriate).";
				}
			} catch ( \Exception $e ) {
				// User info unavailable, continue with generic message
			}
		} else {
			// Use injected user data
			if ( ! empty( $this->user_data['name'] ) ) {
				$lines[] = "- Name: {$this->user_data['name']} (address them by name when appropriate).";
			}

			if ( ! empty( $this->user_data['email'] ) ) {
				$lines[] = "- Email: {$this->user_data['email']}";
			}

			if ( ! empty( $this->user_data['role'] ) ) {
				$lines[] = "- Role: {$this->user_data['role']}";
			}

			if ( ! empty( $this->user_data['segment'] ) ) {
				$lines[] = "- Customer Segment: {$this->user_data['segment']}";
			}
		}

		// If no user info yet, still leave a generic intro
		if ( count( $lines ) === 1 ) {
			$lines[] = '- No additional user details are available for this conversation.';
		}

		return $lines;
	}

	public function get_priority(): int {
		return 20;
	}
}
