<?php
/**
 * Hub API helpers for maca Tjatt (shared by REST layer).
 *
 * @package Maca_Tjatt
 */

defined( 'ABSPATH' ) || exit;

/**
 * Site key stored by maca Sec Hub reporter.
 *
 * @return string
 */
function maca_tjatt_hub_get_site_key() {
	return trim( (string) get_option( 'maca_sec_hub_site_key', '' ) );
}

/**
 * @return array<string, mixed>
 */
function maca_tjatt_hub_get_status() {
	$index_status = Maca_Tjatt_Service::get_index_status();
	$chunk_count  = Maca_Tjatt_DB::count_chunks();

	return array(
		'installed'               => true,
		'plugin_version'          => defined( 'MACA_TJATT_VERSION' ) ? MACA_TJATT_VERSION : '',
		'enabled'                 => Maca_Tjatt_Service::is_enabled(),
		'floating'                => '1' === (string) get_option( 'maca_tjatt_floating', '1' ),
		'ai_available'            => Maca_Tjatt_Service::is_ai_available(),
		'display_name'            => Maca_Tjatt_Service::get_display_name(),
		'avatar_url'              => Maca_Tjatt_Service::get_avatar_url(),
		'avatar_size'             => Maca_Tjatt_Service::get_avatar_size(),
		'chat_model'              => Maca_Tjatt_Service::get_chat_model(),
		'rate_limit'              => Maca_Tjatt_Service::get_rate_limit(),
		'index_all_pages'         => Maca_Tjatt_Service::index_all_pages(),
		'index_posts'             => Maca_Tjatt_Service::index_posts(),
		'selected_page_count'     => count( Maca_Tjatt_Service::get_page_ids() ),
		'custom_knowledge_length' => strlen( Maca_Tjatt_Service::get_custom_knowledge() ),
		'chunk_count'             => $chunk_count,
		'index'                   => array(
			'success'  => ! empty( $index_status['success'] ),
			'message'  => (string) ( $index_status['message'] ?? '' ),
			'built_at' => (string) ( $index_status['built_at'] ?? '' ),
			'count'    => (int) ( $index_status['count'] ?? $chunk_count ),
		),
		'ready'                   => Maca_Tjatt_Service::is_enabled()
			&& Maca_Tjatt_Service::is_ai_available()
			&& $chunk_count > 0,
	);
}

/**
 * Partial settings update for maca Hub.
 *
 * @param array<string, mixed> $patch Allowed setting keys only.
 * @return array<string, mixed>|WP_Error
 */
function maca_tjatt_hub_update_settings( array $patch ) {
	$allowed = array(
		'enabled',
		'floating',
		'name',
		'rate_limit',
		'index_all_pages',
		'index_posts',
		'chat_model',
		'custom_knowledge',
	);

	$has_changes = false;

	foreach ( $allowed as $key ) {
		if ( ! array_key_exists( $key, $patch ) ) {
			continue;
		}

		switch ( $key ) {
			case 'enabled':
				update_option( 'maca_tjatt_enabled', ! empty( $patch[ $key ] ) ? '1' : '0', false );
				$has_changes = true;
				break;
			case 'floating':
				update_option( 'maca_tjatt_floating', ! empty( $patch[ $key ] ) ? '1' : '0', false );
				$has_changes = true;
				break;
			case 'name':
				update_option( 'maca_tjatt_name', sanitize_text_field( (string) $patch[ $key ] ), false );
				$has_changes = true;
				break;
			case 'rate_limit':
				$limit = absint( $patch[ $key ] );
				update_option( 'maca_tjatt_rate_limit', max( 5, min( 200, $limit ) ), false );
				$has_changes = true;
				break;
			case 'index_all_pages':
				update_option( 'maca_tjatt_index_all_pages', ! empty( $patch[ $key ] ) ? '1' : '0', false );
				$has_changes = true;
				break;
			case 'index_posts':
				update_option( 'maca_tjatt_index_posts', ! empty( $patch[ $key ] ) ? '1' : '0', false );
				$has_changes = true;
				break;
			case 'chat_model':
				update_option( 'maca_tjatt_chat_model', sanitize_text_field( (string) $patch[ $key ] ), false );
				$has_changes = true;
				break;
			case 'custom_knowledge':
				update_option( 'maca_tjatt_custom_knowledge', sanitize_textarea_field( (string) $patch[ $key ] ), false );
				$has_changes = true;
				break;
		}
	}

	if ( ! $has_changes ) {
		return new WP_Error(
			'maca_tjatt_no_changes',
			__( 'No settings to update.', 'maca-tjatt' ),
			array( 'status' => 400 )
		);
	}

	Maca_Tjatt_Service::maybe_schedule_cron();

	if ( Maca_Tjatt_Service::is_enabled() && Maca_Tjatt_Service::is_ai_available() ) {
		Maca_Tjatt_Service::schedule_reindex();
	}

	return array(
		'ok'     => true,
		'status' => maca_tjatt_hub_get_status(),
	);
}

/**
 * Build the search index from maca Hub.
 *
 * @return array<string, mixed>|WP_Error
 */
function maca_tjatt_hub_build_index() {
	if ( ! Maca_Tjatt_Service::is_ai_available() ) {
		return new WP_Error(
			'maca_tjatt_ai_unavailable',
			Maca_Tjatt_AI_Client::get_unavailable_message(),
			array( 'status' => 409 )
		);
	}

	$result = Maca_Tjatt_Indexer::build_index();

	if ( is_wp_error( $result ) ) {
		return $result;
	}

	$message = is_array( $result ) ? (string) ( $result['message'] ?? '' ) : '';

	return array(
		'ok'      => true,
		'message' => $message,
		'status'  => maca_tjatt_hub_get_status(),
	);
}
