hel 0.2.0

HEL — Heuristic Expression Language: a deterministic, auditable expression language & parser, AST, builtin registry and evaluator.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
//! HEL — Heuristics Expression Language
//!
//! A deterministic, auditable expression language designed for security analysis,
//! rule engines, and policy evaluation systems.
//!
//! # Features
//!
//! - **Simple Expression Evaluation**: Validate and evaluate boolean expressions with facts
//! - **Script Support**: Multi-line scripts with reusable let bindings
//! - **Type-Safe**: Strong typing with compile-time guarantees
//! - **Deterministic**: Stable evaluation order, reproducible results
//! - **Auditable**: Comprehensive trace capture for debugging and compliance
//! - **Extensible**: Plugin architecture for domain-specific built-in functions
//!
//! # Quick Start
//!
//! ## Expression Validation
//!
//! ```
//! use hel::validate_expression;
//!
//! // Validate syntax without evaluation
//! let expr = r#"binary.arch == "x86_64" AND security.nx == false"#;
//! assert!(validate_expression(expr).is_ok());
//! ```
//!
//! ## Expression Evaluation
//!
//! ```
//! use hel::{evaluate, FactsEvalContext, Value};
//!
//! let mut ctx = FactsEvalContext::new();
//! ctx.add_fact("binary.arch", Value::String("x86_64".into()));
//! ctx.add_fact("security.nx", Value::Bool(false));
//!
//! let expr = r#"binary.arch == "x86_64" AND security.nx == false"#;
//! let result = evaluate(expr, &ctx).expect("evaluation failed");
//! assert!(result);
//! ```
//!
//! ## Script Evaluation with Let Bindings
//!
//! ```
//! use hel::{evaluate_script, FactsEvalContext, Value};
//!
//! let mut ctx = FactsEvalContext::new();
//! ctx.add_fact("manifest.permissions", Value::List(vec![
//!     Value::String("READ_SMS".into()),
//! ]));
//! ctx.add_fact("binary.entropy", Value::Number(8.0));
//!
//! let script = r#"
//!     let has_sms = manifest.permissions CONTAINS "READ_SMS"
//!     let has_obfuscation = binary.entropy > 7.5
//!     has_sms AND has_obfuscation
//! "#;
//!
//! let result = evaluate_script(script, &ctx).expect("evaluation failed");
//! assert!(result);
//! ```
//!
//! # Architecture
//!
//! HEL is designed as a modular expression language with several key components:
//!
//! ## Core Components
//!
//! - **Parser**: Pest-based grammar for parsing HEL expressions
//! - **AST**: Compact Abstract Syntax Tree representation
//! - **Evaluator**: Deterministic expression evaluation engine
//! - **Resolver**: Trait-based attribute resolution for custom integrations
//!
//! ## Extension Systems
//!
//! - **Built-ins**: Pluggable function registry for domain-specific operations
//! - **Schema**: Type definitions for data validation
//! - **Packages**: Modular schema distribution and loading
//! - **Trace**: Audit trail generation for compliance and debugging
//!
//! # Advanced Usage
//!
//! ## Custom Built-in Functions
//!
//! ```
//! use hel::{BuiltinsProvider, BuiltinFn, Value, EvalError};
//! use std::collections::BTreeMap;
//! use std::sync::Arc;
//!
//! struct MyProvider;
//!
//! impl BuiltinsProvider for MyProvider {
//!     fn namespace(&self) -> &str { "custom" }
//!
//!     fn get_builtins(&self) -> BTreeMap<String, BuiltinFn> {
//!         let mut map = BTreeMap::new();
//!         map.insert("double".to_string(), Arc::new(|args: &[Value]| {
//!             match args.get(0) {
//!                 Some(Value::Number(n)) => Ok(Value::Number(n * 2.0)),
//!                 _ => Err(EvalError::InvalidOperation("Expected number".to_string())),
//!             }
//!         }) as BuiltinFn);
//!         map
//!     }
//! }
//! ```
//!
//! ## Evaluation Tracing
//!
//! ```
//! use hel::{evaluate_with_trace, HelResolver, Value};
//!
//! struct MyResolver;
//! impl HelResolver for MyResolver {
//!     fn resolve_attr(&self, object: &str, field: &str) -> Option<Value> {
//!         match (object, field) {
//!             ("binary", "format") => Some(Value::String("elf".into())),
//!             _ => None,
//!         }
//!     }
//! }
//!
//! let trace = evaluate_with_trace(
//!     r#"binary.format == "elf""#,
//!     &MyResolver,
//!     None
//! ).expect("trace failed");
//!
//! assert!(trace.result);
//! assert_eq!(trace.atoms.len(), 1);
//! ```

use pest::iterators::Pair;
use pest::Parser;
use pest_derive::Parser;
use std::collections::BTreeMap;
use std::sync::Arc;

pub mod schema;
pub use schema::{
    package::{PackageError, PackageManifest, PackageRegistry, SchemaPackage, TypeEnvironment},
    parse_schema, FieldDef, FieldType, Schema, TypeDef,
};

pub mod builtins;
pub use builtins::{BuiltinFn, BuiltinsProvider, BuiltinsRegistry, CoreBuiltinsProvider};

pub mod trace;
pub use trace::{evaluate_with_trace, AtomTrace as TraceAtom, EvalTrace};

/// HEL parser generated by Pest
///
/// This parser is automatically generated from the `hel.pest` grammar file.
/// It provides the low-level parsing functionality for HEL expressions.
///
/// # Note
///
/// Most users should use the higher-level APIs like `validate_expression()`,
/// `parse_expression()`, or `parse_script()` instead of using this parser directly.
#[derive(Parser)]
#[grammar = "hel.pest"]
pub struct HelParser;

