/**
 * Temporary ASE sync plugin quarantine guard.
 *
 * This file is written during a site sync and removed when plugin quarantine
 * is released. It runs before regular plugins so synced plugin code cannot
 * bootstrap against a pre-sync database or stale object-cache state.
 */
if ( ! defined( 'ABSPATH' ) ) {
	return;
}

if ( ! function_exists( 'asenha_sync_plugin_quarantine_guard_state' ) ) {
	/**
	 * Read guard state directly from the database to bypass stale alloptions.
	 *
	 * @return array
	 */
	function asenha_sync_plugin_quarantine_guard_state() {
		global $wpdb;

		if ( ! $wpdb ) {
			return array();
		}

		// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		$value = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
				'asenha_sync_plugin_quarantine_guard'
			)
		);

		$state = maybe_unserialize( $value );
		if ( ! is_array( $state ) || empty( $state['enabled'] ) ) {
			return array();
		}

		return $state;
	}
}

add_filter(
	'pre_option_active_plugins',
	function ( $pre_option ) {
		$state = asenha_sync_plugin_quarantine_guard_state();
		if ( empty( $state ) ) {
			return $pre_option;
		}

		$plugins = isset( $state['active_plugins'] ) && is_array( $state['active_plugins'] ) ? $state['active_plugins'] : array();
		return array_values( array_unique( array_filter( array_map( 'strval', $plugins ) ) ) );
	},
	1
);

add_filter(
	'pre_site_option_active_sitewide_plugins',
	function ( $pre_option ) {
		$state = asenha_sync_plugin_quarantine_guard_state();
		if ( empty( $state ) ) {
			return $pre_option;
		}

		$plugins = isset( $state['sitewide_plugins'] ) && is_array( $state['sitewide_plugins'] ) ? $state['sitewide_plugins'] : array();
		$filtered = array();
		foreach ( $plugins as $plugin_file => $activated_at ) {
			$plugin_file = (string) $plugin_file;
			if ( '' === $plugin_file ) {
				continue;
			}
			$filtered[ $plugin_file ] = is_numeric( $activated_at ) ? (int) $activated_at : time();
		}

		return $filtered;
	},
	1
);
