<?php
defined( 'ABSPATH' ) || exit;

/**
 * REEID — save_post sandbox
 * Temporarily disables third-party save_post listeners
 * during translation to avoid SEO / analytics crashes.
 */

if ( ! function_exists( 'reeid_save_post_sandbox_begin' ) ) {
    function reeid_save_post_sandbox_begin() {
        if ( ! doing_action( 'wp_ajax_reeid_translate_openai' ) ) {
            return;
        }

        global $wp_filter;

        if ( empty( $wp_filter['save_post'] ) ) {
            return;
        }

        foreach ( $wp_filter['save_post']->callbacks as $prio => $callbacks ) {
            foreach ( $callbacks as $id => $cb ) {
                if ( empty( $cb['function'] ) ) {
                    continue;
                }

                // Keep REEID callbacks only
                if (
                    is_string( $cb['function'] ) &&
                    str_starts_with( $cb['function'], 'reeid_' )
                ) {
                    continue;
                }

                remove_action( 'save_post', $cb['function'], $prio );
            }
        }
    }
}

if ( ! function_exists( 'reeid_save_post_sandbox_end' ) ) {
    function reeid_save_post_sandbox_end() {
        // noop for now — page reload restores hooks
    }
}

add_action( 'wp_ajax_reeid_translate_openai', 'reeid_save_post_sandbox_begin', 0 );
add_action( 'wp_ajax_reeid_translate_openai', 'reeid_save_post_sandbox_end', 999 );