/// Abstract Syntax Tree node representing a parsed HEL expression
///
/// This enum represents all possible nodes in a HEL expression AST.
/// Each variant corresponds to a different syntactic construct in the language.
///
/// # Examples
///
/// ```
/// use hel::{parse_expression, AstNode};
///
/// let expr = r#"binary.format == "elf""#;
/// let ast = parse_expression(expr).expect("parse failed");
///
/// // The AST can be inspected or manipulated
/// match ast {
///     AstNode::Comparison { .. } => println!("It's a comparison"),
///     _ => println!("Something else"),
/// }
/// ```
#[derive(Debug, Clone)]
pub enum AstNode {
    /// Boolean literal (true or false)
    Bool(bool),
    /// String literal
    String(Arc<str>),
    /// Integer number literal
    Number(u64),
    /// Float number (f64)
    Float(f64),
    /// Identifier (variable name or unqualified reference)
    Identifier(Arc<str>),
    /// Attribute access (object.field notation)
    Attribute {
        /// Object name
        object: Arc<str>,
        /// Field name
        field: Arc<str>,
    },
    /// Comparison expression (left op right)
    Comparison {
        /// Left operand
        left: Box<AstNode>,
        /// Comparison operator
        op: Comparator,
        /// Right operand
        right: Box<AstNode>,
    },
    /// Logical AND expression
    And(Vec<AstNode>),
    /// Logical OR expression
    Or(Vec<AstNode>),
    /// List literal: [1, 2, 3] or ["a", "b"]
    ListLiteral(Vec<AstNode>),
    /// Map literal: {"key": value, ...}
    MapLiteral(Vec<(Arc<str>, AstNode)>),
    /// Function call: namespace.function(args) or function(args)
    FunctionCall {
        /// Namespace (if qualified, e.g., "core" in core.len)
        namespace: Option<Arc<str>>,
        /// Function name
        name: Arc<str>,
        /// Arguments
        args: Vec<AstNode>,
    },
}

/// Comparison operators supported by HEL
///
/// These operators are used in comparison expressions to compare two values.
///
/// # Examples
///
/// ```
/// use hel::evaluate;
/// use hel::FactsEvalContext;
/// use hel::Value;
///
/// let mut ctx = FactsEvalContext::new();
///
/// // FactsEvalContext resolves attributes of the form "object.field"
/// ctx.add_fact("vars.x", 10.0.into());
/// ctx.add_fact("vars.y", 20.0.into());
///
/// // Equality: ==
/// assert!(evaluate(r#"vars.x == 10"#, &ctx).unwrap());
///
/// // Less than: <
/// assert!(evaluate(r#"vars.x < vars.y"#, &ctx).unwrap());
///
/// // Contains (for lists and strings)
/// ctx.add_fact("vars.list", Value::List(vec![1.0.into(), 2.0.into()]));
/// assert!(evaluate(r#"vars.list CONTAINS 1"#, &ctx).unwrap());
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Comparator {
    /// Equality (==)
    Eq,
    /// Inequality (!=)
    Ne,
    /// Greater than (>)
    Gt,
    /// Greater than or equal (>=)
    Ge,
    /// Less than (<)
    Lt,
    /// Less than or equal (<=)
    Le,
    /// Contains operator (CONTAINS)
    Contains,
    /// IN operator for membership tests (e.g., "a" IN ["a", "b"])
    In,
}

/// Runtime value type for HEL evaluation
///
/// Represents all possible values that can be produced or consumed during
/// expression evaluation. Values are used for literals, attribute resolution,
/// function arguments and results.
///
/// # Examples
///
/// ```
/// use hel::Value;
/// use std::sync::Arc;
///
/// // Create different value types
/// let null_val = Value::Null;
/// let bool_val = Value::Bool(true);
/// let string_val = Value::String(Arc::from("hello"));
/// let number_val = Value::Number(42.5);
/// let list_val = Value::List(vec![Value::Number(1.0), Value::Number(2.0)]);
/// ```
///
/// # Conversions
///
/// The `Value` type implements `From` for common Rust types for convenience:
///
/// ```
/// use hel::Value;
///
/// let s: Value = "hello".into();
/// let b: Value = true.into();
/// let n: Value = 42.5.into();
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    /// Null value (represents missing or undefined data)
    Null,
    /// Boolean value (true or false)
    Bool(bool),
    /// String value
    String(Arc<str>),
    /// Numeric value (stored as f64)
    Number(f64),
    /// List of values
    List(Vec<Value>),
    /// Map of string keys to values
    Map(BTreeMap<Arc<str>, Value>),
}

/// Resolver interface for host integration
///
/// Products implement this trait to provide values for attribute access
/// in HEL expressions. This decouples HEL from domain-specific facts.
pub trait HelResolver {
    /// Resolve an attribute path (object.field) to a value
    ///
    /// Returns `Some(Value)` if the attribute exists, `None` if missing.
    /// Missing attributes are treated as `Null` by the evaluator.
    fn resolve_attr(&self, object: &str, field: &str) -> Option<Value>;
}

/// Evaluation context that includes resolver and optional built-ins registry
///
/// This is the low-level evaluation context used internally. Most users should
/// use `FactsEvalContext` and the `evaluate()` function instead.
///
/// # Examples
///
/// ```
/// use hel::{EvalContext, HelResolver, Value};
///
/// struct MyResolver;
/// impl HelResolver for MyResolver {
///     fn resolve_attr(&self, object: &str, field: &str) -> Option<Value> {
///         match (object, field) {
///             ("binary", "arch") => Some(Value::String("x86_64".into())),
///             _ => None,
///         }
///     }
/// }
///
/// let resolver = MyResolver;
/// let ctx = EvalContext::new(&resolver);
/// ```
pub struct EvalContext<'a> {
    resolver: &'a dyn HelResolver,
    builtins: Option<&'a builtins::BuiltinsRegistry>,
    /// Variable bindings for let expressions (name -> value)
    variables: BTreeMap<Arc<str>, Value>,
}

impl<'a> EvalContext<'a> {
    /// Create a context with just a resolver (no built-ins)
    pub fn new(resolver: &'a dyn HelResolver) -> Self {
        Self {
            resolver,
            builtins: None,
            variables: BTreeMap::new(),
        }
    }

    /// Create a context with both resolver and built-ins registry
    pub fn with_builtins(
        resolver: &'a dyn HelResolver,
        builtins: &'a builtins::BuiltinsRegistry,
    ) -> Self {
        Self {
            resolver,
            builtins: Some(builtins),
            variables: BTreeMap::new(),
        }
    }

    /// Add a variable binding to the context
    fn with_variable(mut self, name: Arc<str>, value: Value) -> Self {
        self.variables.insert(name, value);
        self
    }

    /// Get a variable by name
    fn get_variable(&self, name: &str) -> Option<&Value> {
        self.variables.get(name)
    }
}

