/**
 * Inqyra Post Auto-Index
 *
 * Automatically crawls and generates embeddings after a published post
 * is saved. Triggered on the post-edit page reload after save.
 *
 * @package Inqyra
 */

(function($) {
    'use strict';

    var config = window.inqyraPostAutoIndex || {};
    if (!config.ajaxUrl || !config.nonce || !config.postId) {
        return;
    }

    // Step 1: Crawl the post server-side
    $.ajax({
        url: config.ajaxUrl,
        type: 'POST',
        data: {
            action: 'inqyra_crawl_single_post',
            nonce: config.nonce,
            post_id: config.postId
        },
        success: function(response) {
            if (!response.success || !response.data || response.data.chunks_created < 1) {
                return;
            }

            // Step 2: Generate embeddings
            waitForEmbeddingsModule(function() {
                window.inqyraEmbeddings.processEmbeddings(
                    config.ajaxUrl,
                    config.nonce,
                    response.data.agent_id,
                    function() {}
                );
            });
        }
    });

    function waitForEmbeddingsModule(callback) {
        if (window.inqyraEmbeddings) {
            callback();
            return;
        }
        var check = setInterval(function() {
            if (window.inqyraEmbeddings) {
                clearInterval(check);
                callback();
            }
        }, 300);
        setTimeout(function() { clearInterval(check); }, 60000);
    }

})(jQuery);
