<?php
/**
 * Action Scheduler minimal test task (dev-only by default).
 *
 * @package AgenticWP
 */

namespace Agentic_WP;

defined( 'ABSPATH' ) || exit;

use Agentic_WP\Error_Handler;

/**
 * Registers a simple Action Scheduler task to verify environment wiring.
 *
 * - Hook: 'agenticwp_as_test_run'
 * - Effect: increments an option and logs a message
 *
 * Enabled by default in development environments, or when the
 * 'agentic_wp_enable_as_test' filter returns true.
 */
final class AS_Test {

	private const GROUP = 'agenticwp_test';

	/**
	 * Register Action Scheduler test hooks if enabled.
	 *
	 * @return void
	 */
	public static function register(): void {
		if ( ! self::is_enabled() ) {
			return;
		}

		add_action( 'agenticwp_as_test_run', array( __CLASS__, 'handle_test_run' ) );
		add_action( 'action_scheduler_init', array( __CLASS__, 'maybe_schedule_recurring' ) );
	}

	/**
	 * Whether the test wiring should be active.
	 *
	 * Defaults to true for 'development' environments; can be overridden via
	 * the 'agentic_wp_enable_as_test' filter.
	 */
	private static function is_enabled(): bool {
		/**
		 * Filters whether Action Scheduler test wiring should be enabled.
		 *
		 * Test wiring provides diagnostic endpoints and test actions for
		 * verifying Action Scheduler functionality. When enabled, test
		 * actions can be dispatched via REST API endpoints.
		 *
		 * @hook agentic_wp_enable_as_test
		 * @since 1.0.0
		 *
		 * @param bool $enabled Whether test wiring is enabled. Default false.
		 * @return bool Whether test wiring should be enabled.
		 */
		$enabled = (bool) apply_filters( 'agentic_wp_enable_as_test', false );

		if ( defined( 'WP_CLI' ) && WP_CLI ) {
			return true;
		}

		if ( function_exists( 'wp_get_environment_type' ) && wp_get_environment_type() === 'development' ) {
			$enabled = true;
		}
		return $enabled;
	}

	/**
	 * Handle the test task execution.
	 *
	 * Increments a counter and updates the last run timestamp.
	 *
	 * @return void
	 */
	public static function handle_test_run(): void {
		try {
			$count = (int) get_option( 'agenticwp_as_test_count', 0 );
			++$count;
			update_option( 'agenticwp_as_test_count', $count );
			update_option( 'agenticwp_as_test_last_run', gmdate( 'c' ) );

			Error_Handler::debug_log(
				'Action Scheduler test ran',
				array(
					'count'    => $count,
					'last_run' => gmdate( 'c' ),
				)
			);
		} catch ( \Throwable $e ) {
			Error_Handler::log_error(
				'action_scheduler',
				'AS test run failed: ' . $e->getMessage(),
				array(
					'handler' => 'handle_test_run',
					'trace'   => $e->getTraceAsString(),
				)
			);
		}
	}

	/**
	 * Schedule recurring test task if not already scheduled.
	 *
	 * @return void
	 */
	public static function maybe_schedule_recurring(): void {
		try {
			if ( ! function_exists( 'as_has_scheduled_action' ) || ! function_exists( 'as_schedule_recurring_action' ) ) {
				Error_Handler::debug_log(
					'Action Scheduler functions not available',
					array( 'handler' => 'maybe_schedule_recurring' )
				);
				return;
			}

			$is_scheduled = as_has_scheduled_action( 'agenticwp_as_test_run', array(), self::GROUP );
			if ( ! $is_scheduled ) {
				as_schedule_recurring_action( time(), 10, 'agenticwp_as_test_run', array(), self::GROUP );

				Error_Handler::debug_log(
					'Action Scheduler test task scheduled',
					array(
						'interval' => 10,
						'group'    => self::GROUP,
					)
				);
			}
		} catch ( \Throwable $e ) {
			Error_Handler::log_error(
				'action_scheduler',
				'Failed to schedule AS test task: ' . $e->getMessage(),
				array(
					'handler' => 'maybe_schedule_recurring',
					'trace'   => $e->getTraceAsString(),
				)
			);
		}
	}
}