/// Error type for HEL evaluation (legacy)
///
/// This error type is used by the low-level evaluation functions.
/// For higher-level APIs, use `HelError` which provides better error information.
///
/// # Variants
///
/// - `UnknownAttribute`: Attempted to access a non-existent attribute
/// - `TypeMismatch`: Operation received wrong type (e.g., comparing string to number)
/// - `InvalidOperation`: Operation not supported (e.g., calling undefined function)
/// - `ParseError`: Expression parsing failed
#[derive(Debug, Clone)]
pub enum EvalError {
    /// Unknown attribute was accessed
    UnknownAttribute {
        /// Object name
        object: String,
        /// Field name
        field: String,
    },
    /// Type mismatch in operation
    TypeMismatch {
        /// Expected type
        expected: String,
        /// Actual type received
        got: String,
        /// Context where mismatch occurred
        context: String,
    },
    /// Invalid operation attempted
    InvalidOperation(String),
    /// Parse error occurred
    ParseError(String),
}

impl std::fmt::Display for EvalError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EvalError::UnknownAttribute { object, field } => {
                write!(f, "Unknown attribute: {}.{}", object, field)
            }
            EvalError::TypeMismatch {
                expected,
                got,
                context,
            } => {
                write!(
                    f,
                    "Type mismatch in {}: expected {}, got {}",
                    context, expected, got
                )
            }
            EvalError::InvalidOperation(msg) => write!(f, "Invalid operation: {}", msg),
            EvalError::ParseError(msg) => write!(f, "Parse error: {}", msg),
        }
    }
}

impl std::error::Error for EvalError {}

/// Enhanced error type for HEL with line/column information
///
/// This error type is returned by the high-level APIs like `validate_expression()`,
/// `parse_expression()`, `evaluate()`, and `evaluate_script()`.
///
/// It provides detailed error information including optional line and column numbers
/// for parse errors, making it easier to debug expression syntax issues.
///
/// # Examples
///
/// ```
/// use hel::validate_expression;
///
/// let bad_expr = "(unclosed";
/// match validate_expression(bad_expr) {
///     Err(e) => {
///         println!("Error: {}", e.message);
///         if let (Some(line), Some(col)) = (e.line, e.column) {
///             println!("At line {}, column {}", line, col);
///         }
///     }
///     Ok(_) => println!("Valid!"),
/// }
/// ```
#[derive(Debug, Clone)]
pub struct HelError {
    /// Error message describing what went wrong
    pub message: String,
    /// Line number where error occurred (for parse errors)
    pub line: Option<usize>,
    /// Column number where error occurred (for parse errors)
    pub column: Option<usize>,
    /// Kind of error that occurred
    pub kind: ErrorKind,
}

/// Classification of HEL errors
///
/// Categorizes errors into different types for easier handling.
#[derive(Debug, Clone)]
pub enum ErrorKind {
    /// Parse error (syntax error in expression or script)
    ParseError,
    /// Evaluation error (runtime error during expression evaluation)
    EvaluationError,
    /// Type error (type mismatch or incompatible operation)
    TypeError,
    /// Unknown attribute (attempted to access non-existent field)
    UnknownAttribute,
}

impl HelError {
    /// Create a parse error without location information
    pub fn parse_error(message: String) -> Self {
        Self {
            message,
            line: None,
            column: None,
            kind: ErrorKind::ParseError,
        }
    }

    /// Create a parse error with line and column information
    pub fn parse_error_at(message: String, line: usize, column: usize) -> Self {
        Self {
            message,
            line: Some(line),
            column: Some(column),
            kind: ErrorKind::ParseError,
        }
    }

    /// Create an evaluation error
    pub fn eval_error(message: String) -> Self {
        Self {
            message,
            line: None,
            column: None,
            kind: ErrorKind::EvaluationError,
        }
    }

    /// Create a type error
    pub fn type_error(message: String) -> Self {
        Self {
            message,
            line: None,
            column: None,
            kind: ErrorKind::TypeError,
        }
    }

    /// Create an unknown attribute error
    pub fn unknown_attribute(message: String) -> Self {
        Self {
            message,
            line: None,
            column: None,
            kind: ErrorKind::UnknownAttribute,
        }
    }
}

impl std::fmt::Display for HelError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let (Some(line), Some(column)) = (self.line, self.column) {
            write!(
                f,
                "HEL {:?} at line {}, column {}: {}",
                self.kind, line, column, self.message
            )
        } else {
            write!(f, "HEL {:?}: {}", self.kind, self.message)
        }
    }
}

impl std::error::Error for HelError {}

impl From<EvalError> for HelError {
    fn from(err: EvalError) -> Self {
        match err {
            EvalError::ParseError(msg) => HelError::parse_error(msg),
            EvalError::TypeMismatch {
                expected,
                got,
                context,
            } => HelError::type_error(format!(
                "Type mismatch in {}: expected {}, got {}",
                context, expected, got
            )),
            EvalError::UnknownAttribute { object, field } => {
                HelError::unknown_attribute(format!("Unknown attribute: {}.{}", object, field))
            }
            EvalError::InvalidOperation(msg) => HelError::eval_error(msg),
        }
    }
}

/// Parse a HEL expression into an AST (low-level API)
///
/// This is a low-level parsing function that parses a HEL expression directly
/// into an AST without validation. It will panic on parse errors.
///
/// # Panics
///
/// Panics if the input cannot be parsed as a valid HEL expression.
///
/// # Note
///
/// Most users should use `parse_expression()` or `validate_expression()` instead,
/// which return `Result` types and provide better error handling.
///
/// # Examples
///
/// ```
/// use hel::parse_rule;
///
/// let ast = parse_rule(r#"binary.format == "elf""#);
/// ```
pub fn parse_rule(input: &str) -> AstNode {
    let mut pairs = HelParser::parse(Rule::condition, input).expect("parse error");
    build_ast(pairs.next().unwrap())
}

