json_eval_rs/
lib.rs

1//! JSON Eval RS - High-performance JSON Logic evaluation library
2//!
3//! This library provides a complete implementation of JSON Logic with advanced features:
4//! - Pre-compilation of logic expressions for optimal performance
5//! - Mutation tracking via proxy-like data wrapper (EvalData)
6//! - All data mutations gated through EvalData for thread safety
7//! - Zero external logic dependencies (built from scratch)
8
9// Use mimalloc allocator on Windows for better performance
10#[cfg(windows)]
11#[global_allocator]
12static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
13
14pub mod rlogic;
15pub mod table_evaluate;
16pub mod table_metadata;
17pub mod topo_sort;
18pub mod parse_schema;
19
20pub mod parsed_schema;
21pub mod parsed_schema_cache;
22pub mod json_parser;
23pub mod path_utils;
24pub mod eval_data;
25pub mod eval_cache;
26pub mod subform_methods;
27
28// FFI module for C# and other languages
29#[cfg(feature = "ffi")]
30pub mod ffi;
31
32// WebAssembly module for JavaScript/TypeScript
33#[cfg(feature = "wasm")]
34pub mod wasm;
35
36// Re-export main types for convenience
37use indexmap::{IndexMap, IndexSet};
38pub use rlogic::{
39    CompiledLogic, CompiledLogicStore, Evaluator,
40    LogicId, RLogic, RLogicConfig,
41    CompiledLogicId, CompiledLogicStoreStats,
42};
43use serde::{Deserialize, Serialize};
44pub use table_metadata::TableMetadata;
45pub use path_utils::ArrayMetadata;
46pub use eval_data::EvalData;
47pub use eval_cache::{EvalCache, CacheKey, CacheStats};
48pub use parsed_schema::ParsedSchema;
49pub use parsed_schema_cache::{ParsedSchemaCache, ParsedSchemaCacheStats, PARSED_SCHEMA_CACHE};
50use serde::de::Error as _;
51
52/// Return format for path-based methods
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
54pub enum ReturnFormat {
55    /// Nested object preserving the path hierarchy (default)
56    /// Example: { "user": { "profile": { "name": "John" } } }
57    #[default]
58    Nested,
59    /// Flat object with dotted keys
60    /// Example: { "user.profile.name": "John" }
61    Flat,
62    /// Array of values in the order of requested paths
63    /// Example: ["John"]
64    Array,
65}
66use serde_json::{Value};
67
68#[cfg(feature = "parallel")]
69use rayon::prelude::*;
70
71use std::mem;
72use std::sync::{Arc, Mutex};
73use std::time::Instant;
74use std::cell::RefCell;
75
76// Timing infrastructure
77thread_local! {
78    static TIMING_ENABLED: RefCell<bool> = RefCell::new(std::env::var("JSONEVAL_TIMING").is_ok());
79    static TIMING_DATA: RefCell<Vec<(String, std::time::Duration)>> = RefCell::new(Vec::new());
80}
81
82/// Check if timing is enabled
83#[inline]
84fn is_timing_enabled() -> bool {
85    TIMING_ENABLED.with(|enabled| *enabled.borrow())
86}
87
88/// Enable timing programmatically (in addition to JSONEVAL_TIMING environment variable)
89pub fn enable_timing() {
90    TIMING_ENABLED.with(|enabled| {
91        *enabled.borrow_mut() = true;
92    });
93}
94
95/// Disable timing
96pub fn disable_timing() {
97    TIMING_ENABLED.with(|enabled| {
98        *enabled.borrow_mut() = false;
99    });
100}
101
102/// Record timing data
103#[inline]
104fn record_timing(label: &str, duration: std::time::Duration) {
105    if is_timing_enabled() {
106        TIMING_DATA.with(|data| {
107            data.borrow_mut().push((label.to_string(), duration));
108        });
109    }
110}
111
112/// Print timing summary
113pub fn print_timing_summary() {
114    if !is_timing_enabled() {
115        return;
116    }
117    
118    TIMING_DATA.with(|data| {
119        let timings = data.borrow();
120        if timings.is_empty() {
121            return;
122        }
123        
124        eprintln!("\nšŸ“Š Timing Summary (JSONEVAL_TIMING enabled)");
125        eprintln!("{}", "=".repeat(60));
126        
127        let mut total = std::time::Duration::ZERO;
128        for (label, duration) in timings.iter() {
129            eprintln!("{:40} {:>12?}", label, duration);
130            total += *duration;
131        }
132        
133        eprintln!("{}", "=".repeat(60));
134        eprintln!("{:40} {:>12?}", "TOTAL", total);
135        eprintln!();
136    });
137}
138
139/// Clear timing data
140pub fn clear_timing_data() {
141    TIMING_DATA.with(|data| {
142        data.borrow_mut().clear();
143    });
144}
145
146/// Macro for timing a block of code
147macro_rules! time_block {
148    ($label:expr, $block:block) => {{
149        let _start = if is_timing_enabled() {
150            Some(Instant::now())
151        } else {
152            None
153        };
154        let result = $block;
155        if let Some(start) = _start {
156            record_timing($label, start.elapsed());
157        }
158        result
159    }};
160}
161
162/// Get the library version
163pub fn version() -> &'static str {
164    env!("CARGO_PKG_VERSION")
165}
166
167/// Clean floating point noise from JSON values
168/// Converts values very close to zero (< 1e-10) to exactly 0
169fn clean_float_noise(value: Value) -> Value {
170    const EPSILON: f64 = 1e-10;
171    
172    match value {
173        Value::Number(n) => {
174            if let Some(f) = n.as_f64() {
175                if f.abs() < EPSILON {
176                    // Clean near-zero values to exactly 0
177                    Value::Number(serde_json::Number::from(0))
178                } else if f.fract().abs() < EPSILON {
179                    // Clean whole numbers: 33.0 → 33
180                    Value::Number(serde_json::Number::from(f.round() as i64))
181                } else {
182                    Value::Number(n)
183                }
184            } else {
185                Value::Number(n)
186            }
187        }
188        Value::Array(arr) => {
189            Value::Array(arr.into_iter().map(clean_float_noise).collect())
190        }
191        Value::Object(obj) => {
192            Value::Object(obj.into_iter().map(|(k, v)| (k, clean_float_noise(v))).collect())
193        }
194        _ => value,
195    }
196}
197
198/// Dependent item structure for transitive dependency tracking
199#[derive(Debug, Clone, Serialize, Deserialize)]
200pub struct DependentItem {
201    pub ref_path: String,
202    pub clear: Option<Value>,  // Can be $evaluation or boolean
203    pub value: Option<Value>,  // Can be $evaluation or primitive value
204}
205
206pub struct JSONEval {
207    pub schema: Arc<Value>,
208    pub engine: Arc<RLogic>,
209    /// Zero-copy Arc-wrapped collections (shared from ParsedSchema)
210    pub evaluations: Arc<IndexMap<String, LogicId>>,
211    pub tables: Arc<IndexMap<String, Value>>,
212    /// Pre-compiled table metadata (computed at parse time for zero-copy evaluation)
213    pub table_metadata: Arc<IndexMap<String, TableMetadata>>,
214    pub dependencies: Arc<IndexMap<String, IndexSet<String>>>,
215    /// Evaluations grouped into parallel-executable batches
216    /// Each inner Vec contains evaluations that can run concurrently
217    pub sorted_evaluations: Arc<Vec<Vec<String>>>,
218    /// Evaluations categorized for result handling
219    /// Dependents: map from source field to list of dependent items
220    pub dependents_evaluations: Arc<IndexMap<String, Vec<DependentItem>>>,
221    /// Rules: evaluations with "/rules/" in path
222    pub rules_evaluations: Arc<Vec<String>>,
223    /// Fields with rules: dotted paths of all fields that have rules (for efficient validation)
224    pub fields_with_rules: Arc<Vec<String>>,
225    /// Others: all other evaluations not in sorted_evaluations (for evaluated_schema output)
226    pub others_evaluations: Arc<Vec<String>>,
227    /// Value: evaluations ending with ".value" in path
228    pub value_evaluations: Arc<Vec<String>>,
229    /// Cached layout paths (collected at parse time)
230    pub layout_paths: Arc<Vec<String>>,
231    /// Options URL templates (url_path, template_str, params_path) collected at parse time
232    pub options_templates: Arc<Vec<(String, String, String)>>,
233    /// Subforms: isolated JSONEval instances for array fields with items
234    /// Key is the schema path (e.g., "#/riders"), value is the sub-JSONEval
235    pub subforms: IndexMap<String, Box<JSONEval>>,
236    pub context: Value,
237    pub data: Value,
238    pub evaluated_schema: Value,
239    pub eval_data: EvalData,
240    /// Evaluation cache with content-based hashing and zero-copy storage
241    pub eval_cache: EvalCache,
242    /// Flag to enable/disable evaluation caching
243    /// Set to false for web API usage where each request creates a new JSONEval instance
244    pub cache_enabled: bool,
245    /// Mutex for synchronous execution of evaluate and evaluate_dependents
246    eval_lock: Mutex<()>,
247    /// Cached MessagePack bytes for zero-copy schema retrieval
248    /// Stores original MessagePack if initialized from binary, cleared on schema mutations
249    cached_msgpack_schema: Option<Vec<u8>>,
250}
251
252impl Clone for JSONEval {
253    fn clone(&self) -> Self {
254        Self {
255            cache_enabled: self.cache_enabled,
256            schema: Arc::clone(&self.schema),
257            engine: Arc::clone(&self.engine),
258            evaluations: self.evaluations.clone(),
259            tables: self.tables.clone(),
260            table_metadata: self.table_metadata.clone(),
261            dependencies: self.dependencies.clone(),
262            sorted_evaluations: self.sorted_evaluations.clone(),
263            dependents_evaluations: self.dependents_evaluations.clone(),
264            rules_evaluations: self.rules_evaluations.clone(),
265            fields_with_rules: self.fields_with_rules.clone(),
266            others_evaluations: self.others_evaluations.clone(),
267            value_evaluations: self.value_evaluations.clone(),
268            layout_paths: self.layout_paths.clone(),
269            options_templates: self.options_templates.clone(),
270            subforms: self.subforms.clone(),
271            context: self.context.clone(),
272            data: self.data.clone(),
273            evaluated_schema: self.evaluated_schema.clone(),
274            eval_data: self.eval_data.clone(),
275            eval_cache: EvalCache::new(), // Create fresh cache for the clone
276            eval_lock: Mutex::new(()), // Create fresh mutex for the clone
277            cached_msgpack_schema: self.cached_msgpack_schema.clone(),
278        }
279    }
280}
281
282impl JSONEval {
283    pub fn new(
284        schema: &str,
285        context: Option<&str>,
286        data: Option<&str>,
287    ) -> Result<Self, serde_json::Error> {
288        time_block!("JSONEval::new() [total]", {
289            // Use serde_json for schema (needs arbitrary_precision) and SIMD for data (needs speed)
290            let schema_val: Value = time_block!("  parse schema JSON", {
291                serde_json::from_str(schema)?
292            });
293            let context: Value = time_block!("  parse context JSON", {
294                json_parser::parse_json_str(context.unwrap_or("{}")).map_err(serde_json::Error::custom)?
295            });
296            let data: Value = time_block!("  parse data JSON", {
297                json_parser::parse_json_str(data.unwrap_or("{}")).map_err(serde_json::Error::custom)?
298            });
299            let evaluated_schema = schema_val.clone();
300            // Use default config: tracking enabled
301            let engine_config = RLogicConfig::default();
302
303            let mut instance = time_block!("  create instance struct", {
304                Self {
305                    schema: Arc::new(schema_val),
306                    evaluations: Arc::new(IndexMap::new()),
307                    tables: Arc::new(IndexMap::new()),
308                    table_metadata: Arc::new(IndexMap::new()),
309                    dependencies: Arc::new(IndexMap::new()),
310                    sorted_evaluations: Arc::new(Vec::new()),
311                    dependents_evaluations: Arc::new(IndexMap::new()),
312                    rules_evaluations: Arc::new(Vec::new()),
313                    fields_with_rules: Arc::new(Vec::new()),
314                    others_evaluations: Arc::new(Vec::new()),
315                    value_evaluations: Arc::new(Vec::new()),
316                    layout_paths: Arc::new(Vec::new()),
317                    options_templates: Arc::new(Vec::new()),
318                    subforms: IndexMap::new(),
319                    engine: Arc::new(RLogic::with_config(engine_config)),
320                    context: context.clone(),
321                    data: data.clone(),
322                    evaluated_schema: evaluated_schema.clone(),
323                    eval_data: EvalData::with_schema_data_context(&evaluated_schema, &data, &context),
324                    eval_cache: EvalCache::new(),
325                    cache_enabled: true, // Caching enabled by default
326                    eval_lock: Mutex::new(()),
327                    cached_msgpack_schema: None, // JSON initialization, no MessagePack cache
328                }
329            });
330            time_block!("  parse_schema", {
331                parse_schema::legacy::parse_schema(&mut instance).map_err(serde_json::Error::custom)?
332            });
333            Ok(instance)
334        })
335    }
336
337    /// Create a new JSONEval instance from MessagePack-encoded schema
338    /// 
339    /// # Arguments
340    /// 
341    /// * `schema_msgpack` - MessagePack-encoded schema bytes
342    /// * `context` - Optional JSON context string
343    /// * `data` - Optional JSON data string
344    /// 
345    /// # Returns
346    /// 
347    /// A Result containing the JSONEval instance or an error
348    pub fn new_from_msgpack(
349        schema_msgpack: &[u8],
350        context: Option<&str>,
351        data: Option<&str>,
352    ) -> Result<Self, String> {
353        // Store original MessagePack bytes for zero-copy retrieval
354        let cached_msgpack = schema_msgpack.to_vec();
355        
356        // Deserialize MessagePack schema to Value
357        let schema_val: Value = rmp_serde::from_slice(schema_msgpack)
358            .map_err(|e| format!("Failed to deserialize MessagePack schema: {}", e))?;
359        
360        let context: Value = json_parser::parse_json_str(context.unwrap_or("{}"))
361            .map_err(|e| format!("Failed to parse context: {}", e))?;
362        let data: Value = json_parser::parse_json_str(data.unwrap_or("{}"))
363            .map_err(|e| format!("Failed to parse data: {}", e))?;
364        let evaluated_schema = schema_val.clone();
365        let engine_config = RLogicConfig::default();
366
367        let mut instance = Self {
368            schema: Arc::new(schema_val),
369            evaluations: Arc::new(IndexMap::new()),
370            tables: Arc::new(IndexMap::new()),
371            table_metadata: Arc::new(IndexMap::new()),
372            dependencies: Arc::new(IndexMap::new()),
373            sorted_evaluations: Arc::new(Vec::new()),
374            dependents_evaluations: Arc::new(IndexMap::new()),
375            rules_evaluations: Arc::new(Vec::new()),
376            fields_with_rules: Arc::new(Vec::new()),
377            others_evaluations: Arc::new(Vec::new()),
378            value_evaluations: Arc::new(Vec::new()),
379            layout_paths: Arc::new(Vec::new()),
380            options_templates: Arc::new(Vec::new()),
381            subforms: IndexMap::new(),
382            engine: Arc::new(RLogic::with_config(engine_config)),
383            context: context.clone(),
384            data: data.clone(),
385            evaluated_schema: evaluated_schema.clone(),
386            eval_data: EvalData::with_schema_data_context(&evaluated_schema, &data, &context),
387            eval_cache: EvalCache::new(),
388            cache_enabled: true, // Caching enabled by default
389            eval_lock: Mutex::new(()),
390            cached_msgpack_schema: Some(cached_msgpack), // Store for zero-copy retrieval
391        };
392        parse_schema::legacy::parse_schema(&mut instance)?;
393        Ok(instance)
394    }
395
396    /// Create a new JSONEval instance from a pre-parsed ParsedSchema
397    /// 
398    /// This enables schema caching: parse once, reuse across multiple evaluations with different data/context.
399    /// 
400    /// # Arguments
401    /// 
402    /// * `parsed` - Arc-wrapped pre-parsed schema (can be cloned and cached)
403    /// * `context` - Optional JSON context string
404    /// * `data` - Optional JSON data string
405    /// 
406    /// # Returns
407    /// 
408    /// A Result containing the JSONEval instance or an error
409    /// 
410    /// # Example
411    /// 
412    /// ```ignore
413    /// use std::sync::Arc;
414    /// 
415    /// // Parse schema once and wrap in Arc for caching
416    /// let parsed = Arc::new(ParsedSchema::parse(schema_str)?);
417    /// cache.insert(schema_key, parsed.clone());
418    /// 
419    /// // Reuse across multiple evaluations (Arc::clone is cheap)
420    /// let eval1 = JSONEval::with_parsed_schema(parsed.clone(), Some(context1), Some(data1))?;
421    /// let eval2 = JSONEval::with_parsed_schema(parsed.clone(), Some(context2), Some(data2))?;
422    /// ```
423    pub fn with_parsed_schema(
424        parsed: Arc<ParsedSchema>,
425        context: Option<&str>,
426        data: Option<&str>,
427    ) -> Result<Self, String> {
428        let context: Value = json_parser::parse_json_str(context.unwrap_or("{}"))
429            .map_err(|e| format!("Failed to parse context: {}", e))?;
430        let data: Value = json_parser::parse_json_str(data.unwrap_or("{}"))
431            .map_err(|e| format!("Failed to parse data: {}", e))?;
432        
433        let evaluated_schema = parsed.schema.clone();
434        
435        // Share the engine Arc (cheap pointer clone, not data clone)
436        // Multiple JSONEval instances created from the same ParsedSchema will share the compiled RLogic
437        let engine = parsed.engine.clone();
438        
439        // Convert Arc<ParsedSchema> subforms to Box<JSONEval> subforms
440        // This is a one-time conversion when creating JSONEval from ParsedSchema
441        let mut subforms = IndexMap::new();
442        for (path, subform_parsed) in &parsed.subforms {
443            // Create JSONEval from the cached ParsedSchema
444            let subform_eval = JSONEval::with_parsed_schema(
445                subform_parsed.clone(),
446                Some("{}"),
447                None
448            )?;
449            subforms.insert(path.clone(), Box::new(subform_eval));
450        }
451        
452        let instance = Self {
453            schema: Arc::clone(&parsed.schema),
454            // Zero-copy Arc clones (just increments reference count, no data copying)
455            evaluations: Arc::clone(&parsed.evaluations),
456            tables: Arc::clone(&parsed.tables),
457            table_metadata: Arc::clone(&parsed.table_metadata),
458            dependencies: Arc::clone(&parsed.dependencies),
459            sorted_evaluations: Arc::clone(&parsed.sorted_evaluations),
460            dependents_evaluations: Arc::clone(&parsed.dependents_evaluations),
461            rules_evaluations: Arc::clone(&parsed.rules_evaluations),
462            fields_with_rules: Arc::clone(&parsed.fields_with_rules),
463            others_evaluations: Arc::clone(&parsed.others_evaluations),
464            value_evaluations: Arc::clone(&parsed.value_evaluations),
465            layout_paths: Arc::clone(&parsed.layout_paths),
466            options_templates: Arc::clone(&parsed.options_templates),
467            subforms,
468            engine,
469            context: context.clone(),
470            data: data.clone(),
471            evaluated_schema: (*evaluated_schema).clone(),
472            eval_data: EvalData::with_schema_data_context(&evaluated_schema, &data, &context),
473            eval_cache: EvalCache::new(),
474            cache_enabled: true, // Caching enabled by default
475            eval_lock: Mutex::new(()),
476            cached_msgpack_schema: None, // No MessagePack cache for parsed schema
477        };
478        
479        Ok(instance)
480    }
481
482    pub fn reload_schema(
483        &mut self,
484        schema: &str,
485        context: Option<&str>,
486        data: Option<&str>,
487    ) -> Result<(), String> {
488        // Use serde_json for schema (precision) and SIMD for data (speed)
489        let schema_val: Value = serde_json::from_str(schema).map_err(|e| format!("failed to parse schema: {e}"))?;
490        let context: Value = json_parser::parse_json_str(context.unwrap_or("{}"))?;
491        let data: Value = json_parser::parse_json_str(data.unwrap_or("{}"))?;
492        self.schema = Arc::new(schema_val);
493        self.context = context.clone();
494        self.data = data.clone();
495        self.evaluated_schema = (*self.schema).clone();
496        self.engine = Arc::new(RLogic::new());
497        self.dependents_evaluations = Arc::new(IndexMap::new());
498        self.rules_evaluations = Arc::new(Vec::new());
499        self.fields_with_rules = Arc::new(Vec::new());
500        self.others_evaluations = Arc::new(Vec::new());
501        self.value_evaluations = Arc::new(Vec::new());
502        self.layout_paths = Arc::new(Vec::new());
503        self.options_templates = Arc::new(Vec::new());
504        self.subforms.clear();
505        parse_schema::legacy::parse_schema(self)?;
506        
507        // Re-initialize eval_data with new schema, data, and context
508        self.eval_data = EvalData::with_schema_data_context(&self.evaluated_schema, &data, &context);
509        
510        // Clear cache when schema changes
511        self.eval_cache.clear();
512        
513        // Clear MessagePack cache since schema has been mutated
514        self.cached_msgpack_schema = None;
515
516        Ok(())
517    }
518
519    /// Set the timezone offset for datetime operations (TODAY, NOW)
520    /// 
521    /// This method updates the RLogic engine configuration with a new timezone offset.
522    /// The offset will be applied to all subsequent datetime evaluations.
523    /// 
524    /// # Arguments
525    /// 
526    /// * `offset_minutes` - Timezone offset in minutes from UTC (e.g., 420 for UTC+7, -300 for UTC-5)
527    ///   Pass `None` to reset to UTC (no offset)
528    /// 
529    /// # Example
530    /// 
531    /// ```ignore
532    /// let mut eval = JSONEval::new(schema, None, None)?;
533    /// 
534    /// // Set to UTC+7 (Jakarta, Bangkok)
535    /// eval.set_timezone_offset(Some(420));
536    /// 
537    /// // Reset to UTC
538    /// eval.set_timezone_offset(None);
539    /// ```
540    pub fn set_timezone_offset(&mut self, offset_minutes: Option<i32>) {
541        // Create new config with the timezone offset
542        let mut config = RLogicConfig::default();
543        if let Some(offset) = offset_minutes {
544            config = config.with_timezone_offset(offset);
545        }
546        
547        // Recreate the engine with the new configuration
548        // This is necessary because RLogic is wrapped in Arc and config is part of the evaluator
549        self.engine = Arc::new(RLogic::with_config(config));
550        
551        // Note: We need to recompile all evaluations because they're associated with the old engine
552        // Re-parse the schema to recompile all evaluations with the new engine
553        let _ = parse_schema::legacy::parse_schema(self);
554        
555        // Clear cache since evaluation results may change with new timezone
556        self.eval_cache.clear();
557    }
558
559    /// Reload schema from MessagePack-encoded bytes
560    /// 
561    /// # Arguments
562    /// 
563    /// * `schema_msgpack` - MessagePack-encoded schema bytes
564    /// * `context` - Optional context data JSON string
565    /// * `data` - Optional initial data JSON string
566    /// 
567    /// # Returns
568    /// 
569    /// A `Result` indicating success or an error message
570    pub fn reload_schema_msgpack(
571        &mut self,
572        schema_msgpack: &[u8],
573        context: Option<&str>,
574        data: Option<&str>,
575    ) -> Result<(), String> {
576        // Deserialize MessagePack to Value
577        let schema_val: Value = rmp_serde::from_slice(schema_msgpack)
578            .map_err(|e| format!("failed to deserialize MessagePack schema: {e}"))?;
579        
580        let context: Value = json_parser::parse_json_str(context.unwrap_or("{}"))?;
581        let data: Value = json_parser::parse_json_str(data.unwrap_or("{}"))?;
582        
583        self.schema = Arc::new(schema_val);
584        self.context = context.clone();
585        self.data = data.clone();
586        self.evaluated_schema = (*self.schema).clone();
587        self.engine = Arc::new(RLogic::new());
588        self.dependents_evaluations = Arc::new(IndexMap::new());
589        self.rules_evaluations = Arc::new(Vec::new());
590        self.fields_with_rules = Arc::new(Vec::new());
591        self.others_evaluations = Arc::new(Vec::new());
592        self.value_evaluations = Arc::new(Vec::new());
593        self.layout_paths = Arc::new(Vec::new());
594        self.options_templates = Arc::new(Vec::new());
595        self.subforms.clear();
596        parse_schema::legacy::parse_schema(self)?;
597        
598        // Re-initialize eval_data
599        self.eval_data = EvalData::with_schema_data_context(&self.evaluated_schema, &data, &context);
600        
601        // Clear cache when schema changes
602        self.eval_cache.clear();
603        
604        // Cache the MessagePack for future retrievals
605        self.cached_msgpack_schema = Some(schema_msgpack.to_vec());
606
607        Ok(())
608    }
609
610    /// Reload schema from a cached ParsedSchema
611    /// 
612    /// This is the most efficient way to reload as it reuses pre-parsed schema compilation.
613    /// 
614    /// # Arguments
615    /// 
616    /// * `parsed` - Arc reference to a cached ParsedSchema
617    /// * `context` - Optional context data JSON string
618    /// * `data` - Optional initial data JSON string
619    /// 
620    /// # Returns
621    /// 
622    /// A `Result` indicating success or an error message
623    pub fn reload_schema_parsed(
624        &mut self,
625        parsed: Arc<ParsedSchema>,
626        context: Option<&str>,
627        data: Option<&str>,
628    ) -> Result<(), String> {
629        let context: Value = json_parser::parse_json_str(context.unwrap_or("{}"))?;
630        let data: Value = json_parser::parse_json_str(data.unwrap_or("{}"))?;
631        
632        // Share all the pre-compiled data from ParsedSchema
633        self.schema = Arc::clone(&parsed.schema);
634        self.evaluations = parsed.evaluations.clone();
635        self.tables = parsed.tables.clone();
636        self.table_metadata = parsed.table_metadata.clone();
637        self.dependencies = parsed.dependencies.clone();
638        self.sorted_evaluations = parsed.sorted_evaluations.clone();
639        self.dependents_evaluations = parsed.dependents_evaluations.clone();
640        self.rules_evaluations = parsed.rules_evaluations.clone();
641        self.fields_with_rules = parsed.fields_with_rules.clone();
642        self.others_evaluations = parsed.others_evaluations.clone();
643        self.value_evaluations = parsed.value_evaluations.clone();
644        self.layout_paths = parsed.layout_paths.clone();
645        self.options_templates = parsed.options_templates.clone();
646        
647        // Share the engine Arc (cheap pointer clone, not data clone)
648        self.engine = parsed.engine.clone();
649        
650        // Convert Arc<ParsedSchema> subforms to Box<JSONEval> subforms
651        let mut subforms = IndexMap::new();
652        for (path, subform_parsed) in &parsed.subforms {
653            let subform_eval = JSONEval::with_parsed_schema(
654                subform_parsed.clone(),
655                Some("{}"),
656                None
657            )?;
658            subforms.insert(path.clone(), Box::new(subform_eval));
659        }
660        self.subforms = subforms;
661        
662        self.context = context.clone();
663        self.data = data.clone();
664        self.evaluated_schema = (*self.schema).clone();
665        
666        // Re-initialize eval_data
667        self.eval_data = EvalData::with_schema_data_context(&self.evaluated_schema, &data, &context);
668        
669        // Clear cache when schema changes
670        self.eval_cache.clear();
671        
672        // Clear MessagePack cache since we're loading from ParsedSchema
673        self.cached_msgpack_schema = None;
674
675        Ok(())
676    }
677
678    /// Reload schema from ParsedSchemaCache using a cache key
679    /// 
680    /// This is the recommended way for cross-platform cached schema reloading.
681    /// 
682    /// # Arguments
683    /// 
684    /// * `cache_key` - Key to lookup in the global ParsedSchemaCache
685    /// * `context` - Optional context data JSON string
686    /// * `data` - Optional initial data JSON string
687    /// 
688    /// # Returns
689    /// 
690    /// A `Result` indicating success or an error message
691    pub fn reload_schema_from_cache(
692        &mut self,
693        cache_key: &str,
694        context: Option<&str>,
695        data: Option<&str>,
696    ) -> Result<(), String> {
697        // Get the cached ParsedSchema from global cache
698        let parsed = PARSED_SCHEMA_CACHE.get(cache_key)
699            .ok_or_else(|| format!("Schema '{}' not found in cache", cache_key))?;
700        
701        // Use reload_schema_parsed with the cached schema
702        self.reload_schema_parsed(parsed, context, data)
703    }
704
705    /// Evaluate the schema with the given data and context.
706    ///
707    /// # Arguments
708    ///
709    /// * `data` - The data to evaluate.
710    /// * `context` - The context to evaluate.
711    ///
712    /// # Returns
713    ///
714    /// A `Result` indicating success or an error message.
715    pub fn evaluate(&mut self, data: &str, context: Option<&str>, paths: Option<&[String]>) -> Result<(), String> {
716        time_block!("evaluate() [total]", {
717            // Use SIMD-accelerated JSON parsing
718            let data: Value = time_block!("  parse data", {
719                json_parser::parse_json_str(data)?
720            });
721            let context: Value = time_block!("  parse context", {
722                json_parser::parse_json_str(context.unwrap_or("{}"))?
723            });
724                
725            self.data = data.clone();
726            
727            // Collect top-level data keys to selectively purge cache
728            let changed_data_paths: Vec<String> = if let Some(obj) = data.as_object() {
729                obj.keys().map(|k| k.clone()).collect()
730            } else {
731                Vec::new()
732            };
733            
734            // Replace data and context in existing eval_data
735            time_block!("  replace_data_and_context", {
736                self.eval_data.replace_data_and_context(data, context);
737            });
738            
739            // Selectively purge cache entries that depend on changed top-level data keys
740            // This is more efficient than clearing entire cache
741            time_block!("  purge_cache", {
742                self.purge_cache_for_changed_data(&changed_data_paths);
743            });
744            
745            // Call internal evaluate (uses existing data if not provided)
746            self.evaluate_internal(paths)
747        })
748    }
749    
750    /// Internal evaluate that can be called when data is already set
751    /// This avoids double-locking and unnecessary data cloning for re-evaluation from evaluate_dependents
752    fn evaluate_internal(&mut self, paths: Option<&[String]>) -> Result<(), String> {
753        time_block!("  evaluate_internal() [total]", {
754            // Acquire lock for synchronous execution
755            let _lock = self.eval_lock.lock().unwrap();
756
757            // Normalize paths to schema pointers for correct filtering
758            let normalized_paths_storage; // Keep alive
759            let normalized_paths = if let Some(p_list) = paths {
760                normalized_paths_storage = p_list.iter()
761                    .flat_map(|p| {
762                        let ptr = path_utils::dot_notation_to_schema_pointer(p);
763                        // Also support version with /properties/ prefix for root match
764                        let with_props = if ptr.starts_with("#/") {
765                             format!("#/properties/{}", &ptr[2..])
766                        } else {
767                             ptr.clone()
768                        };
769                        vec![ptr, with_props]
770                    })
771                    .collect::<Vec<_>>();
772                Some(normalized_paths_storage.as_slice())
773            } else {
774                None
775            };
776
777            // Clone sorted_evaluations (Arc clone is cheap, then clone inner Vec)
778            let eval_batches: Vec<Vec<String>> = (*self.sorted_evaluations).clone();
779
780            // Process each batch - parallelize evaluations within each batch
781            // Batches are processed sequentially to maintain dependency order
782            // Process value evaluations (simple computed fields)
783            // These are independent of rule batches and should always run
784            let eval_data_values = self.eval_data.clone();
785            time_block!("      evaluate values", {
786                #[cfg(feature = "parallel")]
787                if self.value_evaluations.len() > 100 {
788                    let value_results: Mutex<Vec<(String, Value)>> = Mutex::new(Vec::with_capacity(self.value_evaluations.len()));
789                    
790                    self.value_evaluations.par_iter().for_each(|eval_key| {
791                        // Filter items if paths are provided
792                        if let Some(filter_paths) = normalized_paths {
793                            if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
794                                return;
795                            }
796                        }
797    
798                        // For value evaluations (e.g. /properties/foo/value), we want the value at that path
799                        // The path in eval_key is like "#/properties/foo/value"
800                        let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
801                        
802                        // Try cache first (thread-safe)
803                        if let Some(_) = self.try_get_cached(eval_key, &eval_data_values) {
804                            return;
805                        }
806                        
807                        // Cache miss - evaluate
808                        if let Some(logic_id) = self.evaluations.get(eval_key) {
809                            if let Ok(val) = self.engine.run(logic_id, eval_data_values.data()) {
810                                let cleaned_val = clean_float_noise(val);
811                                // Cache result (thread-safe)
812                                self.cache_result(eval_key, Value::Null, &eval_data_values);
813                                value_results.lock().unwrap().push((pointer_path, cleaned_val));
814                            }
815                        }
816                    });
817    
818                    // Write results to evaluated_schema
819                    for (result_path, value) in value_results.into_inner().unwrap() {
820                        if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&result_path) {
821                            *pointer_value = value;
822                        }
823                    }
824                }
825
826                // Sequential execution for values (if not parallel or small count)
827                #[cfg(feature = "parallel")]
828                let value_eval_items = if self.value_evaluations.len() > 100 { &self.value_evaluations[0..0] } else { &self.value_evaluations };
829
830                #[cfg(not(feature = "parallel"))]
831                let value_eval_items = &self.value_evaluations;
832
833                for eval_key in value_eval_items.iter() {
834                    // Filter items if paths are provided
835                    if let Some(filter_paths) = normalized_paths {
836                        if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
837                            continue;
838                        }
839                    }
840
841                    let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
842                    
843                    // Try cache first
844                    if let Some(_) = self.try_get_cached(eval_key, &eval_data_values) {
845                        continue;
846                    }
847                    
848                    // Cache miss - evaluate
849                    if let Some(logic_id) = self.evaluations.get(eval_key) {
850                        if let Ok(val) = self.engine.run(logic_id, eval_data_values.data()) {
851                            let cleaned_val = clean_float_noise(val);
852                            println!("[DEBUG] Evaluated {} = {:?}", eval_key, cleaned_val);
853                            // Cache result
854                            self.cache_result(eval_key, Value::Null, &eval_data_values);
855                            
856                            println!("[DEBUG] pointer_path: {}", pointer_path);
857                            if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
858                                println!("[DEBUG] Successfully updated pointer");
859                                *pointer_value = cleaned_val;
860                            } else {
861                                println!("[DEBUG] Failed to find pointer in schema");
862                            }
863                        }
864                    } else {
865                        println!("[DEBUG] No logic_id found for {}", eval_key);
866                    }
867                }
868            });
869
870            time_block!("    process batches", {
871                for batch in eval_batches {
872            // Skip empty batches
873            if batch.is_empty() {
874                continue;
875            }
876            
877            // Check if we can skip this entire batch optimization
878            // If paths are provided, we can check if ANY item in batch matches ANY path
879            if let Some(filter_paths) = normalized_paths {
880                if !filter_paths.is_empty() {
881                    let batch_has_match = batch.iter().any(|eval_key| {
882                        filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str()))
883                    });
884                    if !batch_has_match {
885                        continue;
886                    }
887                }
888            }
889            
890            // No pre-checking cache - we'll check inside parallel execution
891            // This allows thread-safe cache access during parallel evaluation
892            
893            // Parallel execution within batch (no dependencies between items)
894            // Use Mutex for thread-safe result collection
895            // Store both eval_key and result for cache storage
896            let eval_data_snapshot = self.eval_data.clone();
897            
898            // Parallelize only if batch has multiple items (overhead not worth it for single item)
899
900            
901            #[cfg(feature = "parallel")]
902            if batch.len() > 1000 {
903                let results: Mutex<Vec<(String, String, Value)>> = Mutex::new(Vec::with_capacity(batch.len()));
904                batch.par_iter().for_each(|eval_key| {
905                    // Filter individual items if paths are provided
906                    if let Some(filter_paths) = normalized_paths {
907                        if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
908                            return;
909                        }
910                    }
911
912                    let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
913                    
914                    // Try cache first (thread-safe)
915                    if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
916                        return;
917                    }
918                    
919                    // Cache miss - evaluate
920                    let is_table = self.table_metadata.contains_key(eval_key);
921                    
922                    if is_table {
923                        // Evaluate table using sandboxed metadata (parallel-safe, immutable parent scope)
924                        if let Ok(rows) = table_evaluate::evaluate_table(self, eval_key, &eval_data_snapshot) {
925                            let value = Value::Array(rows);
926                            // Cache result (thread-safe)
927                            self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
928                            results.lock().unwrap().push((eval_key.clone(), pointer_path, value));
929                        }
930                    } else {
931                        if let Some(logic_id) = self.evaluations.get(eval_key) {
932                            // Evaluate directly with snapshot
933                            if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
934                                let cleaned_val = clean_float_noise(val);
935                                // Cache result (thread-safe)
936                                self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
937                                results.lock().unwrap().push((eval_key.clone(), pointer_path, cleaned_val));
938                            }
939                        }
940                    }
941                });
942                
943                // Write all results back sequentially (already cached in parallel execution)
944                for (_eval_key, path, value) in results.into_inner().unwrap() {
945                    let cleaned_value = clean_float_noise(value);
946                    
947                    self.eval_data.set(&path, cleaned_value.clone());
948                    // Also write to evaluated_schema
949                    if let Some(schema_value) = self.evaluated_schema.pointer_mut(&path) {
950                        *schema_value = cleaned_value;
951                    }
952                }
953                continue;
954            }
955            
956            // Sequential execution (single item or parallel feature disabled)
957            #[cfg(not(feature = "parallel"))]
958            let batch_items = &batch;
959            
960            #[cfg(feature = "parallel")]
961            let batch_items = if batch.len() > 1000 { &batch[0..0] } else { &batch }; // Empty slice if already processed in parallel
962            
963            for eval_key in batch_items {
964                // Filter individual items if paths are provided
965                if let Some(filter_paths) = paths {
966                    if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
967                        continue;
968                    }
969                }
970
971                let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
972                
973                // Try cache first
974                if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
975                    continue;
976                }
977                
978                // Cache miss - evaluate
979                let is_table = self.table_metadata.contains_key(eval_key);
980                
981                if is_table {
982                    if let Ok(rows) = table_evaluate::evaluate_table(self, eval_key, &eval_data_snapshot) {
983                        let value = Value::Array(rows);
984                        // Cache result
985                        self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
986                        
987                        let cleaned_value = clean_float_noise(value);
988                        self.eval_data.set(&pointer_path, cleaned_value.clone());
989                        if let Some(schema_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
990                            *schema_value = cleaned_value;
991                        }
992                    }
993                } else {
994                    if let Some(logic_id) = self.evaluations.get(eval_key) {
995                        if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
996                            let cleaned_val = clean_float_noise(val);
997                            // Cache result
998                            self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
999                            
1000                            self.eval_data.set(&pointer_path, cleaned_val.clone());
1001                            if let Some(schema_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
1002                                *schema_value = cleaned_val;
1003                            }
1004                        }
1005                    }
1006                }
1007            }
1008                }
1009            });
1010
1011            // Drop lock before calling evaluate_others
1012            drop(_lock);
1013            
1014            self.evaluate_others(paths);
1015
1016            Ok(())
1017        })
1018    }
1019
1020    /// Get the evaluated schema with optional layout resolution.
1021    ///
1022    /// # Arguments
1023    ///
1024    /// * `skip_layout` - Whether to skip layout resolution.
1025    ///
1026    /// # Returns
1027    ///
1028    /// The evaluated schema as a JSON value.
1029    pub fn get_evaluated_schema(&mut self, skip_layout: bool) -> Value {
1030        time_block!("get_evaluated_schema()", {
1031            if !skip_layout {
1032                self.resolve_layout_internal();
1033            }
1034            
1035            self.evaluated_schema.clone()
1036        })
1037    }
1038
1039    /// Get the evaluated schema as MessagePack binary format
1040    ///
1041    /// # Arguments
1042    ///
1043    /// * `skip_layout` - Whether to skip layout resolution.
1044    ///
1045    /// # Returns
1046    ///
1047    /// The evaluated schema serialized as MessagePack bytes
1048    ///
1049    /// # Zero-Copy Optimization
1050    ///
1051    /// This method serializes the evaluated schema to MessagePack. The resulting Vec<u8>
1052    /// is then passed to FFI/WASM boundaries via raw pointers (zero-copy at boundary).
1053    /// The serialization step itself (Value -> MessagePack) cannot be avoided but is
1054    /// highly optimized by rmp-serde.
1055    pub fn get_evaluated_schema_msgpack(&mut self, skip_layout: bool) -> Result<Vec<u8>, String> {
1056        if !skip_layout {
1057            self.resolve_layout_internal();
1058        }
1059        
1060        // Serialize evaluated schema to MessagePack
1061        // Note: This is the only copy required. The FFI layer then returns raw pointers
1062        // to this data for zero-copy transfer to calling code.
1063        rmp_serde::to_vec(&self.evaluated_schema)
1064            .map_err(|e| format!("Failed to serialize schema to MessagePack: {}", e))
1065    }
1066
1067    /// Get all schema values (evaluations ending with .value)
1068    /// Mutates self.data by overriding with values from value evaluations
1069    /// Returns the modified data
1070    pub fn get_schema_value(&mut self) -> Value {
1071        // Ensure self.data is an object
1072        if !self.data.is_object() {
1073            self.data = Value::Object(serde_json::Map::new());
1074        }
1075        
1076        // Override self.data with values from value evaluations
1077        for eval_key in self.value_evaluations.iter() {
1078            let clean_key = eval_key.replace("#", "");
1079            let path = clean_key.replace("/properties", "").replace("/value", "");
1080            
1081            // Get the value from evaluated_schema
1082            let value = match self.evaluated_schema.pointer(&clean_key) {
1083                Some(v) => v.clone(),
1084                None => continue,
1085            };
1086            
1087            // Parse the path and create nested structure as needed
1088            let path_parts: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
1089            
1090            if path_parts.is_empty() {
1091                continue;
1092            }
1093            
1094            // Navigate/create nested structure
1095            let mut current = &mut self.data;
1096            for (i, part) in path_parts.iter().enumerate() {
1097                let is_last = i == path_parts.len() - 1;
1098                
1099                if is_last {
1100                    // Set the value at the final key
1101                    if let Some(obj) = current.as_object_mut() {
1102                        obj.insert(part.to_string(), clean_float_noise(value.clone()));
1103                    }
1104                } else {
1105                    // Ensure current is an object, then navigate/create intermediate objects
1106                    if let Some(obj) = current.as_object_mut() {
1107                        current = obj.entry(part.to_string())
1108                            .or_insert_with(|| Value::Object(serde_json::Map::new()));
1109                    } else {
1110                        // Skip this path if current is not an object and can't be made into one
1111                        break;
1112                    }
1113                }
1114            }
1115        }
1116        
1117        clean_float_noise(self.data.clone())
1118    }
1119
1120    /// Get the evaluated schema without $params field.
1121    /// This method filters out $params from the root level only.
1122    ///
1123    /// # Arguments
1124    ///
1125    /// * `skip_layout` - Whether to skip layout resolution.
1126    ///
1127    /// # Returns
1128    ///
1129    /// The evaluated schema with $params removed.
1130    pub fn get_evaluated_schema_without_params(&mut self, skip_layout: bool) -> Value {
1131        if !skip_layout {
1132            self.resolve_layout_internal();
1133        }
1134        
1135        // Filter $params at root level only
1136        if let Value::Object(mut map) = self.evaluated_schema.clone() {
1137            map.remove("$params");
1138            Value::Object(map)
1139        } else {
1140            self.evaluated_schema.clone()
1141        }
1142    }
1143
1144    /// Get a value from the evaluated schema using dotted path notation.
1145    /// Converts dotted notation (e.g., "properties.field.value") to JSON pointer format.
1146    ///
1147    /// # Arguments
1148    ///
1149    /// * `path` - The dotted path to the value (e.g., "properties.field.value")
1150    /// * `skip_layout` - Whether to skip layout resolution.
1151    ///
1152    /// # Returns
1153    ///
1154    /// The value at the specified path, or None if not found.
1155    pub fn get_evaluated_schema_by_path(&mut self, path: &str, skip_layout: bool) -> Option<Value> {
1156        if !skip_layout {
1157            self.resolve_layout_internal();
1158        }
1159        
1160        // Convert dotted notation to JSON pointer
1161        let pointer = if path.is_empty() {
1162            "".to_string()
1163        } else {
1164            format!("/{}", path.replace(".", "/"))
1165        };
1166        
1167        self.evaluated_schema.pointer(&pointer).cloned()
1168    }
1169
1170    /// Get values from the evaluated schema using multiple dotted path notations.
1171    /// Returns data in the specified format. Skips paths that are not found.
1172    ///
1173    /// # Arguments
1174    ///
1175    /// * `paths` - Array of dotted paths to retrieve (e.g., ["properties.field1", "properties.field2"])
1176    /// * `skip_layout` - Whether to skip layout resolution.
1177    /// * `format` - Optional return format (Nested, Flat, or Array). Defaults to Nested.
1178    ///
1179    /// # Returns
1180    ///
1181    /// Data in the specified format, or an empty object/array if no paths are found.
1182    pub fn get_evaluated_schema_by_paths(&mut self, paths: &[String], skip_layout: bool, format: Option<ReturnFormat>) -> Value {
1183        let format = format.unwrap_or_default();
1184        if !skip_layout {
1185            self.resolve_layout_internal();
1186        }
1187        
1188        let mut result = serde_json::Map::new();
1189        
1190        for path in paths {
1191            // Convert dotted notation to JSON pointer
1192            let pointer = if path.is_empty() {
1193                "".to_string()
1194            } else {
1195                format!("/{}", path.replace(".", "/"))
1196            };
1197            
1198            // Get value at path, skip if not found
1199            if let Some(value) = self.evaluated_schema.pointer(&pointer) {
1200                // Store the full path structure to maintain the hierarchy
1201                // Clone only once per path
1202                self.insert_at_path(&mut result, path, value.clone());
1203            }
1204        }
1205        
1206        self.convert_to_format(result, paths, format)
1207    }
1208    
1209    /// Helper function to insert a value at a dotted path in a JSON object
1210    fn insert_at_path(&self, obj: &mut serde_json::Map<String, Value>, path: &str, value: Value) {
1211        if path.is_empty() {
1212            // If path is empty, merge the value into the root
1213            if let Value::Object(map) = value {
1214                for (k, v) in map {
1215                    obj.insert(k, v);
1216                }
1217            }
1218            return;
1219        }
1220        
1221        let parts: Vec<&str> = path.split('.').collect();
1222        if parts.is_empty() {
1223            return;
1224        }
1225        
1226        let mut current = obj;
1227        let last_index = parts.len() - 1;
1228        
1229        for (i, part) in parts.iter().enumerate() {
1230            if i == last_index {
1231                // Last part - insert the value
1232                current.insert(part.to_string(), value);
1233                break;
1234            } else {
1235                // Intermediate part - ensure object exists
1236                current = current
1237                    .entry(part.to_string())
1238                    .or_insert_with(|| Value::Object(serde_json::Map::new()))
1239                    .as_object_mut()
1240                    .unwrap();
1241            }
1242        }
1243    }
1244    
1245    /// Convert result map to the requested format
1246    fn convert_to_format(&self, result: serde_json::Map<String, Value>, paths: &[String], format: ReturnFormat) -> Value {
1247        match format {
1248            ReturnFormat::Nested => Value::Object(result),
1249            ReturnFormat::Flat => {
1250                // Flatten nested object to dotted keys
1251                let mut flat = serde_json::Map::new();
1252                self.flatten_object(&result, String::new(), &mut flat);
1253                Value::Object(flat)
1254            }
1255            ReturnFormat::Array => {
1256                // Return array of values in order of requested paths
1257                let values: Vec<Value> = paths.iter()
1258                    .map(|path| {
1259                        let pointer = if path.is_empty() {
1260                            "".to_string()
1261                        } else {
1262                            format!("/{}", path.replace(".", "/"))
1263                        };
1264                        Value::Object(result.clone()).pointer(&pointer).cloned().unwrap_or(Value::Null)
1265                    })
1266                    .collect();
1267                Value::Array(values)
1268            }
1269        }
1270    }
1271    
1272    /// Recursively flatten a nested object into dotted keys
1273    fn flatten_object(&self, obj: &serde_json::Map<String, Value>, prefix: String, result: &mut serde_json::Map<String, Value>) {
1274        for (key, value) in obj {
1275            let new_key = if prefix.is_empty() {
1276                key.clone()
1277            } else {
1278                format!("{}.{}", prefix, key)
1279            };
1280            
1281            if let Value::Object(nested) = value {
1282                self.flatten_object(nested, new_key, result);
1283            } else {
1284                result.insert(new_key, value.clone());
1285            }
1286        }
1287    }
1288
1289    /// Get a value from the schema using dotted path notation.
1290    /// Converts dotted notation (e.g., "properties.field.value") to JSON pointer format.
1291    ///
1292    /// # Arguments
1293    ///
1294    /// * `path` - The dotted path to the value (e.g., "properties.field.value")
1295    ///
1296    /// # Returns
1297    ///
1298    /// The value at the specified path, or None if not found.
1299    pub fn get_schema_by_path(&self, path: &str) -> Option<Value> {
1300        // Convert dotted notation to JSON pointer
1301        let pointer = if path.is_empty() {
1302            "".to_string()
1303        } else {
1304            format!("/{}", path.replace(".", "/"))
1305        };
1306        
1307        self.schema.pointer(&pointer).cloned()
1308    }
1309
1310    /// Get values from the schema using multiple dotted path notations.
1311    /// Returns data in the specified format. Skips paths that are not found.
1312    ///
1313    /// # Arguments
1314    ///
1315    /// * `paths` - Array of dotted paths to retrieve (e.g., ["properties.field1", "properties.field2"])
1316    /// * `format` - Optional return format (Nested, Flat, or Array). Defaults to Nested.
1317    ///
1318    /// # Returns
1319    ///
1320    /// Data in the specified format, or an empty object/array if no paths are found.
1321    pub fn get_schema_by_paths(&self, paths: &[String], format: Option<ReturnFormat>) -> Value {
1322        let format = format.unwrap_or_default();
1323        let mut result = serde_json::Map::new();
1324        
1325        for path in paths {
1326            // Convert dotted notation to JSON pointer
1327            let pointer = if path.is_empty() {
1328                "".to_string()
1329            } else {
1330                format!("/{}", path.replace(".", "/"))
1331            };
1332            
1333            // Get value at path, skip if not found
1334            if let Some(value) = self.schema.pointer(&pointer) {
1335                // Store the full path structure to maintain the hierarchy
1336                // Clone only once per path
1337                self.insert_at_path(&mut result, path, value.clone());
1338            }
1339        }
1340        
1341        self.convert_to_format(result, paths, format)
1342    }
1343
1344    /// Check if a dependency should be cached
1345    /// Caches everything except keys starting with $ (except $context)
1346    #[inline]
1347    fn should_cache_dependency(key: &str) -> bool {
1348        if key.starts_with("/$") || key.starts_with('$') {
1349            // Only cache $context, exclude other $ keys like $params
1350            key == "$context" || key.starts_with("$context.") || key.starts_with("/$context")
1351        } else {
1352            true
1353        }
1354    }
1355
1356    /// Helper: Try to get cached result for an evaluation (thread-safe)
1357    /// Helper: Try to get cached result (zero-copy via Arc)
1358    fn try_get_cached(&self, eval_key: &str, eval_data: &EvalData) -> Option<Value> {
1359        // Skip cache lookup if caching is disabled
1360        if !self.cache_enabled {
1361            return None;
1362        }
1363        
1364        // Get dependencies for this evaluation
1365        let deps = self.dependencies.get(eval_key)?;
1366        
1367        // If no dependencies, use simple cache key
1368        let cache_key = if deps.is_empty() {
1369            CacheKey::simple(eval_key.to_string())
1370        } else {
1371            // Filter dependencies (exclude $ keys except $context)
1372            let filtered_deps: IndexSet<String> = deps
1373                .iter()
1374                .filter(|dep_key| JSONEval::should_cache_dependency(dep_key))
1375                .cloned()
1376                .collect();
1377            
1378            // Collect dependency values
1379            let dep_values: Vec<(String, &Value)> = filtered_deps
1380                .iter()
1381                .filter_map(|dep_key| {
1382                    eval_data.get(dep_key).map(|v| (dep_key.clone(), v))
1383                })
1384                .collect();
1385            
1386            CacheKey::new(eval_key.to_string(), &filtered_deps, &dep_values)
1387        };
1388        
1389        // Try cache lookup (zero-copy via Arc, thread-safe)
1390        self.eval_cache.get(&cache_key).map(|arc_val| (*arc_val).clone())
1391    }
1392    
1393    /// Helper: Store evaluation result in cache (thread-safe)
1394    fn cache_result(&self, eval_key: &str, value: Value, eval_data: &EvalData) {
1395        // Skip cache insertion if caching is disabled
1396        if !self.cache_enabled {
1397            return;
1398        }
1399        
1400        // Get dependencies for this evaluation
1401        let deps = match self.dependencies.get(eval_key) {
1402            Some(d) => d,
1403            None => {
1404                // No dependencies - use simple cache key
1405                let cache_key = CacheKey::simple(eval_key.to_string());
1406                self.eval_cache.insert(cache_key, value);
1407                return;
1408            }
1409        };
1410        
1411        // Filter and collect dependency values (exclude $ keys except $context)
1412        let filtered_deps: IndexSet<String> = deps
1413            .iter()
1414            .filter(|dep_key| JSONEval::should_cache_dependency(dep_key))
1415            .cloned()
1416            .collect();
1417        
1418        let dep_values: Vec<(String, &Value)> = filtered_deps
1419            .iter()
1420            .filter_map(|dep_key| {
1421                eval_data.get(dep_key).map(|v| (dep_key.clone(), v))
1422            })
1423            .collect();
1424        
1425        let cache_key = CacheKey::new(eval_key.to_string(), &filtered_deps, &dep_values);
1426        self.eval_cache.insert(cache_key, value);
1427    }
1428
1429    /// Selectively purge cache entries that depend on changed data paths
1430    /// Only removes cache entries whose dependencies intersect with changed_paths
1431    /// Compares old vs new values and only purges if values actually changed
1432    fn purge_cache_for_changed_data_with_comparison(
1433        &self, 
1434        changed_data_paths: &[String],
1435        old_data: &Value,
1436        new_data: &Value
1437    ) {
1438        if changed_data_paths.is_empty() {
1439            return;
1440        }
1441        
1442        // Check which paths actually have different values
1443        let mut actually_changed_paths = Vec::new();
1444        for path in changed_data_paths {
1445            let old_val = old_data.pointer(path);
1446            let new_val = new_data.pointer(path);
1447            
1448            // Only add to changed list if values differ
1449            if old_val != new_val {
1450                actually_changed_paths.push(path.clone());
1451            }
1452        }
1453        
1454        // If no values actually changed, no need to purge
1455        if actually_changed_paths.is_empty() {
1456            return;
1457        }
1458        
1459        // Find all eval_keys that depend on the actually changed data paths
1460        let mut affected_eval_keys = IndexSet::new();
1461        
1462        for (eval_key, deps) in self.dependencies.iter() {
1463            // Check if this evaluation depends on any of the changed paths
1464            let is_affected = deps.iter().any(|dep| {
1465                // Check if the dependency matches any changed path
1466                actually_changed_paths.iter().any(|changed_path| {
1467                    // Exact match or prefix match (for nested fields)
1468                    dep == changed_path || 
1469                    dep.starts_with(&format!("{}/", changed_path)) ||
1470                    changed_path.starts_with(&format!("{}/", dep))
1471                })
1472            });
1473            
1474            if is_affected {
1475                affected_eval_keys.insert(eval_key.clone());
1476            }
1477        }
1478        
1479        // Remove all cache entries for affected eval_keys using retain
1480        // Keep entries whose eval_key is NOT in the affected set
1481        self.eval_cache.retain(|cache_key, _| {
1482            !affected_eval_keys.contains(&cache_key.eval_key)
1483        });
1484    }
1485    
1486    /// Selectively purge cache entries that depend on changed data paths
1487    /// Simpler version without value comparison for cases where we don't have old data
1488    fn purge_cache_for_changed_data(&self, changed_data_paths: &[String]) {
1489        if changed_data_paths.is_empty() {
1490            return;
1491        }
1492        
1493        // Find all eval_keys that depend on the changed data paths
1494        let mut affected_eval_keys = IndexSet::new();
1495        
1496        for (eval_key, deps) in self.dependencies.iter() {
1497            // Check if this evaluation depends on any of the changed paths
1498            let is_affected = deps.iter().any(|dep| {
1499                // Check if the dependency matches any changed path
1500                changed_data_paths.iter().any(|changed_path| {
1501                    // Exact match or prefix match (for nested fields)
1502                    dep == changed_path || 
1503                    dep.starts_with(&format!("{}/", changed_path)) ||
1504                    changed_path.starts_with(&format!("{}/", dep))
1505                })
1506            });
1507            
1508            if is_affected {
1509                affected_eval_keys.insert(eval_key.clone());
1510            }
1511        }
1512        
1513        // Remove all cache entries for affected eval_keys using retain
1514        // Keep entries whose eval_key is NOT in the affected set
1515        self.eval_cache.retain(|cache_key, _| {
1516            !affected_eval_keys.contains(&cache_key.eval_key)
1517        });
1518    }
1519
1520    /// Get cache statistics
1521    pub fn cache_stats(&self) -> CacheStats {
1522        self.eval_cache.stats()
1523    }
1524    
1525    /// Clear evaluation cache
1526    pub fn clear_cache(&mut self) {
1527        self.eval_cache.clear();
1528        for subform in self.subforms.values_mut() {
1529            subform.clear_cache();
1530        }
1531    }
1532    
1533    /// Get number of cached entries
1534    pub fn cache_len(&self) -> usize {
1535        self.eval_cache.len()
1536    }
1537    
1538    /// Enable evaluation caching
1539    /// Useful for reusing JSONEval instances with different data
1540    pub fn enable_cache(&mut self) {
1541        self.cache_enabled = true;
1542        for subform in self.subforms.values_mut() {
1543            subform.enable_cache();
1544        }
1545    }
1546    
1547    /// Disable evaluation caching
1548    /// Useful for web API usage where each request creates a new JSONEval instance
1549    /// Improves performance by skipping cache operations that have no benefit for single-use instances
1550    pub fn disable_cache(&mut self) {
1551        self.cache_enabled = false;
1552        self.eval_cache.clear(); // Clear any existing cache entries
1553        for subform in self.subforms.values_mut() {
1554            subform.disable_cache();
1555        }
1556    }
1557    
1558    /// Check if caching is enabled
1559    pub fn is_cache_enabled(&self) -> bool {
1560        self.cache_enabled
1561    }
1562
1563    fn evaluate_others(&mut self, paths: Option<&[String]>) {
1564        time_block!("    evaluate_others()", {
1565            // Step 1: Evaluate options URL templates (handles {variable} patterns)
1566            time_block!("      evaluate_options_templates", {
1567                self.evaluate_options_templates(paths);
1568            });
1569            
1570            // Step 2: Evaluate "rules" and "others" categories with caching
1571            // Rules are evaluated here so their values are available in evaluated_schema
1572            let combined_count = self.rules_evaluations.len() + self.others_evaluations.len();
1573            if combined_count == 0 {
1574                return;
1575            }
1576            
1577            time_block!("      evaluate rules+others", {
1578                let eval_data_snapshot = self.eval_data.clone();
1579        
1580                let normalized_paths: Option<Vec<String>> = paths.map(|p_list| {
1581                    p_list.iter()
1582                        .flat_map(|p| {
1583                            let ptr = path_utils::dot_notation_to_schema_pointer(p);
1584                            // Also support version with /properties/ prefix for root match
1585                            let with_props = if ptr.starts_with("#/") {
1586                                    format!("#/properties/{}", &ptr[2..])
1587                            } else {
1588                                    ptr.clone()
1589                            };
1590                            vec![ptr, with_props]
1591                        })
1592                        .collect()
1593                });
1594
1595        #[cfg(feature = "parallel")]
1596        {
1597            let combined_results: Mutex<Vec<(String, Value)>> = Mutex::new(Vec::with_capacity(combined_count));
1598            
1599            self.rules_evaluations
1600                .par_iter()
1601                .chain(self.others_evaluations.par_iter())
1602                .for_each(|eval_key| {
1603                    // Filter items if paths are provided
1604                    if let Some(filter_paths) = normalized_paths.as_ref() {
1605                        if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
1606                            return;
1607                        }
1608                    }
1609
1610                    let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
1611
1612                    // Try cache first (thread-safe)
1613                    if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
1614                        return;
1615                    }
1616
1617                    // Cache miss - evaluate
1618                    if let Some(logic_id) = self.evaluations.get(eval_key) {
1619                        if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
1620                            let cleaned_val = clean_float_noise(val);
1621                            // Cache result (thread-safe)
1622                            self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
1623                            combined_results.lock().unwrap().push((pointer_path, cleaned_val));
1624                        }
1625                    }
1626                });
1627
1628            // Write results to evaluated_schema
1629            for (result_path, value) in combined_results.into_inner().unwrap() {
1630                if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&result_path) {
1631                    // Special handling for rules with $evaluation
1632                    // This includes both direct rules and array items: /rules/evaluation/0/$evaluation
1633                    if !result_path.starts_with("$") && result_path.contains("/rules/") && !result_path.ends_with("/value") {
1634                        match pointer_value.as_object_mut() {
1635                            Some(pointer_obj) => {
1636                                pointer_obj.remove("$evaluation");
1637                                pointer_obj.insert("value".to_string(), value);
1638                            },
1639                            None => continue,
1640                        }
1641                    } else {
1642                        *pointer_value = value;
1643                    }
1644                }
1645            }
1646        }
1647        
1648        #[cfg(not(feature = "parallel"))]
1649        {
1650            // Sequential evaluation
1651            let combined_evals: Vec<&String> = self.rules_evaluations.iter()
1652                .chain(self.others_evaluations.iter())
1653                .collect();
1654                
1655            for eval_key in combined_evals {
1656                // Filter items if paths are provided
1657                if let Some(filter_paths) = normalized_paths.as_ref() {
1658                    if !filter_paths.is_empty() && !filter_paths.iter().any(|p| eval_key.starts_with(p.as_str()) || p.starts_with(eval_key.as_str())) {
1659                        continue;
1660                    }
1661                }
1662
1663                let pointer_path = path_utils::normalize_to_json_pointer(eval_key);
1664                
1665                // Try cache first
1666                if let Some(_) = self.try_get_cached(eval_key, &eval_data_snapshot) {
1667                    continue;
1668                }
1669                
1670                // Cache miss - evaluate
1671                if let Some(logic_id) = self.evaluations.get(eval_key) {
1672                    if let Ok(val) = self.engine.run(logic_id, eval_data_snapshot.data()) {
1673                        let cleaned_val = clean_float_noise(val);
1674                        // Cache result
1675                        self.cache_result(eval_key, Value::Null, &eval_data_snapshot);
1676                        
1677                        if let Some(pointer_value) = self.evaluated_schema.pointer_mut(&pointer_path) {
1678                            if !pointer_path.starts_with("$") && pointer_path.contains("/rules/") && !pointer_path.ends_with("/value") {
1679                                match pointer_value.as_object_mut() {
1680                                    Some(pointer_obj) => {
1681                                        pointer_obj.remove("$evaluation");
1682                                        pointer_obj.insert("value".to_string(), cleaned_val);
1683                                    },
1684                                    None => continue,
1685                                }
1686                            } else {
1687                                *pointer_value = cleaned_val;
1688                            }
1689                        }
1690                    }
1691                }
1692            }
1693        }
1694            });
1695        });
1696    }
1697    
1698    /// Evaluate options URL templates (handles {variable} patterns)
1699    fn evaluate_options_templates(&mut self, paths: Option<&[String]>) {
1700        // Use pre-collected options templates from parsing (Arc clone is cheap)
1701        let templates_to_eval = self.options_templates.clone();
1702        
1703        // Evaluate each template
1704        for (path, template_str, params_path) in templates_to_eval.iter() {
1705            // Filter items if paths are provided
1706            // 'path' here is the schema path to the field (dot notation or similar, need to check)
1707            // It seems to be schema pointer based on usage in other methods
1708            if let Some(filter_paths) = paths {
1709                if !filter_paths.is_empty() && !filter_paths.iter().any(|p| path.starts_with(p.as_str()) || p.starts_with(path.as_str())) {
1710                    continue;
1711                }
1712            }
1713
1714            if let Some(params) = self.evaluated_schema.pointer(&params_path) {
1715                if let Ok(evaluated) = self.evaluate_template(&template_str, params) {
1716                    if let Some(target) = self.evaluated_schema.pointer_mut(&path) {
1717                        *target = Value::String(evaluated);
1718                    }
1719                }
1720            }
1721        }
1722    }
1723    
1724    /// Evaluate a template string like "api/users/{id}" with params
1725    fn evaluate_template(&self, template: &str, params: &Value) -> Result<String, String> {
1726        let mut result = template.to_string();
1727        
1728        // Simple template evaluation: replace {key} with params.key
1729        if let Value::Object(params_map) = params {
1730            for (key, value) in params_map {
1731                let placeholder = format!("{{{}}}", key);
1732                if let Some(str_val) = value.as_str() {
1733                    result = result.replace(&placeholder, str_val);
1734                } else {
1735                    // Convert non-string values to strings
1736                    result = result.replace(&placeholder, &value.to_string());
1737                }
1738            }
1739        }
1740        
1741        Ok(result)
1742    }
1743
1744    /// Compile a logic expression from a JSON string and store it globally
1745    /// 
1746    /// Returns a CompiledLogicId that can be used with run_logic for zero-clone evaluation.
1747    /// The compiled logic is stored in a global thread-safe cache and can be shared across
1748    /// different JSONEval instances. If the same logic was compiled before, returns the existing ID.
1749    /// 
1750    /// For repeated evaluations with different data, compile once and run multiple times.
1751    ///
1752    /// # Arguments
1753    ///
1754    /// * `logic_str` - JSON logic expression as a string
1755    ///
1756    /// # Returns
1757    ///
1758    /// A CompiledLogicId that can be reused for multiple evaluations across instances
1759    pub fn compile_logic(&self, logic_str: &str) -> Result<CompiledLogicId, String> {
1760        rlogic::compiled_logic_store::compile_logic(logic_str)
1761    }
1762    
1763    /// Compile a logic expression from a Value and store it globally
1764    /// 
1765    /// This is more efficient than compile_logic when you already have a parsed Value,
1766    /// as it avoids the JSON string serialization/parsing overhead.
1767    /// 
1768    /// Returns a CompiledLogicId that can be used with run_logic for zero-clone evaluation.
1769    /// The compiled logic is stored in a global thread-safe cache and can be shared across
1770    /// different JSONEval instances. If the same logic was compiled before, returns the existing ID.
1771    ///
1772    /// # Arguments
1773    ///
1774    /// * `logic` - JSON logic expression as a Value
1775    ///
1776    /// # Returns
1777    ///
1778    /// A CompiledLogicId that can be reused for multiple evaluations across instances
1779    pub fn compile_logic_value(&self, logic: &Value) -> Result<CompiledLogicId, String> {
1780        rlogic::compiled_logic_store::compile_logic_value(logic)
1781    }
1782    
1783    /// Run pre-compiled logic with zero-clone pattern
1784    /// 
1785    /// Uses references to avoid data cloning - similar to evaluate method.
1786    /// This is the most efficient way to evaluate logic multiple times with different data.
1787    /// The CompiledLogicId is retrieved from global storage, allowing the same compiled logic
1788    /// to be used across different JSONEval instances.
1789    ///
1790    /// # Arguments
1791    ///
1792    /// * `logic_id` - Pre-compiled logic ID from compile_logic
1793    /// * `data` - Optional data to evaluate against (uses existing data if None)
1794    /// * `context` - Optional context to use (uses existing context if None)
1795    ///
1796    /// # Returns
1797    ///
1798    /// The result of the evaluation as a Value
1799    pub fn run_logic(&mut self, logic_id: CompiledLogicId, data: Option<&Value>, context: Option<&Value>) -> Result<Value, String> {
1800        // Get compiled logic from global store
1801        let compiled_logic = rlogic::compiled_logic_store::get_compiled_logic(logic_id)
1802            .ok_or_else(|| format!("Compiled logic ID {:?} not found in store", logic_id))?;
1803        
1804        // Get the data to evaluate against
1805        // If custom data is provided, merge it with context and $params
1806        // Otherwise, use the existing eval_data which already has everything merged
1807        let eval_data_value = if let Some(input_data) = data {
1808            let context_value = context.unwrap_or(&self.context);
1809            
1810            self.eval_data.replace_data_and_context(input_data.clone(), context_value.clone());
1811            self.eval_data.data()
1812        } else {
1813            self.eval_data.data()
1814        };
1815        
1816        // Create an evaluator and run the pre-compiled logic with zero-clone pattern
1817        let evaluator = Evaluator::new();
1818        let result = evaluator.evaluate(&compiled_logic, &eval_data_value)?;
1819        
1820        Ok(clean_float_noise(result))
1821    }
1822    
1823    /// Compile and run JSON logic in one step (convenience method)
1824    /// 
1825    /// This is a convenience wrapper that combines compile_logic and run_logic.
1826    /// For repeated evaluations with different data, use compile_logic once 
1827    /// and run_logic multiple times for better performance.
1828    ///
1829    /// # Arguments
1830    ///
1831    /// * `logic_str` - JSON logic expression as a string
1832    /// * `data` - Optional data JSON string to evaluate against (uses existing data if None)
1833    /// * `context` - Optional context JSON string to use (uses existing context if None)
1834    ///
1835    /// # Returns
1836    ///
1837    /// The result of the evaluation as a Value
1838    pub fn compile_and_run_logic(&mut self, logic_str: &str, data: Option<&str>, context: Option<&str>) -> Result<Value, String> {
1839        // Parse the logic string and compile
1840        let compiled_logic = self.compile_logic(logic_str)?;
1841        
1842        // Parse data and context if provided
1843        let data_value = if let Some(data_str) = data {
1844            Some(json_parser::parse_json_str(data_str)?)
1845        } else {
1846            None
1847        };
1848        
1849        let context_value = if let Some(ctx_str) = context {
1850            Some(json_parser::parse_json_str(ctx_str)?)
1851        } else {
1852            None
1853        };
1854        
1855        // Run the compiled logic
1856        self.run_logic(compiled_logic, data_value.as_ref(), context_value.as_ref())
1857    }
1858
1859    /// Resolve layout references with optional evaluation
1860    ///
1861    /// # Arguments
1862    ///
1863    /// * `evaluate` - If true, runs evaluation before resolving layout. If false, only resolves layout.
1864    ///
1865    /// # Returns
1866    ///
1867    /// A Result indicating success or an error message.
1868    pub fn resolve_layout(&mut self, evaluate: bool) -> Result<(), String> {
1869        if evaluate {
1870            // Use existing data
1871            let data_str = serde_json::to_string(&self.data)
1872                .map_err(|e| format!("Failed to serialize data: {}", e))?;
1873            self.evaluate(&data_str, None, None)?;
1874        }
1875        
1876        self.resolve_layout_internal();
1877        Ok(())
1878    }
1879    
1880    fn resolve_layout_internal(&mut self) {
1881        time_block!("  resolve_layout_internal()", {
1882            // Use cached layout paths (collected at parse time)
1883            // Clone Arc reference (cheap)
1884            let layout_paths = self.layout_paths.clone();
1885            
1886            time_block!("    resolve_layout_elements", {
1887                for layout_path in layout_paths.iter() {
1888                    self.resolve_layout_elements(layout_path);
1889                }
1890            });
1891            
1892            // After resolving all references, propagate parent hidden/disabled to children
1893            time_block!("    propagate_parent_conditions", {
1894                for layout_path in layout_paths.iter() {
1895                    self.propagate_parent_conditions(layout_path);
1896                }
1897            });
1898        });
1899    }
1900    
1901    /// Propagate parent hidden/disabled conditions to children recursively
1902    fn propagate_parent_conditions(&mut self, layout_elements_path: &str) {
1903        // Normalize path from schema format (#/) to JSON pointer format (/)
1904        let normalized_path = path_utils::normalize_to_json_pointer(layout_elements_path);
1905        
1906        // Extract elements array to avoid borrow checker issues
1907        let elements = if let Some(Value::Array(arr)) = self.evaluated_schema.pointer_mut(&normalized_path) {
1908            mem::take(arr)
1909        } else {
1910            return;
1911        };
1912        
1913        // Process elements (now we can borrow self immutably)
1914        let mut updated_elements = Vec::with_capacity(elements.len());
1915        for element in elements {
1916            updated_elements.push(self.apply_parent_conditions(element, false, false));
1917        }
1918        
1919        // Write back the updated elements
1920        if let Some(target) = self.evaluated_schema.pointer_mut(&normalized_path) {
1921            *target = Value::Array(updated_elements);
1922        }
1923    }
1924    
1925    /// Recursively apply parent hidden/disabled conditions to an element and its children
1926    fn apply_parent_conditions(&self, element: Value, parent_hidden: bool, parent_disabled: bool) -> Value {
1927        if let Value::Object(mut map) = element {
1928            // Get current element's condition
1929            let mut element_hidden = parent_hidden;
1930            let mut element_disabled = parent_disabled;
1931            
1932            // Check condition field (used by field elements with $ref)
1933            if let Some(Value::Object(condition)) = map.get("condition") {
1934                if let Some(Value::Bool(hidden)) = condition.get("hidden") {
1935                    element_hidden = element_hidden || *hidden;
1936                }
1937                if let Some(Value::Bool(disabled)) = condition.get("disabled") {
1938                    element_disabled = element_disabled || *disabled;
1939                }
1940            }
1941            
1942            // Check hideLayout field (used by direct layout elements without $ref)
1943            if let Some(Value::Object(hide_layout)) = map.get("hideLayout") {
1944                // Check hideLayout.all
1945                if let Some(Value::Bool(all_hidden)) = hide_layout.get("all") {
1946                    if *all_hidden {
1947                        element_hidden = true;
1948                    }
1949                }
1950            }
1951            
1952            // Update condition to include parent state (for field elements)
1953            if parent_hidden || parent_disabled {
1954                // Update condition field if it exists or if this is a field element
1955                if map.contains_key("condition") || map.contains_key("$ref") || map.contains_key("$fullpath") {
1956                    let mut condition = if let Some(Value::Object(c)) = map.get("condition") {
1957                        c.clone()
1958                    } else {
1959                        serde_json::Map::new()
1960                    };
1961                    
1962                    if parent_hidden {
1963                        condition.insert("hidden".to_string(), Value::Bool(true));
1964                    }
1965                    if parent_disabled {
1966                        condition.insert("disabled".to_string(), Value::Bool(true));
1967                    }
1968                    
1969                    map.insert("condition".to_string(), Value::Object(condition));
1970                }
1971                
1972                // Update hideLayout for direct layout elements
1973                if parent_hidden && (map.contains_key("hideLayout") || map.contains_key("type")) {
1974                    let mut hide_layout = if let Some(Value::Object(h)) = map.get("hideLayout") {
1975                        h.clone()
1976                    } else {
1977                        serde_json::Map::new()
1978                    };
1979                    
1980                    // Set hideLayout.all to true when parent is hidden
1981                    hide_layout.insert("all".to_string(), Value::Bool(true));
1982                    map.insert("hideLayout".to_string(), Value::Object(hide_layout));
1983                }
1984            }
1985            
1986            // Update $parentHide flag if element has it (came from $ref resolution)
1987            // Only update if the element already has the field (to avoid adding it to non-ref elements)
1988            if map.contains_key("$parentHide") {
1989                map.insert("$parentHide".to_string(), Value::Bool(parent_hidden));
1990            }
1991            
1992            // Recursively process children if elements array exists
1993            if let Some(Value::Array(elements)) = map.get("elements") {
1994                let mut updated_children = Vec::with_capacity(elements.len());
1995                for child in elements {
1996                    updated_children.push(self.apply_parent_conditions(
1997                        child.clone(),
1998                        element_hidden,
1999                        element_disabled,
2000                    ));
2001                }
2002                map.insert("elements".to_string(), Value::Array(updated_children));
2003            }
2004            
2005            return Value::Object(map);
2006        }
2007        
2008        element
2009    }
2010    
2011    /// Resolve $ref references in layout elements (recursively)
2012    fn resolve_layout_elements(&mut self, layout_elements_path: &str) {
2013        // Normalize path from schema format (#/) to JSON pointer format (/)
2014        let normalized_path = path_utils::normalize_to_json_pointer(layout_elements_path);
2015        
2016        // Always read elements from original schema (not evaluated_schema)
2017        // This ensures we get fresh $ref entries on re-evaluation
2018        // since evaluated_schema elements get mutated to objects after first resolution
2019        let elements = if let Some(Value::Array(arr)) = self.schema.pointer(&normalized_path) {
2020            arr.clone()
2021        } else {
2022            return;
2023        };
2024        
2025        // Extract the parent path from normalized_path (e.g., "/properties/form/$layout/elements" -> "form.$layout")
2026        let parent_path = normalized_path
2027            .trim_start_matches('/')
2028            .replace("/elements", "")
2029            .replace('/', ".");
2030        
2031        // Process elements (now we can borrow self immutably)
2032        let mut resolved_elements = Vec::with_capacity(elements.len());
2033        for (index, element) in elements.iter().enumerate() {
2034            let element_path = if parent_path.is_empty() {
2035                format!("elements.{}", index)
2036            } else {
2037                format!("{}.elements.{}", parent_path, index)
2038            };
2039            let resolved = self.resolve_element_ref_recursive(element.clone(), &element_path);
2040            resolved_elements.push(resolved);
2041        }
2042        
2043        // Write back the resolved elements
2044        if let Some(target) = self.evaluated_schema.pointer_mut(&normalized_path) {
2045            *target = Value::Array(resolved_elements);
2046        }
2047    }
2048    
2049    /// Recursively resolve $ref in an element and its nested elements
2050    /// path_context: The dotted path to the current element (e.g., "form.$layout.elements.0")
2051    fn resolve_element_ref_recursive(&self, element: Value, path_context: &str) -> Value {
2052        // First resolve the current element's $ref
2053        let resolved = self.resolve_element_ref(element);
2054        
2055        // Then recursively resolve any nested elements arrays
2056        if let Value::Object(mut map) = resolved {
2057            // Ensure all layout elements have metadata fields
2058            // For elements with $ref, these were already set by resolve_element_ref
2059            // For direct layout elements without $ref, set them based on path_context
2060            if !map.contains_key("$parentHide") {
2061                map.insert("$parentHide".to_string(), Value::Bool(false));
2062            }
2063            
2064            // Set path metadata for direct layout elements (without $ref)
2065            if !map.contains_key("$fullpath") {
2066                map.insert("$fullpath".to_string(), Value::String(path_context.to_string()));
2067            }
2068            
2069            if !map.contains_key("$path") {
2070                // Extract last segment from path_context
2071                let last_segment = path_context.split('.').last().unwrap_or(path_context);
2072                map.insert("$path".to_string(), Value::String(last_segment.to_string()));
2073            }
2074            
2075            // Check if this object has an "elements" array
2076            if let Some(Value::Array(elements)) = map.get("elements") {
2077                let mut resolved_nested = Vec::with_capacity(elements.len());
2078                for (index, nested_element) in elements.iter().enumerate() {
2079                    let nested_path = format!("{}.elements.{}", path_context, index);
2080                    resolved_nested.push(self.resolve_element_ref_recursive(nested_element.clone(), &nested_path));
2081                }
2082                map.insert("elements".to_string(), Value::Array(resolved_nested));
2083            }
2084            
2085            return Value::Object(map);
2086        }
2087        
2088        resolved
2089    }
2090    
2091    /// Resolve $ref in a single element
2092    fn resolve_element_ref(&self, element: Value) -> Value {
2093        match element {
2094            Value::Object(mut map) => {
2095                // Check if element has $ref
2096                if let Some(Value::String(ref_path)) = map.get("$ref").cloned() {
2097                    // Convert ref_path to dotted notation for metadata storage
2098                    let dotted_path = path_utils::pointer_to_dot_notation(&ref_path);
2099                    
2100                    // Extract last segment for $path and path fields
2101                    let last_segment = dotted_path.split('.').last().unwrap_or(&dotted_path);
2102                    
2103                    // Inject metadata fields with dotted notation
2104                    map.insert("$fullpath".to_string(), Value::String(dotted_path.clone()));
2105                    map.insert("$path".to_string(), Value::String(last_segment.to_string()));
2106                    map.insert("$parentHide".to_string(), Value::Bool(false));
2107                    
2108                    // Normalize to JSON pointer for actual lookup
2109                    // Try different path formats to find the referenced value
2110                    let normalized_path = if ref_path.starts_with('#') || ref_path.starts_with('/') {
2111                        // Already a pointer, normalize it
2112                        path_utils::normalize_to_json_pointer(&ref_path)
2113                    } else {
2114                        // Try as schema path first (for paths like "illustration.insured.name")
2115                        let schema_pointer = path_utils::dot_notation_to_schema_pointer(&ref_path);
2116                        let schema_path = path_utils::normalize_to_json_pointer(&schema_pointer);
2117                        
2118                        // Check if it exists
2119                        if self.evaluated_schema.pointer(&schema_path).is_some() {
2120                            schema_path
2121                        } else {
2122                            // Try with /properties/ prefix (for simple refs like "parent_container")
2123                            let with_properties = format!("/properties/{}", ref_path.replace('.', "/properties/"));
2124                            with_properties
2125                        }
2126                    };
2127                    
2128                    // Get the referenced value
2129                    if let Some(referenced_value) = self.evaluated_schema.pointer(&normalized_path) {
2130                        // Clone the referenced value
2131                        let resolved = referenced_value.clone();
2132                        
2133                        // If resolved is an object, check for special handling
2134                        if let Value::Object(mut resolved_map) = resolved {
2135                            // Remove $ref from original map
2136                            map.remove("$ref");
2137                            
2138                            // Special case: if resolved has $layout, flatten it
2139                            // Extract $layout contents and merge at root level
2140                            if let Some(Value::Object(layout_obj)) = resolved_map.remove("$layout") {
2141                                // Start with layout properties (they become root properties)
2142                                let mut result = layout_obj.clone();
2143                                
2144                                // Remove properties from resolved (we don't want it)
2145                                resolved_map.remove("properties");
2146                                
2147                                // Merge remaining resolved_map properties (except type if layout has it)
2148                                for (key, value) in resolved_map {
2149                                    if key != "type" || !result.contains_key("type") {
2150                                        result.insert(key, value);
2151                                    }
2152                                }
2153                                
2154                                // Finally, merge element override properties
2155                                for (key, value) in map {
2156                                    result.insert(key, value);
2157                                }
2158                                
2159                                return Value::Object(result);
2160                            } else {
2161                                // Normal merge: element properties override referenced properties
2162                                for (key, value) in map {
2163                                    resolved_map.insert(key, value);
2164                                }
2165                                
2166                                return Value::Object(resolved_map);
2167                            }
2168                        } else {
2169                            // If referenced value is not an object, just return it
2170                            return resolved;
2171                        }
2172                    }
2173                }
2174                
2175                // No $ref or couldn't resolve - return element as-is
2176                Value::Object(map)
2177            }
2178            _ => element,
2179        }
2180    }
2181
2182    /// Evaluate fields that depend on a changed path
2183    /// This processes all dependent fields transitively when a source field changes
2184    /// 
2185    /// # Arguments
2186    /// * `changed_paths` - Array of field paths that changed (supports dot notation or schema pointers)
2187    /// * `data` - Optional JSON data to update before processing
2188    /// * `context` - Optional context data
2189    /// * `re_evaluate` - If true, performs full evaluation after processing dependents
2190    pub fn evaluate_dependents(
2191        &mut self,
2192        changed_paths: &[String],
2193        data: Option<&str>,
2194        context: Option<&str>,
2195        re_evaluate: bool,
2196    ) -> Result<Value, String> {
2197        // Acquire lock for synchronous execution
2198        let _lock = self.eval_lock.lock().unwrap();
2199        
2200        // Update data if provided
2201        if let Some(data_str) = data {
2202            // Save old data for comparison
2203            let old_data = self.eval_data.clone_data_without(&["$params"]);
2204            
2205            let data_value = json_parser::parse_json_str(data_str)?;
2206            let context_value = if let Some(ctx) = context {
2207                json_parser::parse_json_str(ctx)?
2208            } else {
2209                Value::Object(serde_json::Map::new())
2210            };
2211            self.eval_data.replace_data_and_context(data_value.clone(), context_value);
2212            
2213            // Selectively purge cache entries that depend on changed data
2214            // Only purge if values actually changed
2215            // Convert changed_paths to data pointer format for cache purging
2216            let data_paths: Vec<String> = changed_paths
2217                .iter()
2218                .map(|path| {
2219                    // Convert "illustration.insured.ins_dob" to "/illustration/insured/ins_dob"
2220                    format!("/{}", path.replace('.', "/"))
2221                })
2222                .collect();
2223            self.purge_cache_for_changed_data_with_comparison(&data_paths, &old_data, &data_value);
2224        }
2225        
2226        let mut result = Vec::new();
2227        let mut processed = IndexSet::new();
2228        
2229        // Normalize all changed paths and add to processing queue
2230        // Converts: "illustration.insured.name" -> "#/illustration/properties/insured/properties/name"
2231        let mut to_process: Vec<(String, bool)> = changed_paths
2232            .iter()
2233            .map(|path| (path_utils::dot_notation_to_schema_pointer(path), false))
2234            .collect(); // (path, is_transitive)
2235        
2236        // Process dependents recursively (always nested/transitive)
2237        while let Some((current_path, is_transitive)) = to_process.pop() {
2238            if processed.contains(&current_path) {
2239                continue;
2240            }
2241            processed.insert(current_path.clone());
2242            
2243            // Get the value of the changed field for $value context
2244            let current_data_path = path_utils::normalize_to_json_pointer(&current_path)
2245                .replace("/properties/", "/")
2246                .trim_start_matches('#')
2247                .to_string();
2248            let mut current_value = self.eval_data.data().pointer(&current_data_path)
2249                .cloned()
2250                .unwrap_or(Value::Null);
2251            
2252            // Find dependents for this path
2253            if let Some(dependent_items) = self.dependents_evaluations.get(&current_path) {
2254                for dep_item in dependent_items {
2255                    let ref_path = &dep_item.ref_path;
2256                    let pointer_path = path_utils::normalize_to_json_pointer(ref_path);
2257                    // Data paths don't include /properties/, strip it for data access
2258                    let data_path = pointer_path.replace("/properties/", "/");
2259
2260                    let current_ref_value = self.eval_data.data().pointer(&data_path)
2261                        .cloned()
2262                        .unwrap_or(Value::Null);
2263                    
2264                    // Get field and parent field from schema
2265                    let field = self.evaluated_schema.pointer(&pointer_path).cloned();
2266                    
2267                    // Get parent field - skip /properties/ to get actual parent object
2268                    let parent_path = if let Some(last_slash) = pointer_path.rfind("/properties") {
2269                        &pointer_path[..last_slash]
2270                    } else {
2271                        "/"
2272                    };
2273                    let mut parent_field = if parent_path.is_empty() || parent_path == "/" {
2274                        self.evaluated_schema.clone()
2275                    } else {
2276                        self.evaluated_schema.pointer(parent_path).cloned()
2277                            .unwrap_or_else(|| Value::Object(serde_json::Map::new()))
2278                    };
2279
2280                    // omit properties to minimize size of parent field
2281                    if let Value::Object(ref mut map) = parent_field {
2282                        map.remove("properties");
2283                        map.remove("$layout");
2284                    }
2285                    
2286                    let mut change_obj = serde_json::Map::new();
2287                    change_obj.insert("$ref".to_string(), Value::String(path_utils::pointer_to_dot_notation(&data_path)));
2288                    if let Some(f) = field {
2289                        change_obj.insert("$field".to_string(), f);
2290                    }
2291                    change_obj.insert("$parentField".to_string(), parent_field);
2292                    change_obj.insert("transitive".to_string(), Value::Bool(is_transitive));
2293                    
2294                    let mut add_transitive = false;
2295                    let mut add_deps = false;
2296                    // Process clear
2297                    if let Some(clear_val) = &dep_item.clear {
2298                        let clear_val_clone = clear_val.clone();
2299                        let should_clear = Self::evaluate_dependent_value_static(&self.engine, &self.evaluations, &self.eval_data, &clear_val_clone, &current_value, &current_ref_value)?;
2300                        let clear_bool = match should_clear {
2301                            Value::Bool(b) => b,
2302                            _ => false,
2303                        };
2304                        
2305                        if clear_bool {
2306                            // Clear the field
2307                            if data_path == current_data_path {
2308                                current_value = Value::Null;
2309                            }
2310                            self.eval_data.set(&data_path, Value::Null);
2311                            change_obj.insert("clear".to_string(), Value::Bool(true));
2312                            add_transitive = true;
2313                            add_deps = true;
2314                        }
2315                    }
2316                    
2317                    // Process value
2318                    if let Some(value_val) = &dep_item.value {
2319                        let value_val_clone = value_val.clone();
2320                        let computed_value = Self::evaluate_dependent_value_static(&self.engine, &self.evaluations, &self.eval_data, &value_val_clone, &current_value, &current_ref_value)?;
2321                        let cleaned_val = clean_float_noise(computed_value.clone());
2322                        
2323                        if cleaned_val != current_ref_value && cleaned_val != Value::Null {   
2324                            // Set the value
2325                            if data_path == current_data_path {
2326                                current_value = cleaned_val.clone();
2327                            }
2328                            self.eval_data.set(&data_path, cleaned_val.clone());
2329                            change_obj.insert("value".to_string(), cleaned_val);
2330                            add_transitive = true;
2331                            add_deps = true;
2332                        }
2333                    }
2334                    
2335                    // add only when has clear / value
2336                    if add_deps {
2337                        result.push(Value::Object(change_obj));
2338                    }
2339                    
2340                    // Add this dependent to queue for transitive processing
2341                    if add_transitive {
2342                        to_process.push((ref_path.clone(), true));
2343                    }
2344                }
2345            }
2346        }
2347        
2348        // If re_evaluate is true, perform full evaluation with the mutated eval_data
2349        // Use evaluate_internal to avoid serialization overhead
2350        // We need to drop the lock first since evaluate_internal acquires its own lock
2351        if re_evaluate {
2352            drop(_lock);  // Release the evaluate_dependents lock
2353            self.evaluate_internal(None)?;
2354        }
2355        
2356        Ok(Value::Array(result))
2357    }
2358    
2359    /// Helper to evaluate a dependent value - uses pre-compiled eval keys for fast lookup
2360    fn evaluate_dependent_value_static(
2361        engine: &RLogic,
2362        evaluations: &IndexMap<String, LogicId>,
2363        eval_data: &EvalData,
2364        value: &Value,
2365        changed_field_value: &Value,
2366        changed_field_ref_value: &Value
2367    ) -> Result<Value, String> {
2368        match value {
2369            // If it's a String, check if it's an eval key reference
2370            Value::String(eval_key) => {
2371                if let Some(logic_id) = evaluations.get(eval_key) {
2372                    // It's a pre-compiled evaluation - run it with scoped context
2373                    // Create internal context with $value and $refValue
2374                    let mut internal_context = serde_json::Map::new();
2375                    internal_context.insert("$value".to_string(), changed_field_value.clone());
2376                    internal_context.insert("$refValue".to_string(), changed_field_ref_value.clone());
2377                    let context_value = Value::Object(internal_context);
2378                    
2379                    let result = engine.run_with_context(logic_id, eval_data.data(), &context_value)
2380                        .map_err(|e| format!("Failed to evaluate dependent logic '{}': {}", eval_key, e))?;
2381                    Ok(result)
2382                } else {
2383                    // It's a regular string value
2384                    Ok(value.clone())
2385                }
2386            }
2387            // For backwards compatibility: compile $evaluation on-the-fly
2388            // This shouldn't happen with properly parsed schemas
2389            Value::Object(map) if map.contains_key("$evaluation") => {
2390                Err("Dependent evaluation contains unparsed $evaluation - schema was not properly parsed".to_string())
2391            }
2392            // Primitive value - return as-is
2393            _ => Ok(value.clone()),
2394        }
2395    }
2396
2397    /// Validate form data against schema rules
2398    /// Returns validation errors for fields that don't meet their rules
2399    pub fn validate(
2400        &mut self,
2401        data: &str,
2402        context: Option<&str>,
2403        paths: Option<&[String]>
2404    ) -> Result<ValidationResult, String> {
2405        // Acquire lock for synchronous execution
2406        let _lock = self.eval_lock.lock().unwrap();
2407        
2408        // Save old data for comparison
2409        let old_data = self.eval_data.clone_data_without(&["$params"]);
2410        
2411        // Parse data and context
2412        let data_value = json_parser::parse_json_str(data)?;
2413        let context_value = if let Some(ctx) = context {
2414            json_parser::parse_json_str(ctx)?
2415        } else {
2416            Value::Object(serde_json::Map::new())
2417        };
2418        
2419        // Update eval_data with new data/context
2420        self.eval_data.replace_data_and_context(data_value.clone(), context_value);
2421        
2422        // Selectively purge cache for rule evaluations that depend on changed data
2423        // Collect all top-level data keys as potentially changed paths
2424        let changed_data_paths: Vec<String> = if let Some(obj) = data_value.as_object() {
2425            obj.keys().map(|k| format!("/{}", k)).collect()
2426        } else {
2427            Vec::new()
2428        };
2429        self.purge_cache_for_changed_data_with_comparison(&changed_data_paths, &old_data, &data_value);
2430        
2431        // Drop lock before calling evaluate_others which needs mutable access
2432        drop(_lock);
2433        
2434        // Re-evaluate rule evaluations to ensure fresh values
2435        // This ensures all rule.$evaluation expressions are re-computed
2436        // Re-evaluate rule evaluations to ensure fresh values
2437        // This ensures all rule.$evaluation expressions are re-computed
2438        self.evaluate_others(paths);
2439        
2440        // Update evaluated_schema with fresh evaluations
2441        self.evaluated_schema = self.get_evaluated_schema(false);
2442        
2443        let mut errors: IndexMap<String, ValidationError> = IndexMap::new();
2444        
2445        // Use pre-parsed fields_with_rules from schema parsing (no runtime collection needed)
2446        // This list was collected during schema parse and contains all fields with rules
2447        for field_path in self.fields_with_rules.iter() {
2448            // Check if we should validate this path (path filtering)
2449            if let Some(filter_paths) = paths {
2450                if !filter_paths.is_empty() && !filter_paths.iter().any(|p| field_path.starts_with(p.as_str()) || p.starts_with(field_path.as_str())) {
2451                    continue;
2452                }
2453            }
2454            
2455            self.validate_field(field_path, &data_value, &mut errors);
2456        }
2457        
2458        let has_error = !errors.is_empty();
2459        
2460        Ok(ValidationResult {
2461            has_error,
2462            errors,
2463        })
2464    }
2465    
2466    /// Validate a single field that has rules
2467    fn validate_field(
2468        &self,
2469        field_path: &str,
2470        data: &Value,
2471        errors: &mut IndexMap<String, ValidationError>
2472    ) {
2473        // Skip if already has error
2474        if errors.contains_key(field_path) {
2475            return;
2476        }
2477        
2478        // Get schema for this field
2479        let schema_path = path_utils::dot_notation_to_schema_pointer(field_path);
2480        
2481        // Remove leading "#" from path for pointer lookup
2482        let pointer_path = schema_path.trim_start_matches('#');
2483        
2484        // Try to get schema, if not found, try with /properties/ prefix for standard JSON Schema
2485        let field_schema = match self.evaluated_schema.pointer(pointer_path) {
2486            Some(s) => s,
2487            None => {
2488                // Try with /properties/ prefix (for standard JSON Schema format)
2489                let alt_path = format!("/properties{}", pointer_path);
2490                match self.evaluated_schema.pointer(&alt_path) {
2491                    Some(s) => s,
2492                    None => return,
2493                }
2494            }
2495        };
2496        
2497        // Check if field is hidden (skip validation)
2498        if let Value::Object(schema_map) = field_schema {
2499            if let Some(Value::Object(condition)) = schema_map.get("condition") {
2500                if let Some(Value::Bool(true)) = condition.get("hidden") {
2501                    return;
2502                }
2503            }
2504            
2505            // Get rules object
2506            let rules = match schema_map.get("rules") {
2507                Some(Value::Object(r)) => r,
2508                _ => return,
2509            };
2510            
2511            // Get field data
2512            let field_data = self.get_field_data(field_path, data);
2513            
2514            // Validate each rule
2515            for (rule_name, rule_value) in rules {
2516                self.validate_rule(
2517                    field_path,
2518                    rule_name,
2519                    rule_value,
2520                    &field_data,
2521                    schema_map,
2522                    field_schema,
2523                    errors
2524                );
2525            }
2526        }
2527    }
2528    
2529    /// Get data value for a field path
2530    fn get_field_data(&self, field_path: &str, data: &Value) -> Value {
2531        let parts: Vec<&str> = field_path.split('.').collect();
2532        let mut current = data;
2533        
2534        for part in parts {
2535            match current {
2536                Value::Object(map) => {
2537                    current = map.get(part).unwrap_or(&Value::Null);
2538                }
2539                _ => return Value::Null,
2540            }
2541        }
2542        
2543        current.clone()
2544    }
2545    
2546    /// Validate a single rule
2547    fn validate_rule(
2548        &self,
2549        field_path: &str,
2550        rule_name: &str,
2551        rule_value: &Value,
2552        field_data: &Value,
2553        schema_map: &serde_json::Map<String, Value>,
2554        _schema: &Value,
2555        errors: &mut IndexMap<String, ValidationError>
2556    ) {
2557        // Skip if already has error
2558        if errors.contains_key(field_path) {
2559            return;
2560        }
2561        
2562        let mut disabled_field = false;
2563        // Check if disabled
2564        if let Some(Value::Object(condition)) = schema_map.get("condition") {
2565            if let Some(Value::Bool(true)) = condition.get("disabled") {
2566                disabled_field = true;
2567            }
2568        }
2569        
2570        // Get the evaluated rule from evaluated_schema (which has $evaluation already processed)
2571        // Convert field_path to schema path
2572        let schema_path = path_utils::dot_notation_to_schema_pointer(field_path);
2573        let rule_path = format!("{}/rules/{}", schema_path.trim_start_matches('#'), rule_name);
2574        
2575        // Look up the evaluated rule from evaluated_schema
2576        let evaluated_rule = if let Some(eval_rule) = self.evaluated_schema.pointer(&rule_path) {
2577            eval_rule.clone()
2578        } else {
2579            rule_value.clone()
2580        };
2581        
2582        // Extract rule object (after evaluation)
2583        let (rule_active, rule_message, rule_code, rule_data) = match &evaluated_rule {
2584            Value::Object(rule_obj) => {
2585                let active = rule_obj.get("value").unwrap_or(&Value::Bool(false));
2586                
2587                // Handle message - could be string or object with "value"
2588                let message = match rule_obj.get("message") {
2589                    Some(Value::String(s)) => s.clone(),
2590                    Some(Value::Object(msg_obj)) if msg_obj.contains_key("value") => {
2591                        msg_obj.get("value")
2592                            .and_then(|v| v.as_str())
2593                            .unwrap_or("Validation failed")
2594                            .to_string()
2595                    }
2596                    Some(msg_val) => msg_val.as_str().unwrap_or("Validation failed").to_string(),
2597                    None => "Validation failed".to_string()
2598                };
2599                
2600                let code = rule_obj.get("code")
2601                    .and_then(|c| c.as_str())
2602                    .map(|s| s.to_string());
2603                
2604                // Handle data - extract "value" from objects with $evaluation
2605                let data = rule_obj.get("data").map(|d| {
2606                    if let Value::Object(data_obj) = d {
2607                        let mut cleaned_data = serde_json::Map::new();
2608                        for (key, value) in data_obj {
2609                            // If value is an object with only "value" key, extract it
2610                            if let Value::Object(val_obj) = value {
2611                                if val_obj.len() == 1 && val_obj.contains_key("value") {
2612                                    cleaned_data.insert(key.clone(), val_obj["value"].clone());
2613                                } else {
2614                                    cleaned_data.insert(key.clone(), value.clone());
2615                                }
2616                            } else {
2617                                cleaned_data.insert(key.clone(), value.clone());
2618                            }
2619                        }
2620                        Value::Object(cleaned_data)
2621                    } else {
2622                        d.clone()
2623                    }
2624                });
2625                
2626                (active.clone(), message, code, data)
2627            }
2628            _ => (evaluated_rule.clone(), "Validation failed".to_string(), None, None)
2629        };
2630        
2631        // Generate default code if not provided
2632        let error_code = rule_code.or_else(|| Some(format!("{}.{}", field_path, rule_name)));
2633        
2634        let is_empty = matches!(field_data, Value::Null) || 
2635                       (field_data.is_string() && field_data.as_str().unwrap_or("").is_empty()) ||
2636                       (field_data.is_array() && field_data.as_array().unwrap().is_empty());
2637        
2638        match rule_name {
2639            "required" => {
2640                if !disabled_field && rule_active == Value::Bool(true) {
2641                    if is_empty {
2642                        errors.insert(field_path.to_string(), ValidationError {
2643                            rule_type: "required".to_string(),
2644                            message: rule_message,
2645                            code: error_code.clone(),
2646                            pattern: None,
2647                            field_value: None,
2648                            data: None,
2649                        });
2650                    }
2651                }
2652            }
2653            "minLength" => {
2654                if !is_empty {
2655                    if let Some(min) = rule_active.as_u64() {
2656                        let len = match field_data {
2657                            Value::String(s) => s.len(),
2658                            Value::Array(a) => a.len(),
2659                            _ => 0
2660                        };
2661                        if len < min as usize {
2662                            errors.insert(field_path.to_string(), ValidationError {
2663                                rule_type: "minLength".to_string(),
2664                                message: rule_message,
2665                                code: error_code.clone(),
2666                                pattern: None,
2667                                field_value: None,
2668                                data: None,
2669                            });
2670                        }
2671                    }
2672                }
2673            }
2674            "maxLength" => {
2675                if !is_empty {
2676                    if let Some(max) = rule_active.as_u64() {
2677                        let len = match field_data {
2678                            Value::String(s) => s.len(),
2679                            Value::Array(a) => a.len(),
2680                            _ => 0
2681                        };
2682                        if len > max as usize {
2683                            errors.insert(field_path.to_string(), ValidationError {
2684                                rule_type: "maxLength".to_string(),
2685                                message: rule_message,
2686                                code: error_code.clone(),
2687                                pattern: None,
2688                                field_value: None,
2689                                data: None,
2690                            });
2691                        }
2692                    }
2693                }
2694            }
2695            "minValue" => {
2696                if !is_empty {
2697                    if let Some(min) = rule_active.as_f64() {
2698                        if let Some(val) = field_data.as_f64() {
2699                            if val < min {
2700                                errors.insert(field_path.to_string(), ValidationError {
2701                                    rule_type: "minValue".to_string(),
2702                                    message: rule_message,
2703                                    code: error_code.clone(),
2704                                    pattern: None,
2705                                    field_value: None,
2706                                    data: None,
2707                                });
2708                            }
2709                        }
2710                    }
2711                }
2712            }
2713            "maxValue" => {
2714                if !is_empty {
2715                    if let Some(max) = rule_active.as_f64() {
2716                        if let Some(val) = field_data.as_f64() {
2717                            if val > max {
2718                                errors.insert(field_path.to_string(), ValidationError {
2719                                    rule_type: "maxValue".to_string(),
2720                                    message: rule_message,
2721                                    code: error_code.clone(),
2722                                    pattern: None,
2723                                    field_value: None,
2724                                    data: None,
2725                                });
2726                            }
2727                        }
2728                    }
2729                }
2730            }
2731            "pattern" => {
2732                if !is_empty {
2733                    if let Some(pattern) = rule_active.as_str() {
2734                        if let Some(text) = field_data.as_str() {
2735                            if let Ok(regex) = regex::Regex::new(pattern) {
2736                                if !regex.is_match(text) {
2737                                    errors.insert(field_path.to_string(), ValidationError {
2738                                        rule_type: "pattern".to_string(),
2739                                        message: rule_message,
2740                                        code: error_code.clone(),
2741                                        pattern: Some(pattern.to_string()),
2742                                        field_value: Some(text.to_string()),
2743                                        data: None,
2744                                    });
2745                                }
2746                            }
2747                        }
2748                    }
2749                }
2750            }
2751            "evaluation" => {
2752                // Handle array of evaluation rules
2753                // Format: "evaluation": [{ "code": "...", "message": "...", "$evaluation": {...} }]
2754                if let Value::Array(eval_array) = &evaluated_rule {
2755                    for (idx, eval_item) in eval_array.iter().enumerate() {
2756                        if let Value::Object(eval_obj) = eval_item {
2757                            // Get the evaluated value (should be in "value" key after evaluation)
2758                            let eval_result = eval_obj.get("value").unwrap_or(&Value::Bool(true));
2759                            
2760                            // Check if result is falsy
2761                            let is_falsy = match eval_result {
2762                                Value::Bool(false) => true,
2763                                Value::Null => true,
2764                                Value::Number(n) => n.as_f64() == Some(0.0),
2765                                Value::String(s) => s.is_empty(),
2766                                Value::Array(a) => a.is_empty(),
2767                                _ => false,
2768                            };
2769                            
2770                            if is_falsy {
2771                                let eval_code = eval_obj.get("code")
2772                                    .and_then(|c| c.as_str())
2773                                    .map(|s| s.to_string())
2774                                    .or_else(|| Some(format!("{}.evaluation.{}", field_path, idx)));
2775                                
2776                                let eval_message = eval_obj.get("message")
2777                                    .and_then(|m| m.as_str())
2778                                    .unwrap_or("Validation failed")
2779                                    .to_string();
2780                                
2781                                let eval_data = eval_obj.get("data").cloned();
2782                                
2783                                errors.insert(field_path.to_string(), ValidationError {
2784                                    rule_type: "evaluation".to_string(),
2785                                    message: eval_message,
2786                                    code: eval_code,
2787                                    pattern: None,
2788                                    field_value: None,
2789                                    data: eval_data,
2790                                });
2791                                
2792                                // Stop at first failure
2793                                break;
2794                            }
2795                        }
2796                    }
2797                }
2798            }
2799            _ => {
2800                // Custom evaluation rules
2801                // In JS: if (!opt.rule.value) then error
2802                // This handles rules with $evaluation that return false/falsy values
2803                if !is_empty {
2804                    // Check if rule_active is falsy (false, 0, null, empty string, empty array)
2805                    let is_falsy = match &rule_active {
2806                        Value::Bool(false) => true,
2807                        Value::Null => true,
2808                        Value::Number(n) => n.as_f64() == Some(0.0),
2809                        Value::String(s) => s.is_empty(),
2810                        Value::Array(a) => a.is_empty(),
2811                        _ => false,
2812                    };
2813                    
2814                    if is_falsy {
2815                        errors.insert(field_path.to_string(), ValidationError {
2816                            rule_type: "evaluation".to_string(),
2817                            message: rule_message,
2818                            code: error_code.clone(),
2819                            pattern: None,
2820                            field_value: None,
2821                            data: rule_data,
2822                        });
2823                    }
2824                }
2825            }
2826        }
2827    }
2828}
2829
2830/// Validation error for a field
2831#[derive(Debug, Clone, Serialize, Deserialize)]
2832pub struct ValidationError {
2833    #[serde(rename = "type")]
2834    pub rule_type: String,
2835    pub message: String,
2836    #[serde(skip_serializing_if = "Option::is_none")]
2837    pub code: Option<String>,
2838    #[serde(skip_serializing_if = "Option::is_none")]
2839    pub pattern: Option<String>,
2840    #[serde(skip_serializing_if = "Option::is_none")]
2841    pub field_value: Option<String>,
2842    #[serde(skip_serializing_if = "Option::is_none")]
2843    pub data: Option<Value>,
2844}
2845
2846/// Result of validation
2847#[derive(Debug, Clone, Serialize, Deserialize)]
2848pub struct ValidationResult {
2849    pub has_error: bool,
2850    pub errors: IndexMap<String, ValidationError>,
2851}
2852