<?php
namespace SearchShifter\Core;

if (!defined('ABSPATH')) exit;

class SyncEngine {

    private static $queue = [];
    private static $max_concurrent = 3;

    /**
     * Initialize Smart Sync Engine
     */
    public static function init() {
        // Check if license is Pro or higher
        if (!self::is_pro_license()) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
               
            }

            return;
        }

        // Hook into WordPress content changes
        add_action('save_post', [__CLASS__, 'on_content_change'], 10, 3);
        add_action('delete_post', function ($post_ID) {
            self::on_content_change($post_ID, null, null);
        }, 10, 1);


       

    }

    /**
     * Check if the current license is Pro or higher
     */
    private static function is_pro_license() {
        if (!class_exists('\SS_Licensing')) {
            return false;
        }
        $license = \SS_Licensing::get_cached_status();
        $plan = strtolower($license['plan'] ?? 'free');
        return in_array($plan, ['pro', 'authority', 'elite'], true);
    }

    /**
     * Triggered when a post/page is created, updated, or deleted
     */
    public static function on_content_change($post_ID, $post, $update = null) {
        if (wp_is_post_revision($post_ID)) return;
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;

        self::$queue[] = $post_ID;

        if (count(self::$queue) <= self::$max_concurrent) {
            self::process_queue();
        }
    }


    /**
     * Process all queued content updates
     */
    private static function process_queue() {
        foreach (self::$queue as $post_ID) {
            self::sync_post($post_ID);
        }
        self::$queue = [];
    }

    /**
     * Write llms.txt, ai.txt, glossary.json, schema.json
     */
    private static function sync_post($post_ID) {
        $title   = get_the_title($post_ID);
        $url     = get_permalink($post_ID);
        $content = wp_strip_all_tags(get_post_field('post_content', $post_ID));

        // --- llms.txt ---
        self::safe_write(ABSPATH . 'llms.txt', "URL: $url\nTITLE: $title\n\n");

        // --- ai.txt ---
        self::safe_write(ABSPATH . 'ai.txt', "AI VISIBILITY: ENABLED\nURL: $url\n\n");

        // --- glossary.json ---
        $glossary_path = ABSPATH . 'glossary.json';
        $glossary_data = ['term' => $title, 'definition' => $content];
        self::safe_json_append($glossary_path, $glossary_data);

        // --- schema.json ---
        $schema_path = ABSPATH . 'schema.json';
        $schema_data = [
            "@context" => "https://schema.org",
            "@type"    => "WebPage",
            "headline" => $title,
            "url"      => $url
        ];
        self::safe_json_append($schema_path, $schema_data);

      

    }

    /**
     * Safely write data to file with retries
     */
    private static function safe_write($path, $data) {
        $retries = 3;
        while ($retries--) {
            $result = @file_put_contents($path, $data, FILE_APPEND | LOCK_EX);
            if ($result !== false) return true;
            sleep(1);
        }
       
        return false;
    }

    /**
     * Safely append to JSON file
     */
    private static function safe_json_append($path, $data) {
        $existing = [];
        if (file_exists($path)) {
            $existing = json_decode(file_get_contents($path), true) ?: [];
        }
        $existing[] = $data;
        file_put_contents($path, json_encode($existing, JSON_PRETTY_PRINT));
    }
}