fn build_ast(pair: Pair<Rule>) -> AstNode {
    match pair.as_rule() {
        Rule::condition => {
            let mut inner = pair.into_inner();
            let next = inner.next().expect("Empty condition");
            build_ast(next)
        }

        Rule::logical_and | Rule::logical_or => {
            let is_and = pair.as_rule() == Rule::logical_and;
            let nodes: Vec<AstNode> = pair
                .into_inner()
                .filter_map(|inner| match inner.as_rule() {
                    Rule::and_op | Rule::or_op => None,
                    _ => Some(build_ast(inner)),
                })
                .collect();

            if is_and {
                AstNode::And(nodes)
            } else {
                AstNode::Or(nodes)
            }
        }

        Rule::comparison => {
            let mut inner = pair.into_inner();
            let left = build_ast(inner.next().expect("Missing left operand"));
            let op = parse_comparator(inner.next().expect("Missing comparator"));
            let right = build_ast(inner.next().expect("Missing right operand"));

            AstNode::Comparison {
                left: Box::new(left),
                op,
                right: Box::new(right),
            }
        }

        Rule::attribute_access => {
            let mut inner = pair.into_inner();
            let object = inner.next().expect("Missing object").as_str();
            let field = inner.next().expect("Missing field").as_str();
            AstNode::Attribute {
                object: object.into(),
                field: field.into(),
            }
        }

        Rule::literal => {
            let inner_pair = pair.into_inner().next().expect("Empty literal");
            build_ast(inner_pair)
        }

        Rule::string_literal => AstNode::String(pair.as_str().trim_matches('"').into()),

        Rule::float_literal => {
            let val = pair.as_str().parse::<f64>().expect("invalid float");
            AstNode::Float(val)
        }

        Rule::number_literal => {
            let num_str = pair.as_str();
            match parse_number(num_str) {
                Some(n) => AstNode::Number(n),
                None => panic!("Failed to parse number literal: '{}'", num_str),
            }
        }

        Rule::boolean_literal => AstNode::Bool(pair.as_str() == "true"),

        Rule::list_literal => {
            let elements: Vec<AstNode> = pair.into_inner().map(|p| build_ast(p)).collect();
            AstNode::ListLiteral(elements)
        }

        Rule::map_literal => {
            let mut entries = Vec::new();
            for entry_pair in pair.into_inner() {
                if entry_pair.as_rule() == Rule::map_entry {
                    let mut entry_inner = entry_pair.into_inner();
                    let key_pair = entry_inner.next().expect("Missing map key");
                    let key = key_pair.as_str().trim_matches('"').into();
                    let value = build_ast(entry_inner.next().expect("Missing map value"));
                    entries.push((key, value));
                }
            }
            AstNode::MapLiteral(entries)
        }

        Rule::function_call => {
            let mut inner = pair.into_inner();
            let first = inner.next().expect("Missing function name");

            // Check if second element exists (namespace.function case)
            let second = inner.next();
            let (namespace, name, remaining_args) = if second.is_some() {
                (
                    Some(Arc::from(first.as_str())),
                    Arc::from(second.unwrap().as_str()),
                    inner,
                )
            } else {
                (None, Arc::from(first.as_str()), inner)
            };

            // Parse arguments from remaining items
            let args: Vec<AstNode> = remaining_args.map(|arg| build_ast(arg)).collect();

            AstNode::FunctionCall {
                namespace,
                name,
                args,
            }
        }

        Rule::identifier | Rule::variable | Rule::symbolic => {
            AstNode::Identifier(pair.as_str().into())
        }

        Rule::primary | Rule::comparison_term | Rule::term | Rule::parenthesized => {
            build_ast(pair.into_inner().next().expect("Empty wrapper"))
        }

        _ => unreachable!("Unhandled rule: {:?}", pair.as_rule()),
    }
}

fn parse_comparator(pair: Pair<Rule>) -> Comparator {
    let token = pair.as_str().trim();
    match token {
        "==" => Comparator::Eq,
        "!=" => Comparator::Ne,
        ">" => Comparator::Gt,
        ">=" => Comparator::Ge,
        "<" => Comparator::Lt,
        "<=" => Comparator::Le,
        "CONTAINS" => Comparator::Contains,
        "IN" => Comparator::In,
        _ => panic!(
            "Unhandled comparator: {}. Supported comparators: ==, !=, >, >=, <, <=, CONTAINS, IN",
            token
        ),
    }
}

// ============================================================================
// Evaluation APIs (resolver-based, low-level)
// ============================================================================

/// Evaluate a HEL expression with a custom resolver (low-level API)
///
/// This function evaluates a HEL expression using a custom resolver to provide
/// attribute values. It does not support built-in functions.
///
/// # Arguments
///
/// * `condition` - The HEL expression to evaluate
/// * `resolver` - Implementation of `HelResolver` to provide attribute values
///
/// # Returns
///
/// Returns `Ok(true)` if the condition evaluates to true, `Ok(false)` otherwise.
/// Returns `Err` if evaluation fails due to type mismatches or other errors.
///
/// # Note
///
/// Most users should use the simpler `evaluate()` function with `FactsEvalContext` instead.
///
/// # Examples
///
/// ```
/// use hel::{evaluate_with_resolver, HelResolver, Value};
///
/// struct MyResolver;
/// impl HelResolver for MyResolver {
///     fn resolve_attr(&self, object: &str, field: &str) -> Option<Value> {
///         match (object, field) {
///             ("binary", "arch") => Some(Value::String("x86_64".into())),
///             _ => None,
///         }
///     }
/// }
///
/// let result = evaluate_with_resolver(
///     r#"binary.arch == "x86_64""#,
///     &MyResolver
/// ).expect("evaluation failed");
/// assert!(result);
/// ```
pub fn evaluate_with_resolver(
    condition: &str,
    resolver: &dyn HelResolver,
) -> Result<bool, EvalError> {
    let ast = parse_rule(condition);
    let ctx = EvalContext::new(resolver);
    evaluate_ast_with_context(&ast, &ctx)
}

/// Evaluate a HEL expression with resolver and built-in functions (low-level API)
///
/// This function evaluates a HEL expression using both a custom resolver and
/// a built-ins registry to support function calls.
///
/// # Arguments
///
/// * `condition` - The HEL expression to evaluate
/// * `resolver` - Implementation of `HelResolver` to provide attribute values
/// * `builtins` - Registry of built-in functions
///
/// # Returns
///
/// Returns `Ok(true)` if the condition evaluates to true, `Ok(false)` otherwise.
/// Returns `Err` if evaluation fails.
///
/// # Examples
///
/// ```
/// use hel::{evaluate_with_context, HelResolver, Value, BuiltinsRegistry, CoreBuiltinsProvider};
///
/// struct MyResolver;
/// impl HelResolver for MyResolver {
///     fn resolve_attr(&self, _: &str, _: &str) -> Option<Value> { None }
/// }
///
/// let mut registry = BuiltinsRegistry::new();
/// registry.register(&CoreBuiltinsProvider).expect("register failed");
///
/// let result = evaluate_with_context(
///     r#"core.len(["a", "b"]) == 2"#,
///     &MyResolver,
///     &registry
/// ).expect("evaluation failed");
/// assert!(result);
/// ```
pub fn evaluate_with_context(
    condition: &str,
    resolver: &dyn HelResolver,
    builtins: &builtins::BuiltinsRegistry,
) -> Result<bool, EvalError> {
    let ast = parse_rule(condition);
    let ctx = EvalContext::with_builtins(resolver, builtins);
    evaluate_ast_with_context(&ast, &ctx)
}

