/**
 * ASE Migration: plugin quarantine guard (auto-generated).
 *
 * Forces ASE-only active_plugins during migration file mutation and database
 * import so destination/source plugin code cannot fatal admin-ajax bootstraps.
 * Optionally forces a safe core theme while quarantine is active.
 * Authority is the migration restore_state JSON file (not WordPress options),
 * because database import overwrites options and object-cache entries.
 *
 * @since 8.9.1
 */

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

if ( ! function_exists( 'asenha_migration_quarantine_guard_state' ) ) {
	/**
	 * Read migration quarantine state from the restore state file.
	 *
	 * @return array{
	 *   enforce:bool,
	 *   ase_basename:string,
	 *   migration_id:string,
	 *   theme_slug:string
	 * }
	 */
	function asenha_migration_quarantine_guard_state() {
		static $cached = null;
		if ( null !== $cached ) {
			return $cached;
		}

		$cached = array(
			'enforce'      => false,
			'ase_basename' => '%%ASE_PLUGIN_BASENAME%%',
			'migration_id' => '%%MIGRATION_ID%%',
			'theme_slug'   => '%%THEME_QUARANTINE_SLUG%%',
		);

		$migration_id = '%%MIGRATION_ID%%';
		$mapping_file = WP_CONTENT_DIR . '/asenha-restore-dirs.json';

		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_exists
		if ( ! file_exists( $mapping_file ) ) {
			return $cached;
		}

		$raw = file_get_contents( $mapping_file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
		if ( false === $raw ) {
			return $cached;
		}

		$mappings = json_decode( $raw, true );
		if ( ! is_array( $mappings ) || empty( $mappings[ $migration_id ] ) ) {
			return $cached;
		}

		$entry      = $mappings[ $migration_id ];
		$backup_dir = '';
		if ( is_array( $entry ) && ! empty( $entry['backup_dir'] ) && is_string( $entry['backup_dir'] ) ) {
			$backup_dir = $entry['backup_dir'];
		} elseif ( is_string( $entry ) ) {
			$backup_dir = $entry;
		}

		if ( '' === $backup_dir || ! is_dir( $backup_dir ) ) {
			return $cached;
		}

		$state_file = rtrim( $backup_dir, '/\\' ) . '/restore_state_' . preg_replace( '/[^A-Za-z0-9_-]/', '', $migration_id ) . '.json';
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_exists
		if ( ! file_exists( $state_file ) ) {
			return $cached;
		}

		$raw_state = file_get_contents( $state_file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
		if ( false === $raw_state ) {
			return $cached;
		}

		$state = json_decode( $raw_state, true );
		if ( ! is_array( $state ) || empty( $state['plugin_quarantine_active'] ) ) {
			return $cached;
		}

		$status = isset( $state['status'] ) ? (string) $state['status'] : '';
		// Completed migrations should have cleared quarantine; if the flag was
		// cleared but the file remains, do not enforce. Kept-after-failure stays
		// enforceable while plugin_quarantine_active remains true.
		if ( 'completed' === $status && empty( $state['plugin_quarantine_kept_after_failure'] ) ) {
			return $cached;
		}

		if ( ! empty( $state['theme_quarantine_slug'] ) ) {
			$cached['theme_slug'] = preg_replace( '/[^a-z0-9_-]/i', '', (string) $state['theme_quarantine_slug'] );
		}

		$cached['enforce'] = true;
		return $cached;
	}
}

add_filter(
	'pre_option_active_plugins',
	static function ( $pre_option ) {
		$state = asenha_migration_quarantine_guard_state();
		if ( empty( $state['enforce'] ) ) {
			return $pre_option;
		}

		$basename = isset( $state['ase_basename'] ) ? (string) $state['ase_basename'] : '';
		if ( '' === $basename ) {
			$basename = '%%ASE_PLUGIN_BASENAME%%';
		}

		return array( $basename );
	},
	1
);

add_filter(
	'pre_site_option_active_sitewide_plugins',
	static function ( $pre_option ) {
		$state = asenha_migration_quarantine_guard_state();
		if ( empty( $state['enforce'] ) ) {
			return $pre_option;
		}

		// Network-activate nothing during quarantine; ASE remains site-active via active_plugins.
		return array();
	},
	1
);

add_filter(
	'pre_option_stylesheet',
	static function ( $pre_option ) {
		$state = asenha_migration_quarantine_guard_state();
		if ( empty( $state['enforce'] ) || empty( $state['theme_slug'] ) ) {
			return $pre_option;
		}
		return (string) $state['theme_slug'];
	},
	1
);

add_filter(
	'pre_option_template',
	static function ( $pre_option ) {
		$state = asenha_migration_quarantine_guard_state();
		if ( empty( $state['enforce'] ) || empty( $state['theme_slug'] ) ) {
			return $pre_option;
		}
		return (string) $state['theme_slug'];
	},
	1
);

// Self-cleanup when quarantine is no longer active and migration is terminal.
add_action(
	'shutdown',
	static function () {
		$state = asenha_migration_quarantine_guard_state();
		if ( ! empty( $state['enforce'] ) ) {
			return;
		}

		$migration_id = isset( $state['migration_id'] ) ? (string) $state['migration_id'] : '%%MIGRATION_ID%%';
		$mapping_file = WP_CONTENT_DIR . '/asenha-restore-dirs.json';
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_exists
		if ( ! file_exists( $mapping_file ) ) {
			@unlink( __FILE__ ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
			return;
		}

		$raw = file_get_contents( $mapping_file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
		if ( false === $raw ) {
			return;
		}

		$mappings = json_decode( $raw, true );
		if ( ! is_array( $mappings ) || empty( $mappings[ $migration_id ] ) ) {
			@unlink( __FILE__ ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
			return;
		}

		$entry      = $mappings[ $migration_id ];
		$backup_dir = '';
		if ( is_array( $entry ) && ! empty( $entry['backup_dir'] ) && is_string( $entry['backup_dir'] ) ) {
			$backup_dir = $entry['backup_dir'];
		} elseif ( is_string( $entry ) ) {
			$backup_dir = $entry;
		}

		if ( '' === $backup_dir ) {
			@unlink( __FILE__ ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
			return;
		}

		$state_file = rtrim( $backup_dir, '/\\' ) . '/restore_state_' . preg_replace( '/[^A-Za-z0-9_-]/', '', $migration_id ) . '.json';
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_exists
		if ( ! file_exists( $state_file ) ) {
			@unlink( __FILE__ ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
			return;
		}

		$raw_state = file_get_contents( $state_file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
		if ( false === $raw_state ) {
			return;
		}

		$parsed = json_decode( $raw_state, true );
		if ( ! is_array( $parsed ) ) {
			return;
		}

		$status = isset( $parsed['status'] ) ? (string) $parsed['status'] : '';
		if ( in_array( $status, array( 'completed', 'cancelled' ), true ) && empty( $parsed['plugin_quarantine_active'] ) ) {
			@unlink( __FILE__ ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
		}
	},
	9999
);
