<?php
/**
 * Live status meta for React Settings tools (indexing, GSC, IndexNow).
 *
 * @package Newsroom_AI_Assistant
 */

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

if ( ! function_exists( 'newsai_settings_registry_meta' ) ) {
	function newsai_settings_registry_meta() {
		$index_last_code         = (int) get_option( 'newsai_indexing_last_code', 0 );
		$index_last_ping         = (int) get_option( 'newsai_indexing_last_ping', 0 );
		$index_last_error        = (string) get_option( 'newsai_indexing_last_error', '' );
		$index_last_success_ping = (int) get_option( 'newsai_indexing_last_success_ping', 0 );
		$index_health            = 'unknown';
		if ( $index_last_success_ping > 0 && $index_last_success_ping >= ( time() - ( 7 * DAY_IN_SECONDS ) ) ) {
			$index_health = 'healthy';
		} elseif ( $index_last_ping > 0 && $index_last_error !== '' ) {
			$index_health = 'degraded';
		}

		$indexnow_last_code         = (int) get_option( 'newsai_indexnow_last_code', 0 );
		$indexnow_last_ping         = (int) get_option( 'newsai_indexnow_last_ping', 0 );
		$indexnow_last_error        = (string) get_option( 'newsai_indexnow_last_error', '' );
		$indexnow_last_success_ping = (int) get_option( 'newsai_indexnow_last_success_ping', 0 );
		$indexnow_health            = 'unknown';
		if ( $indexnow_last_success_ping > 0 && $indexnow_last_success_ping >= ( time() - ( 7 * DAY_IN_SECONDS ) ) ) {
			$indexnow_health = 'healthy';
		} elseif ( $indexnow_last_ping > 0 && $indexnow_last_error !== '' ) {
			$indexnow_health = 'degraded';
		}

		$gsc_backfill_state   = function_exists( 'newsai_gsc_backfill_get_state' ) ? newsai_gsc_backfill_get_state() : [];
		$gsc_bf_chunks        = isset( $gsc_backfill_state['chunks'] ) && is_array( $gsc_backfill_state['chunks'] ) ? $gsc_backfill_state['chunks'] : [];
		$gsc_bf_index         = (int) ( $gsc_backfill_state['chunk_index'] ?? 0 );
		$gsc_bf_total         = count( $gsc_bf_chunks );

		return [
			'schemaWarm' => [
				'last'  => (int) get_option( 'nros_schema_warm_last_batch', 0 ),
				'count' => (int) get_option( 'nros_schema_warm_last_count', 0 ),
			],
			'indexing'   => [
				'jsonConfigured' => function_exists( 'newsai_secret_has_stored' ) && newsai_secret_has_stored( 'indexing_service_json' ),
				'jsonLocked'     => function_exists( 'newsai_secret_is_locked' ) && newsai_secret_is_locked( 'indexing_service_json' ),
				'clientEmail'    => function_exists( 'newsai_secret_indexing_client_email' ) ? (string) newsai_secret_indexing_client_email() : (string) get_option( 'newsai_indexing_service_email', '' ),
				'lastPing'       => $index_last_ping,
				'lastCode'       => $index_last_code,
				'lastUrl'        => (string) get_option( 'newsai_indexing_last_url', '' ),
				'lastError'      => $index_last_error,
				'lastSuccessPing'=> $index_last_success_ping,
				'lastSuccessCode'=> (int) get_option( 'newsai_indexing_last_success_code', 0 ),
				'lastSuccessUrl' => (string) get_option( 'newsai_indexing_last_success_url', '' ),
				'health'         => $index_health,
			],
			'gsc'        => [
				'lastSync'        => (string) get_option( 'newsai_gsc_last_sync', '' ),
				'lastCount'       => (int) get_option( 'newsai_gsc_last_count', 0 ),
				'lastError'       => (string) get_option( 'newsai_gsc_last_error', '' ),
				'rows'            => function_exists( 'newsai_gsc_row_count' ) ? (int) newsai_gsc_row_count() : 0,
				'queryRows'       => function_exists( 'newsai_gsc_query_row_count' ) ? (int) newsai_gsc_query_row_count() : 0,
				'lastQueryRows'   => (int) get_option( 'newsai_gsc_last_query_rows', 0 ),
				'lastQueryMode'   => (string) get_option( 'newsai_gsc_last_query_sync_mode', '' ),
				'nextCronTs'      => function_exists( 'newsai_gsc_should_schedule_cron' ) && newsai_gsc_should_schedule_cron()
					? (int) wp_next_scheduled( 'newsai_gsc_daily_sync' )
					: 0,
				'backfillRunning' => function_exists( 'newsai_gsc_backfill_is_running' ) && newsai_gsc_backfill_is_running(),
				'backfillDoneAt'  => (int) get_option( 'newsai_gsc_backfill_completed_at', 0 ),
				'backfillChunk'   => $gsc_bf_total > 0 ? min( $gsc_bf_index + 1, $gsc_bf_total ) : 0,
				'backfillTotal'   => $gsc_bf_total,
				'backfillMessage' => (string) ( $gsc_backfill_state['last_message'] ?? '' ),
			],
			'indexnow'   => [
				'key'             => function_exists( 'newsai_indexnow_get_key' ) ? (string) newsai_indexnow_get_key() : '',
				'keyUrl'          => function_exists( 'newsai_indexnow_key_url' ) ? (string) newsai_indexnow_key_url() : '',
				'lastPing'        => $indexnow_last_ping,
				'lastCode'        => $indexnow_last_code,
				'lastUrl'         => (string) get_option( 'newsai_indexnow_last_url', '' ),
				'lastError'       => $indexnow_last_error,
				'lastSuccessPing' => $indexnow_last_success_ping,
				'lastSuccessCode' => (int) get_option( 'newsai_indexnow_last_success_code', 0 ),
				'lastSuccessUrl'  => (string) get_option( 'newsai_indexnow_last_success_url', '' ),
				'health'          => $indexnow_health,
			],
			'weeklyReport' => [
				'lastSent'  => (int) get_option( 'newsai_weekly_report_last_sent', 0 ),
				'lastCount' => (int) get_option( 'newsai_weekly_report_last_count', 0 ),
			],
			'aiPolicyReady' => function_exists( 'newsai_ai_is_active' ) && newsai_ai_is_active(),
		];
	}
}