fn evaluate_ast_with_context(ast: &AstNode, ctx: &EvalContext) -> Result<bool, EvalError> {
    match ast {
        AstNode::Bool(b) => Ok(*b),
        AstNode::And(nodes) => {
            for node in nodes {
                if !evaluate_ast_with_context(node, ctx)? {
                    return Ok(false);
                }
            }
            Ok(true)
        }
        AstNode::Or(nodes) => {
            for node in nodes {
                if evaluate_ast_with_context(node, ctx)? {
                    return Ok(true);
                }
            }
            Ok(false)
        }
        AstNode::Comparison { left, op, right } => {
            evaluate_comparison_with_context(left, *op, right, ctx)
        }
        // Handle identifiers and other nodes that might evaluate to boolean
        other => {
            let value = eval_node_to_value_with_context(other, ctx)?;
            match value {
                Value::Bool(b) => Ok(b),
                _ => Err(EvalError::TypeMismatch {
                    expected: "boolean".to_string(),
                    got: format!("{:?}", value),
                    context: "boolean expression context".to_string(),
                }),
            }
        }
    }
}

fn evaluate_comparison_with_context(
    left: &AstNode,
    op: Comparator,
    right: &AstNode,
    ctx: &EvalContext,
) -> Result<bool, EvalError> {
    let left_val = eval_node_to_value_with_context(left, ctx)?;
    let right_val = eval_node_to_value_with_context(right, ctx)?;
    Ok(compare_new_values(&left_val, &right_val, op))
}

pub(crate) fn eval_node_to_value_with_context(
    node: &AstNode,
    ctx: &EvalContext,
) -> Result<Value, EvalError> {
    match node {
        AstNode::Bool(b) => Ok(Value::Bool(*b)),
        AstNode::String(s) => Ok(Value::String(s.clone())),
        AstNode::Number(n) => Ok(Value::Number(*n as f64)),
        AstNode::Float(f) => Ok(Value::Number(*f)),
        AstNode::Identifier(s) => {
            // First check if this is a variable binding
            if let Some(value) = ctx.get_variable(s) {
                Ok(value.clone())
            } else {
                // Otherwise treat it as a string literal
                Ok(Value::String(s.clone()))
            }
        }
        AstNode::Attribute { object, field } => Ok(ctx
            .resolver
            .resolve_attr(object, field)
            .unwrap_or(Value::Null)),
        AstNode::ListLiteral(elements) => {
            let values: Result<Vec<Value>, EvalError> = elements
                .iter()
                .map(|e| eval_node_to_value_with_context(e, ctx))
                .collect();
            Ok(Value::List(values?))
        }
        AstNode::MapLiteral(entries) => {
            let mut map = BTreeMap::new();
            for (key, value_node) in entries {
                let value = eval_node_to_value_with_context(value_node, ctx)?;
                map.insert(key.clone(), value);
            }
            Ok(Value::Map(map))
        }
        // Handle boolean expressions (Comparison, And, Or)
        AstNode::Comparison { .. } | AstNode::And(_) | AstNode::Or(_) => {
            // Evaluate as boolean and wrap in Value::Bool
            let bool_result = evaluate_ast_with_context(node, ctx)?;
            Ok(Value::Bool(bool_result))
        }
        AstNode::FunctionCall {
            namespace,
            name,
            args,
        } => {
            // Evaluate arguments
            let arg_values: Result<Vec<Value>, EvalError> = args
                .iter()
                .map(|arg| eval_node_to_value_with_context(arg, ctx))
                .collect();
            let arg_values = arg_values?;

            // Call built-in function if registry is available
            if let Some(builtins) = ctx.builtins {
                let ns = namespace.as_ref().map(|s| s.as_ref()).unwrap_or("core");
                builtins.call(ns, name, &arg_values)
            } else {
                Err(EvalError::InvalidOperation(format!(
                    "Function calls not supported without built-ins registry: {}.{}",
                    namespace.as_ref().map(|s| s.as_ref()).unwrap_or("core"),
                    name
                )))
            }
        }
    }
}

pub(crate) fn compare_new_values(left: &Value, right: &Value, op: Comparator) -> bool {
    match op {
        Comparator::Eq => match (left, right) {
            (Value::Null, Value::Null) => true,
            (Value::Null, _) | (_, Value::Null) => false,
            (Value::Bool(l), Value::Bool(r)) => l == r,
            (Value::String(l), Value::String(r)) => l == r,
            (Value::Number(l), Value::Number(r)) => {
                if l.is_nan() || r.is_nan() {
                    return false;
                }
                l == r
            }
            _ => false,
        },
        Comparator::Ne => !compare_new_values(left, right, Comparator::Eq),
        Comparator::Contains => match (left, right) {
            (Value::String(l), Value::String(r)) => l.contains(&**r),
            (Value::List(list), val) => list
                .iter()
                .any(|item| compare_new_values(item, val, Comparator::Eq)),
            (Value::Map(map), Value::String(key)) => map.contains_key(key),
            _ => false,
        },
        Comparator::In => match (left, right) {
            (val, Value::List(list)) => list
                .iter()
                .any(|item| compare_new_values(val, item, Comparator::Eq)),
            (Value::String(s), Value::String(haystack)) => haystack.contains(&**s),
            _ => false,
        },
        Comparator::Gt | Comparator::Ge | Comparator::Lt | Comparator::Le => match (left, right) {
            (Value::Number(l), Value::Number(r)) => {
                if l.is_nan() || r.is_nan() {
                    return false;
                }
                match op {
                    Comparator::Gt => l > r,
                    Comparator::Ge => l >= r,
                    Comparator::Lt => l < r,
                    Comparator::Le => l <= r,
                    _ => false,
                }
            }
            _ => false,
        },
    }
}

fn parse_number(val: &str) -> Option<u64> {
    let val = val.trim();
    if let Some(stripped) = val.strip_prefix("0x").or_else(|| val.strip_prefix("0X")) {
        u64::from_str_radix(stripped, 16).ok()
    } else {
        val.parse::<u64>().ok()
    }
}

// ============================================================================
// New Public APIs for Expression Validation and Evaluation
// ============================================================================

/// Represents a parsed HEL expression
pub type Expression = AstNode;

