<?php
/**
 * Custom fields configuration loader.
 *
 * @package WPR_Translate
 */

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

/**
 * Retrieve the absolute path to the active theme custom fields configuration file.
 *
 * @return string
 */
function wpr_translate_get_custom_fields_config_path() {
    // Use the active theme directory for configuration lookups.
    $theme_directory = get_stylesheet_directory();

    if ( empty( $theme_directory ) ) {
        // No theme directory means no config file.
        return '';
    }

    // Build the expected config file path.
    return trailingslashit( $theme_directory ) . 'wpr/custom-fields-config.json';
}

/**
 * Calculate the hash of the custom fields configuration file.
 *
 * @return string
 */
function wpr_translate_get_custom_fields_config_hash() {
    // Resolve the config file path for hashing.
    $config_path = wpr_translate_get_custom_fields_config_path();

    if ( empty( $config_path ) || ! file_exists( $config_path ) || ! is_readable( $config_path ) ) {
        // No readable file means no hash.
        return '';
    }

    // Read the file contents for hashing.
    $contents = file_get_contents( $config_path );

    if ( false === $contents ) {
        // Return empty hash when read fails.
        return '';
    }

    return md5( $contents );
}

/**
 * Synchronize the custom field preferences with the theme configuration file.
 *
 * @return array<string,mixed>
 */
function wpr_translate_sync_custom_fields_preferences() {
    // Initialize defaults for stored preferences.
    $option_name = 'wpr_cf_preferences';
    $cache_key   = 'wpr_cf_preferences';
    $cache_group = 'wpr_translate';
    $preferences = array(
        'hash'  => '',
        'rules' => array(),
    );

    $config_path = wpr_translate_get_custom_fields_config_path();

    if ( empty( $config_path ) || ! file_exists( $config_path ) || ! is_readable( $config_path ) ) {
        // Persist empty preferences when the config file is missing.
        update_option( $option_name, $preferences );
        wp_cache_set( $cache_key, $preferences, $cache_group );

        return $preferences;
    }

    $file_contents = file_get_contents( $config_path );

    if ( false === $file_contents ) {
        // Persist empty preferences when the file cannot be read.
        update_option( $option_name, $preferences );
        wp_cache_set( $cache_key, $preferences, $cache_group );

        return $preferences;
    }

    $decoded = wp_json_file_decode(
        $config_path,
        array(
            'associative' => true,
        )
    );

    if ( is_wp_error( $decoded ) || null === $decoded ) {
        // Default to an empty rules array when decode fails.
        $decoded = array();
    }

    if ( ! is_array( $decoded ) ) {
        // Cast non-array payloads to arrays for consistency.
        $decoded = (array) $decoded;
    }

    $preferences = array(
        'hash'  => md5( $file_contents ),
        'rules' => $decoded,
    );

    // Persist the latest preferences to options and cache.
    update_option( $option_name, $preferences );
    wp_cache_set( $cache_key, $preferences, $cache_group );

    return $preferences;
}

/**
 * Ensure the preferences are cached and in sync with the current configuration file.
 *
 * @return array<string,mixed>
 */
function wpr_translate_prime_custom_fields_preferences_cache() {
    // Load and compare cached preferences to the current file hash.
    $option_name = 'wpr_cf_preferences';
    $cache_key   = 'wpr_cf_preferences';
    $cache_group = 'wpr_translate';

    $current_hash = wpr_translate_get_custom_fields_config_hash();

    $cached = wp_cache_get( $cache_key, $cache_group );

    if ( is_array( $cached ) ) {
        $cached_hash = isset( $cached['hash'] ) ? (string) $cached['hash'] : '';

        if ( isset( $cached['rules'] ) && $cached_hash === $current_hash ) {
            // Cached preferences are up to date.
            return $cached;
        }
    }

    $stored      = get_option( $option_name );
    $stored      = is_array( $stored ) ? $stored : array();
    $stored_hash = isset( $stored['hash'] ) ? (string) $stored['hash'] : '';

    if ( isset( $stored['rules'] ) && $stored_hash === $current_hash ) {
        // Promote stored preferences into cache when they match.
        wp_cache_set( $cache_key, $stored, $cache_group );

        return $stored;
    }

    return wpr_translate_sync_custom_fields_preferences();
}

/**
 * Retrieve the currently cached custom field preferences.
 *
 * @return array<string,mixed>
 */
function wpr_translate_get_custom_fields_preferences() {
    // Return cached preferences when available.
    $cache_key   = 'wpr_cf_preferences';
    $cache_group = 'wpr_translate';

    $cached = wp_cache_get( $cache_key, $cache_group );

    if ( false !== $cached ) {
        // Cache hit.
        return $cached;
    }

    // Prime cache and return latest preferences.
    return wpr_translate_prime_custom_fields_preferences_cache();
}
