<?php
/**
 * Admin browser actor context helper.
 *
 * @package Niwa_AI
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Niwa_AI_Admin_Autonomy_Browser_Message_Context {
	public function build_actor_context( $session_id, $user_id = 0, $shared_founder_chat_id = '' ) {
		$session_id  = trim( (string) $session_id );
		$user_id     = max( 0, intval( $user_id ) );
		$user        = $user_id > 0 ? get_userdata( $user_id ) : false;
		$chat_id     = trim( (string) $shared_founder_chat_id );
		$ui_locale   = $this->resolve_ui_locale( $user_id );
		$ui_language = $this->get_ui_language();

		return array(
			'channel'                => 'admin_ui',
			'chat_id'                => $chat_id,
			'message_id'             => 0,
			'session_id'             => $session_id,
			'user_role'              => 'admin',
			'shared_founder_session' => '' !== $chat_id,
			'admin_user_id'          => $user_id,
			'admin_user_login'       => $user && isset( $user->user_login ) ? (string) $user->user_login : '',
			'admin_user_email'       => $user && isset( $user->user_email ) ? (string) $user->user_email : '',
			'admin_user_name'        => $user && isset( $user->display_name ) ? (string) $user->display_name : '',
			'ui_locale'              => $ui_locale,
			'ui_language'            => $ui_language,
			'conversation_language'  => $ui_language,
		);
	}

	public function get_ui_language() {
		if ( ! function_exists( 'get_option' ) ) {
			return 'en';
		}

		$ui_settings = get_option( Niwa_AI_Constants::OPT_UI_SETTINGS, array() );
		$language    = is_array( $ui_settings ) && isset( $ui_settings['ui_language'] )
			? (string) $ui_settings['ui_language']
			: '';
		$normalized  = $this->normalize_ui_language( $language );

		return '' !== $normalized ? $normalized : 'en';
	}

	public function normalize_ui_language( $language ) {
		$language = strtolower( trim( str_replace( '-', '_', (string) $language ) ) );
		if ( '' === $language ) {
			return '';
		}

		$parts = preg_split( '/_+/', $language );
		$base  = isset( $parts[0] ) ? preg_replace( '/[^a-z]/', '', (string) $parts[0] ) : '';
		if ( '' === $base ) {
			return '';
		}

		return $base;
	}

	private function resolve_ui_locale( $user_id ) {
		$ui_locale = '';
		if ( $user_id > 0 && function_exists( 'get_user_locale' ) ) {
			$ui_locale = trim( (string) get_user_locale( $user_id ) );
		}
		if ( '' === $ui_locale && function_exists( 'determine_locale' ) ) {
			$ui_locale = trim( (string) determine_locale() );
		}
		if ( '' === $ui_locale && function_exists( 'get_locale' ) ) {
			$ui_locale = trim( (string) get_locale() );
		}

		return $ui_locale;
	}
}