/// Validates HEL expression syntax without evaluation
///
/// Returns `Ok(())` if syntax is valid, `Err` with detailed parse error if invalid.
///
/// # Examples
///
/// ```
/// use hel::validate_expression;
///
/// let expr = r#"binary.arch == "x86_64" AND security.nx == false"#;
/// assert!(validate_expression(expr).is_ok());
///
/// // Use genuinely invalid syntax (not just a string literal),
/// // so the parser must return an error.
/// let bad_expr = "(";
/// assert!(validate_expression(bad_expr).is_err());
/// ```
pub fn validate_expression(expr: &str) -> Result<(), HelError> {
    match HelParser::parse(Rule::condition, expr) {
        Ok(_) => Ok(()),
        Err(e) => {
            let (line, column) = match &e.line_col {
                pest::error::LineColLocation::Pos((l, c)) => (*l, *c),
                pest::error::LineColLocation::Span((l, c), _) => (*l, *c),
            };

            Err(HelError::parse_error_at(
                format!("{}", e.variant),
                line,
                column,
            ))
        }
    }
}

/// Parse a HEL expression into an AST (for advanced use cases)
///
/// Returns the parsed AST if successful, or a detailed parse error.
///
/// # Examples
///
/// ```
/// use hel::parse_expression;
///
/// let expr = r#"binary.format == "elf""#;
/// let ast = parse_expression(expr).expect("parse failed");
/// ```
pub fn parse_expression(expr: &str) -> Result<Expression, HelError> {
    validate_expression(expr)?;
    Ok(parse_rule(expr))
}

/// Evaluation context with facts/data for expression evaluation
///
/// Provides a simple key-value store for facts that can be referenced
/// in HEL expressions.
///
/// # Examples
///
/// ```
/// use hel::{FactsEvalContext, Value};
///
/// let mut ctx = FactsEvalContext::new();
/// ctx.add_fact("binary.arch", Value::String("x86_64".into()));
/// ctx.add_fact("security.nx", Value::Bool(false));
/// ```
pub struct FactsEvalContext {
    facts: BTreeMap<String, Value>,
}

impl FactsEvalContext {
    /// Create a new empty evaluation context
    pub fn new() -> Self {
        Self {
            facts: BTreeMap::new(),
        }
    }

    /// Add a fact to the context
    pub fn add_fact(&mut self, key: &str, value: Value) {
        self.facts.insert(key.to_string(), value);
    }

    /// Create a context from JSON data
    ///
    /// **Note**: This method is currently not implemented and will return an empty context.
    /// A full implementation would require the `serde_json` dependency.
    ///
    /// The JSON should be an object where keys are fact names (e.g., "binary.arch")
    /// and values are the fact values.
    ///
    /// # TODO
    ///
    /// Implement proper JSON parsing once serde_json is added as a dependency.
    pub fn from_json(_json: &str) -> Result<Self, HelError> {
        // Placeholder implementation
        // TODO: Implement proper JSON parsing with serde_json
        Ok(Self::new())
    }
}

impl Default for FactsEvalContext {
    fn default() -> Self {
        Self::new()
    }
}

impl HelResolver for FactsEvalContext {
    fn resolve_attr(&self, object: &str, field: &str) -> Option<Value> {
        let key = format!("{}.{}", object, field);
        self.facts.get(&key).cloned()
    }
}

/// Evaluate expression against context
///
/// Evaluates a HEL expression using the provided facts context.
///
/// # Examples
///
/// ```
/// use hel::{evaluate, FactsEvalContext, Value};
///
/// let mut ctx = FactsEvalContext::new();
/// ctx.add_fact("binary.arch", Value::String("x86_64".into()));
/// ctx.add_fact("security.nx", Value::Bool(false));
///
/// let expr = r#"binary.arch == "x86_64" AND security.nx == false"#;
/// let result = evaluate(expr, &ctx).expect("evaluation failed");
/// assert!(result);
/// ```
pub fn evaluate(expr: &str, context: &FactsEvalContext) -> Result<bool, HelError> {
    let ast = parse_expression(expr)?;
    let ctx = EvalContext::new(context);
    evaluate_ast_with_context(&ast, &ctx).map_err(|e| e.into())
}

// ============================================================================
// Script Support (Let Bindings and Multi-Expression Scripts)
// ============================================================================

/// Represents a parsed HEL script with let bindings
#[derive(Debug, Clone)]
pub struct Script {
    /// Let bindings in the script (name -> expression)
    pub bindings: Vec<(Arc<str>, AstNode)>,
    /// Final expression that must evaluate to a boolean
    pub final_expr: AstNode,
}

/// Parse and validate a .hel script file (may contain multiple expressions, let bindings)
///
/// Scripts support let bindings for reusable sub-expressions and a final boolean expression.
///
/// **Implementation Note**: The current parser uses heuristics to determine expression boundaries,
/// which works for most cases but may have edge cases with complex multi-line expressions.
/// Future improvements could include a more robust state machine-based parser.
///
/// # Examples
///
/// ```
/// use hel::parse_script;
///
/// let script = r#"
/// let has_perms = manifest.permissions CONTAINS "READ_SMS"
/// has_perms AND binary.entropy > 7.5
/// "#;
///
/// let parsed = parse_script(script).expect("parse failed");
/// ```
pub fn parse_script(script: &str) -> Result<Script, HelError> {
    let lines: Vec<&str> = script.lines().collect();
    let mut bindings = Vec::new();
    let mut final_expr = None;

    let mut i = 0;
    while i < lines.len() {
        let line = lines[i].trim();

        // Skip empty lines and comments
        if line.is_empty() || line.starts_with('#') {
            i += 1;
            continue;
        }

        // Check for let binding
        if line.starts_with("let ") {
            // Parse: let name = expression
            let rest = line.strip_prefix("let ").unwrap().trim();

            if let Some(eq_pos) = rest.find('=') {
                let name = rest[..eq_pos].trim();
                let expr_after_eq = rest[eq_pos + 1..].trim();
                let mut expr_str = String::new();

                // Start expression string if there's content after '='
                if !expr_after_eq.is_empty() {
                    expr_str = expr_after_eq.to_string();
                }

                // Handle multi-line let expressions
                // Continue collecting lines until we hit another "let" or a potential final expression
                i += 1;
                while i < lines.len() {
                    let next_line = lines[i].trim();

                    // Skip empty lines and comments
                    if next_line.is_empty() || next_line.starts_with('#') {
                        i += 1;
                        continue;
                    }

                    // If we hit another "let", stop collecting
                    if next_line.starts_with("let ") {
                        break;
                    }

                    // If this line looks like it could be a standalone final expression
                    // (doesn't start with an operator), check if we have collected enough
                    if !expr_str.is_empty()
                        && !next_line.starts_with("AND")
                        && !next_line.starts_with("OR")
                        && !next_line.starts_with("and")
                        && !next_line.starts_with("or")
                        && !next_line.starts_with("&&")
                        && !next_line.starts_with("||")
                    {
                        // Try to parse what we have so far
                        if parse_expression(&expr_str).is_ok() {
                            // We have a complete expression, stop here
                            break;
                        }
                    }

                    // Add this line to the expression
                    if !expr_str.is_empty() {
                        expr_str.push(' ');
                    }
                    expr_str.push_str(next_line);
                    i += 1;
                }

                let expr = parse_expression(&expr_str)?;
                bindings.push((Arc::from(name), expr));
                continue;
            }
        }

        // This is the final expression
        if final_expr.is_none() {
            let mut expr_str = line.to_string();

            // Collect remaining lines as part of final expression
            i += 1;
            while i < lines.len() {
                let next_line = lines[i].trim();
                if !next_line.is_empty() && !next_line.starts_with('#') {
                    if !expr_str.is_empty() {
                        expr_str.push(' ');
                    }
                    expr_str.push_str(next_line);
                }
                i += 1;
            }

            final_expr = Some(parse_expression(&expr_str)?);
            break;
        }

        i += 1;
    }

    let final_expr = final_expr.ok_or_else(|| {
        HelError::parse_error("Script must have a final boolean expression".to_string())
    })?;

    Ok(Script {
        bindings,
        final_expr,
    })
}

