<?php
/**
 * Embed optimizer.
 *
 * Disables WordPress oEmbed functionality on the frontend,
 * removing wp-embed.min.js (~10KB) and related discovery links.
 *
 * @package MonitorCat\Modules\Speed\Optimizer
 */

declare(strict_types=1);

namespace MonitorCat\Modules\Speed\Optimizer;

defined( 'ABSPATH' ) || exit;

use MonitorCat\Settings;

/**
 * Disables WordPress embed scripts and discovery on the frontend.
 */
final class EmbedOptimizer {

	/**
	 * Plugin settings.
	 *
	 * @var Settings
	 */
	private Settings $settings;

	/**
	 * Constructor.
	 *
	 * @param Settings $settings Plugin settings.
	 */
	public function __construct( Settings $settings ) {
		$this->settings = $settings;
	}

	/**
	 * Register hooks if the optimization is enabled.
	 */
	public function boot(): void {
		if ( ! $this->settings->get( 'speed.optimize_embeds', true ) ) {
			return;
		}

		if ( is_admin() ) {
			return;
		}

		// Remove the embed script.
		add_action( 'wp_footer', array( $this, 'deregister_embed_script' ) );

		// Remove oEmbed-specific discovery links.
		remove_action( 'wp_head', 'wp_oembed_add_host_js' );

		// Remove the oEmbed REST API route filter (keeps the route but removes auto-discovery).
		remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 );
		remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );

		// Disable oEmbed auto-discovery for this site's own posts.
		add_filter( 'embed_oembed_discover', '__return_false' );
	}

	/**
	 * Deregister the wp-embed script on the frontend.
	 */
	public function deregister_embed_script(): void {
		wp_deregister_script( 'wp-embed' );
	}
}