/// Evaluate a script and return the final boolean result
///
/// Evaluates all let bindings in order, then evaluates the final expression.
///
/// # Examples
///
/// ```
/// use hel::{evaluate_script, FactsEvalContext, Value};
///
/// let mut ctx = FactsEvalContext::new();
/// ctx.add_fact("manifest.permissions", Value::List(vec![
///     Value::String("READ_SMS".into()),
///     Value::String("SEND_SMS".into()),
/// ]));
/// ctx.add_fact("binary.entropy", Value::Number(8.0));
///
/// let script = r#"
/// let has_sms_perms = manifest.permissions CONTAINS "READ_SMS"
/// has_sms_perms AND binary.entropy > 7.5
/// "#;
///
/// let result = evaluate_script(script, &ctx).expect("evaluation failed");
/// assert!(result);
/// ```
pub fn evaluate_script(script: &str, context: &FactsEvalContext) -> Result<bool, HelError> {
    let parsed = parse_script(script)?;

    // Start with base context
    let mut eval_ctx = EvalContext::new(context);

    // Evaluate and store let bindings
    for (name, expr) in &parsed.bindings {
        let value =
            eval_node_to_value_with_context(expr, &eval_ctx).map_err(|e| HelError::from(e))?;

        // Add variable to context
        eval_ctx = eval_ctx.with_variable(name.clone(), value);
    }

    // Evaluate final expression
    evaluate_ast_with_context(&parsed.final_expr, &eval_ctx).map_err(|e| e.into())
}

// ============================================================================
// Helper implementations
// ============================================================================

impl From<&str> for Value {
    fn from(s: &str) -> Self {
        Value::String(Arc::from(s))
    }
}

impl From<String> for Value {
    fn from(s: String) -> Self {
        Value::String(Arc::from(s.as_str()))
    }
}

impl From<bool> for Value {
    fn from(b: bool) -> Self {
        Value::Bool(b)
    }
}

impl From<f64> for Value {
    fn from(n: f64) -> Self {
        Value::Number(n)
    }
}

impl From<i32> for Value {
    fn from(n: i32) -> Self {
        Value::Number(n as f64)
    }
}

impl From<u64> for Value {
    fn from(n: u64) -> Self {
        Value::Number(n as f64)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Basic resolver used in trace tests and other unit tests
    struct TestResolver;

    impl HelResolver for TestResolver {
        fn resolve_attr(&self, object: &str, field: &str) -> Option<Value> {
            match (object, field) {
                ("binary", "format") => Some(Value::String("elf".into())),
                ("security", "nx_enabled") => Some(Value::Bool(true)),
                _ => None,
            }
        }
    }

    #[test]
    fn test_evaluate_with_trace_simple() {
        let resolver = TestResolver;
        let condition = r#"binary.format == "elf""#;

        let trace = evaluate_with_trace(condition, &resolver, None).expect("evaluation failed");

        assert!(trace.result, "Condition should evaluate to true");
        assert_eq!(trace.atoms.len(), 1, "Should have one atom");
        assert_eq!(trace.atoms[0].left, "binary.format");
        assert_eq!(trace.atoms[0].right, "\"elf\"");
        assert_eq!(trace.atoms[0].resolved_left_value, Some("elf".to_string()));
        assert_eq!(trace.atoms[0].resolved_right_value, Some("elf".to_string()));
        assert!(trace.atoms[0].atom_result);
    }

    #[test]
    fn test_resolver_number_and_list_behavior() {
        struct CustomResolver;
        impl HelResolver for CustomResolver {
            fn resolve_attr(&self, object: &str, field: &str) -> Option<Value> {
                if object == "enrichment" && field == "confidence" {
                    Some(Value::Number(0.85))
                } else if object == "tags" && field == "values" {
                    Some(Value::List(vec![
                        Value::String("security".into()),
                        Value::String("critical".into()),
                    ]))
                } else {
                    None
                }
            }
        }

        let resolver = CustomResolver;
        let cond1 = "enrichment.confidence > 0.7";
        let res1 = evaluate_with_resolver(cond1, &resolver).expect("evaluation failed");
        assert!(res1);

        let cond2 = r#"tags.values CONTAINS "critical""#;
        let res2 = evaluate_with_resolver(cond2, &resolver).expect("evaluation failed");
        assert!(res2);
    }

    #[test]
    fn test_nan_comparison_behavior() {
        struct NaNResolver;
        impl HelResolver for NaNResolver {
            fn resolve_attr(&self, object: &str, field: &str) -> Option<Value> {
                if object == "test" && field == "nan" {
                    Some(Value::Number(f64::NAN))
                } else {
                    None
                }
            }
        }

        let resolver = NaNResolver;
        let cond = "test.nan > 0.0";
        let res = evaluate_with_resolver(cond, &resolver).expect("evaluation failed");
        assert!(!res, "NaN comparison should be false");
    }

    // ========================================================================
    // Tests for new API functions
    // ========================================================================

    #[test]
    fn test_validate_expression_success() {
        let expr = r#"binary.arch == "x86_64" AND security.nx == false"#;
        assert!(validate_expression(expr).is_ok());
    }

    #[test]
    fn test_validate_expression_failure() {
        // Use an expression with genuinely invalid syntax
        let bad_expr = "(";
        let result = validate_expression(bad_expr);
        assert!(result.is_err());

        if let Err(e) = result {
            assert!(e.line.is_some());
            assert!(e.column.is_some());
        }
    }

    #[test]
    fn test_parse_expression_success() {
        let expr = r#"binary.format == "elf""#;
        let ast = parse_expression(expr).expect("parse failed");

        // The AST is returned, just verify it parsed successfully
        // The actual structure depends on the grammar
        match &ast {
            AstNode::Comparison {
                left: _,
                op,
                right: _,
            } => {
                assert_eq!(*op, Comparator::Eq);
            }
            _ => {
                // It's okay if it's wrapped in other nodes, as long as it parsed
            }
        }
    }

    #[test]
    fn test_facts_eval_context() {
        let mut ctx = FactsEvalContext::new();
        ctx.add_fact("binary.arch", Value::String("x86_64".into()));
        ctx.add_fact("security.nx", Value::Bool(false));

        // Test resolver interface
        assert_eq!(
            ctx.resolve_attr("binary", "arch"),
            Some(Value::String("x86_64".into()))
        );
        assert_eq!(ctx.resolve_attr("security", "nx"), Some(Value::Bool(false)));
    }

    #[test]
    fn test_evaluate_with_facts_context() {
        let mut ctx = FactsEvalContext::new();
        ctx.add_fact("binary.arch", "x86_64".into());
        ctx.add_fact("security.nx", false.into());

        let expr = r#"binary.arch == "x86_64" AND security.nx == false"#;
        let result = evaluate(expr, &ctx).expect("evaluation failed");
        assert!(result);
    }

    #[test]
    fn test_evaluate_with_facts_context_false() {
        let mut ctx = FactsEvalContext::new();
        ctx.add_fact("binary.arch", "arm".into());
        ctx.add_fact("security.nx", true.into());

        let expr = r#"binary.arch == "x86_64" AND security.nx == false"#;
        let result = evaluate(expr, &ctx).expect("evaluation failed");
        assert!(!result);
    }

    #[test]
    fn test_parse_script_simple() {
        let script = r#"
            let has_perms = manifest.permissions CONTAINS "READ_SMS"
            has_perms AND binary.entropy > 7.5
        "#;

        let parsed = parse_script(script).expect("parse failed");
        assert_eq!(parsed.bindings.len(), 1);
        assert_eq!(parsed.bindings[0].0.as_ref(), "has_perms");
    }

    #[test]
    fn test_parse_script_with_comments() {
        let script = r#"
            # This is a comment
            let has_perms = manifest.permissions CONTAINS "READ_SMS"

            # Another comment
            has_perms AND binary.entropy > 7.5
        "#;

        let parsed = parse_script(script).expect("parse failed");
        assert_eq!(parsed.bindings.len(), 1);
    }

    #[test]
    fn test_parse_script_multiple_bindings() {
        let script = r#"
            let has_sms_perms = manifest.permissions CONTAINS "READ_SMS"
            let has_obfuscation = binary.entropy > 7.5
            has_sms_perms AND has_obfuscation
        "#;

        let parsed = parse_script(script).expect("parse failed");
        assert_eq!(parsed.bindings.len(), 2);
        assert_eq!(parsed.bindings[0].0.as_ref(), "has_sms_perms");
        assert_eq!(parsed.bindings[1].0.as_ref(), "has_obfuscation");
    }

    #[test]
    fn test_evaluate_script_simple() {
        let mut ctx = FactsEvalContext::new();
        ctx.add_fact(
            "manifest.permissions",
            Value::List(vec![
                Value::String("READ_SMS".into()),
                Value::String("SEND_SMS".into()),
            ]),
        );
        ctx.add_fact("binary.entropy", Value::Number(8.0));

        let script = r#"
            let has_sms_perms = manifest.permissions CONTAINS "READ_SMS"
            has_sms_perms AND binary.entropy > 7.5
        "#;

        let result = evaluate_script(script, &ctx).expect("evaluation failed");
        assert!(result);
    }

    #[test]
    fn test_evaluate_script_with_multiple_bindings() {
        let mut ctx = FactsEvalContext::new();
        ctx.add_fact(
            "manifest.permissions",
            Value::List(vec![
                Value::String("READ_SMS".into()),
                Value::String("SEND_SMS".into()),
            ]),
        );
        ctx.add_fact("binary.entropy", Value::Number(8.0));
        ctx.add_fact("strings.count", Value::Number(5.0));

        let script = r#"
            let has_sms_perms = manifest.permissions CONTAINS "READ_SMS" AND manifest.permissions CONTAINS "SEND_SMS"
            let has_obfuscation = binary.entropy > 7.5 OR strings.count < 10
            has_sms_perms AND has_obfuscation
        "#;

        let result = evaluate_script(script, &ctx).expect("evaluation failed");
        assert!(result);
    }

    #[test]
    fn test_value_from_conversions() {
        let v1: Value = "test".into();
        assert_eq!(v1, Value::String("test".into()));

        let v2: Value = true.into();
        assert_eq!(v2, Value::Bool(true));

        let v3: Value = 42.5.into();
        assert_eq!(v3, Value::Number(42.5));

        let v4: Value = 42i32.into();
        assert_eq!(v4, Value::Number(42.0));
    }

    #[test]
    fn test_eval_context_variables() {
        let ctx = FactsEvalContext::new();
        let mut eval_ctx = EvalContext::new(&ctx);

        // Add a variable
        eval_ctx = eval_ctx.with_variable(Arc::from("test_var"), Value::Bool(true));

        // Verify we can retrieve it
        let result = eval_ctx.get_variable("test_var");
        assert_eq!(result, Some(&Value::Bool(true)));
    }

    #[test]
    fn test_script_let_binding_storage() {
        let ctx = FactsEvalContext::new();
        let mut eval_ctx = EvalContext::new(&ctx);

        // Simulate what happens in evaluate_script
        let name: Arc<str> = Arc::from("has_perms");
        let value = Value::Bool(true);

        eval_ctx = eval_ctx.with_variable(name.clone(), value);

        // Check if we can retrieve it
        let retrieved = eval_ctx.get_variable("has_perms");
        assert_eq!(retrieved, Some(&Value::Bool(true)));

        // Now check what happens when we evaluate an identifier
        let identifier = AstNode::Identifier(Arc::from("has_perms"));
        let result = eval_node_to_value_with_context(&identifier, &eval_ctx).unwrap();
        assert_eq!(result, Value::Bool(true));
    }
}