rs-jsonnet 0.1.22

Pure Rust implementation of Jsonnet 0.21.0 compatible with Google Jsonnet
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
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
//! Jsonnet standard library implementation

use crate::error::{JsonnetError, Result};
use crate::value::JsonnetValue;
use serde_json::json;

/// Callback trait for function calling from stdlib
pub trait FunctionCallback {
    fn call_function(&mut self, func: JsonnetValue, args: Vec<JsonnetValue>) -> Result<JsonnetValue>;
    fn call_external_function(&mut self, func: &str, args: Vec<JsonnetValue>) -> Result<JsonnetValue>;
}
use sha1::Sha1;
use sha2::{Sha256, Sha512, Digest};
use sha3::Sha3_256;
use std::collections::HashMap;

/// Standard library function implementations
pub struct StdLib;

/// Standard library with function callback support
pub struct StdLibWithCallback<'a> {
    callback: &'a mut dyn FunctionCallback,
}

impl<'a> StdLibWithCallback<'a> {
    pub fn new(callback: &'a mut dyn FunctionCallback) -> Self {
        StdLibWithCallback { callback }
    }

    /// Call a standard library function with function callback support
    pub fn call_function(&mut self, name: &str, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        match name {
            "length" => StdLib::length(args),
            "type" => StdLib::type_of(args),
            "makeArray" => StdLib::make_array(args),
            "filter" => self.filter(args),
            "map" => self.map(args),
            "foldl" => self.foldl(args),
            "foldr" => self.foldr(args),
            // ... other functions that don't need callback
            "range" => StdLib::range(args),
            "join" => self.join_variadic(args),
            "split" => StdLib::split(args),
            "contains" => self.contains_variadic(args),
            "startsWith" => StdLib::starts_with(args),
            "endsWith" => StdLib::ends_with(args),
            "toLower" => StdLib::to_lower(args),
            "toUpper" => StdLib::to_upper(args),
            "trim" => StdLib::trim(args),
            "substr" => StdLib::substr(args),
            "char" => StdLib::char_fn(args),
            "codepoint" => StdLib::codepoint(args),
            "toString" => StdLib::to_string(args),
            "parseInt" => StdLib::parse_int(args),
            "parseJson" => StdLib::parse_json(args),
            "encodeUTF8" => StdLib::encode_utf8(args),
            "decodeUTF8" => StdLib::decode_utf8(args),
            "md5" => StdLib::md5(args),
            "base64" => StdLib::base64(args),
            "base64Decode" => StdLib::base64_decode(args),
            "manifestJson" => StdLib::manifest_json(args),
            "manifestJsonEx" => StdLib::manifest_json_ex(args),
            "manifestYaml" => StdLib::manifest_yaml(args),
            "escapeStringJson" => StdLib::escape_string_json(args),
            "escapeStringYaml" => StdLib::escape_string_yaml(args),
            "escapeStringPython" => StdLib::escape_string_python(args),
            "escapeStringBash" => StdLib::escape_string_bash(args),
            "escapeStringDollars" => StdLib::escape_string_dollars(args),
            "stringChars" => StdLib::string_chars(args),
            "stringBytes" => StdLib::string_bytes(args),
            "format" => StdLib::format(args),
            "isArray" => StdLib::is_array(args),
            "isBoolean" => StdLib::is_boolean(args),
            "isFunction" => StdLib::is_function(args),
            "isNumber" => StdLib::is_number(args),
            "isObject" => StdLib::is_object(args),
            "isString" => StdLib::is_string(args),
            "count" => StdLib::count(args),
            "find" => StdLib::find(args),
            "member" => StdLib::member(args),
            "modulo" => StdLib::modulo(args),
            "pow" => StdLib::pow(args),
            "exp" => StdLib::exp(args),
            "log" => StdLib::log(args),
            "sqrt" => StdLib::sqrt(args),
            "sin" => StdLib::sin(args),
            "cos" => StdLib::cos(args),
            "tan" => StdLib::tan(args),
            "asin" => StdLib::asin(args),
            "acos" => StdLib::acos(args),
            "atan" => StdLib::atan(args),
            "floor" => StdLib::floor(args),
            "ceil" => StdLib::ceil(args),
            "round" => StdLib::round(args),
            "abs" => StdLib::abs(args),
            "max" => StdLib::max(args),
            "min" => StdLib::min(args),
            "clamp" => StdLib::clamp(args),
            "assertEqual" => StdLib::assert_equal(args),
            "trace" => StdLib::trace(args),
            "sort" => StdLib::sort(args),
            "uniq" => StdLib::uniq(args),
            "reverse" => StdLib::reverse(args),
            "mergePatch" => StdLib::merge_patch(args),
            "get" => StdLib::get(args),
            "id" => StdLib::id(args),
            "equals" => StdLib::equals(args),
            "lines" => StdLib::lines(args),
            "strReplace" => StdLib::str_replace(args),
            "sha1" => StdLib::sha1(args),
            "sha256" => StdLib::sha256(args),
            "sha3" => StdLib::sha3(args),
            "sha512" => StdLib::sha512(args),
            "asciiLower" => StdLib::ascii_lower(args),
            "asciiUpper" => StdLib::ascii_upper(args),
            "set" => StdLib::set(args),
            "flatMap" => StdLib::flat_map(args),
            "mapWithIndex" => StdLib::map_with_index(args),
            "lstripChars" => StdLib::lstrip_chars(args),
            "rstripChars" => StdLib::rstrip_chars(args),
            "stripChars" => StdLib::strip_chars(args),
            "findSubstr" => StdLib::find_substr(args),
            "repeat" => StdLib::repeat(args),
            "setMember" => StdLib::set_member(args),
            "setUnion" => StdLib::set_union(args),
            "setInter" => StdLib::set_inter(args),
            "setDiff" => StdLib::set_diff(args),
            "objectFields" => StdLib::object_fields(args),
            "objectFieldsAll" => StdLib::object_fields_all(args),
            "objectHas" => StdLib::object_has(args),
            "objectHasAll" => StdLib::object_has_all(args),
            "objectValues" => StdLib::object_values(args),
            "objectValuesAll" => StdLib::object_values_all(args),
            "objectFieldsEx" => StdLib::object_fields_ex(args),
            "objectValuesEx" => StdLib::object_values_ex(args),
            "prune" => StdLib::prune(args),
            "mapWithKey" => StdLib::map_with_key(args),
            "manifestIni" => StdLib::manifest_ini(args),
            "manifestPython" => StdLib::manifest_python(args),
            "manifestCpp" => StdLib::manifest_cpp(args),
            "manifestXmlJsonml" => StdLib::manifest_xml_jsonml(args),
            "log2" => StdLib::log2(args),
            "log10" => StdLib::log10(args),
            "log1p" => StdLib::log1p(args),
            "expm1" => StdLib::expm1(args),
            "remove" => StdLib::remove(args),
            "removeAt" => StdLib::remove_at(args),
            "flattenArrays" => StdLib::flatten_arrays(args),
            "objectKeysValues" => StdLib::object_keys_values(args),
            "objectRemoveKey" => StdLib::object_remove_key(args),
            "isInteger" => StdLib::is_integer(args),
            "isDecimal" => StdLib::is_decimal(args),
            "isEven" => StdLib::is_even(args),
            "isOdd" => StdLib::is_odd(args),
            // New functions to implement
            "slice" => self.slice(args),
            "zip" => self.zip(args),
            "transpose" => self.transpose(args),
            "flatten" => self.flatten(args),
            "sum" => self.sum(args),
            "product" => self.product(args),
            "all" => self.all(args),
            "any" => self.any(args),
            "sortBy" => self.sort_by(args),
            "groupBy" => self.group_by(args),
            "partition" => self.partition(args),
            "chunk" => self.chunk(args),
            "unique" => self.unique(args),
            "difference" => self.difference(args),
            "intersection" => self.intersection(args),
            "symmetricDifference" => self.symmetric_difference(args),
            "isSubset" => self.is_subset(args),
            "isSuperset" => self.is_superset(args),
            "isDisjoint" => self.is_disjoint(args),
            "cartesian" => self.cartesian(args),
            "cross" => self.cross(args),
            "dot" => self.dot(args),
            "norm" => self.norm(args),
            "normalize" => self.normalize(args),
            "distance" => self.distance(args),
            "angle" => self.angle(args),
            "rotate" => self.rotate(args),
            "scale" => self.scale(args),
            "translate" => self.translate(args),
            "reflect" => self.reflect(args),
            "affine" => self.affine(args),
            "splitLimit" => self.split_limit(args),
            "replace" => self.replace(args),

            // ==========================================
            // AI Agent Functions (Manimani)
            // ==========================================

            // HTTP functions
            "ai.httpGet" => StdLib::ai_http_get(args),
            "ai.httpPost" => StdLib::ai_http_post(args),

            // AI model functions
            "ai.callModel" => StdLib::ai_call_model(args),

            // Tool functions
            "tool.execute" => StdLib::tool_execute(args),

            // Memory functions
            "memory.get" => StdLib::memory_get(args),
            "memory.set" => StdLib::memory_set(args),

            // Agent functions
            "agent.create" => StdLib::agent_create(args),
            "agent.execute" => self.callback.call_external_function(name, args),

            // Chain functions
            "chain.create" => self.callback.call_external_function(name, args),
            "chain.execute" => self.callback.call_external_function(name, args),
            "db.query" => self.callback.call_external_function(name, args),
            "db.rewrite" => self.callback.call_external_function(name, args),
            "db.patch" => self.callback.call_external_function(name, args),

            _ => Err(JsonnetError::runtime_error(format!(
                "Unknown function: {}",
                name
            ))),
        }
    }

    // Higher-order functions that use function callbacks
    fn filter(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "filter")?;
        let _func = &args[0];
        let arr = args[1].as_array()?;

        let mut result = Vec::new();
        for item in arr {
            // Call func(item) and check if result is truthy
            let call_result = self.callback.call_function(_func.clone(), vec![item.clone()])?;
            if call_result.is_truthy() {
                result.push(item.clone());
            }
        }

        Ok(JsonnetValue::array(result))
    }

    fn map(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "map")?;
        let _func = &args[0];
        let arr = args[1].as_array()?;

        let mut result = Vec::new();
        for item in arr {
            // Call func(item) and collect results
            let call_result = self.callback.call_function(_func.clone(), vec![item.clone()])?;
            result.push(call_result);
        }

        Ok(JsonnetValue::array(result))
    }

    fn foldl(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 3, "foldl")?;
        let _func = &args[0];
        let arr = args[1].as_array()?;
        let mut accumulator = args[2].clone();

        for item in arr {
            // Call func(accumulator, item)
            accumulator = self.callback.call_function(_func.clone(), vec![accumulator, item.clone()])?;
        }

        Ok(accumulator)
    }

    fn foldr(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 3, "foldr")?;
        let _func = &args[0];
        let arr = args[1].as_array()?;
        let mut accumulator = args[2].clone();

        for item in arr.iter().rev() {
            // Call func(item, accumulator)
            accumulator = self.callback.call_function(_func.clone(), vec![item.clone(), accumulator])?;
        }

        Ok(accumulator)
    }

    // New utility functions
    fn slice(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        if args.len() < 2 {
            return Err(JsonnetError::invalid_function_call("slice() expects at least 2 arguments".to_string()));
        }
        let start = args[1].as_number()? as usize;

        match &args[0] {
            JsonnetValue::Array(arr) => {
                let end = if args.len() > 2 {
                    args[2].as_number()? as usize
                } else {
                    arr.len()
                };
                let start = start.min(arr.len());
                let end = end.min(arr.len());
                if start > end {
                    Ok(JsonnetValue::array(vec![]))
                } else {
                    Ok(JsonnetValue::array(arr[start..end].to_vec()))
                }
            }
            JsonnetValue::String(s) => {
                let end = if args.len() > 2 {
                    args[2].as_number()? as usize
                } else {
                    s.chars().count()
                };
                let chars: Vec<char> = s.chars().collect();
                let start = start.min(chars.len());
                let end = end.min(chars.len());
                if start > end {
                    Ok(JsonnetValue::string("".to_string()))
                } else {
                    let sliced: String = chars[start..end].iter().collect();
                    Ok(JsonnetValue::string(sliced))
                }
            }
            _ => Err(JsonnetError::invalid_function_call("slice() expects array or string as first argument".to_string())),
        }
    }

    fn zip(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        if args.is_empty() {
            return Err(JsonnetError::invalid_function_call("zip() expects at least one argument".to_string()));
        }

        // Convert all arguments to arrays
        let arrays: Result<Vec<Vec<JsonnetValue>>> = args.into_iter()
            .map(|arg| arg.as_array().cloned())
            .collect();

        let arrays = arrays?;
        if arrays.is_empty() {
            return Ok(JsonnetValue::array(vec![]));
        }

        // Find minimum length
        let min_len = arrays.iter().map(|arr| arr.len()).min().unwrap_or(0);

        // Create zipped result
        let mut result = Vec::new();
        for i in 0..min_len {
            let mut tuple = Vec::new();
            for arr in &arrays {
                tuple.push(arr[i].clone());
            }
            result.push(JsonnetValue::array(tuple));
        }

        Ok(JsonnetValue::array(result))
    }

    fn transpose(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "transpose")?;
        let matrix = args[0].as_array()?;

        if matrix.is_empty() {
            return Ok(JsonnetValue::array(vec![]));
        }

        // Check if all elements are arrays and get dimensions
        let mut max_len = 0;
        for row in matrix {
            match row {
                JsonnetValue::Array(arr) => {
                    max_len = max_len.max(arr.len());
                }
                _ => return Err(JsonnetError::invalid_function_call("transpose() expects array of arrays".to_string())),
            }
        }

        if max_len == 0 {
            return Ok(JsonnetValue::array(vec![]));
        }

        // Create transposed matrix
        let mut result = Vec::new();
        for col in 0..max_len {
            let mut new_row = Vec::new();
            for row in matrix {
                if let JsonnetValue::Array(arr) = row {
                    if col < arr.len() {
                        new_row.push(arr[col].clone());
                    } else {
                        new_row.push(JsonnetValue::Null);
                    }
                }
            }
            result.push(JsonnetValue::array(new_row));
        }

        Ok(JsonnetValue::array(result))
    }

    fn flatten(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "flatten")?;
        let depth = if args.len() > 1 {
            args[1].as_number()? as usize
        } else {
            usize::MAX
        };

        fn flatten_recursive(arr: &Vec<JsonnetValue>, current_depth: usize, max_depth: usize) -> Vec<JsonnetValue> {
            let mut result = Vec::new();
            for item in arr {
                match item {
                    JsonnetValue::Array(nested) if current_depth < max_depth => {
                        result.extend(flatten_recursive(nested, current_depth + 1, max_depth));
                    }
                    _ => result.push(item.clone()),
                }
            }
            result
        }

        let arr = args[0].as_array()?;
        let flattened = flatten_recursive(arr, 0, depth);
        Ok(JsonnetValue::array(flattened))
    }

    fn sum(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "sum")?;
        let arr = args[0].as_array()?;

        let mut total = 0.0;
        for item in arr {
            total += item.as_number()?;
        }

        Ok(JsonnetValue::number(total))
    }

    fn product(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "product")?;
        let arr = args[0].as_array()?;

        let mut result = 1.0;
        for item in arr {
            result *= item.as_number()?;
        }

        Ok(JsonnetValue::number(result))
    }

    fn all(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "all")?;
        let arr = args[0].as_array()?;

        for item in arr {
            if !item.is_truthy() {
                return Ok(JsonnetValue::boolean(false));
            }
        }

        Ok(JsonnetValue::boolean(true))
    }

    fn any(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "any")?;
        let arr = args[0].as_array()?;

        for item in arr {
            if item.is_truthy() {
                return Ok(JsonnetValue::boolean(true));
            }
        }

        Ok(JsonnetValue::boolean(false))
    }

    fn chunk(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "chunk")?;
        let arr = args[0].as_array()?;
        let size = args[1].as_number()? as usize;

        if size == 0 {
            return Err(JsonnetError::invalid_function_call("chunk() size must be positive".to_string()));
        }

        let mut result = Vec::new();
        for chunk in arr.chunks(size) {
            result.push(JsonnetValue::array(chunk.to_vec()));
        }

        Ok(JsonnetValue::array(result))
    }

    fn unique(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "unique")?;
        let arr = args[0].as_array()?;

        let mut seen = std::collections::HashSet::new();
        let mut result = Vec::new();

        for item in arr {
            // Simple equality check - in real Jsonnet this uses deep equality
            if !seen.contains(&format!("{:?}", item)) {
                seen.insert(format!("{:?}", item));
                result.push(item.clone());
            }
        }

        Ok(JsonnetValue::array(result))
    }

    fn difference(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        if args.is_empty() {
            return Ok(JsonnetValue::array(vec![]));
        }

        let first = args[0].as_array()?;
        let mut result = first.clone();

        for arg in &args[1..] {
            let other = arg.as_array()?;
            let other_set: std::collections::HashSet<String> = other.iter()
                .map(|v| format!("{:?}", v))
                .collect();

            result.retain(|item| !other_set.contains(&format!("{:?}", item)));
        }

        Ok(JsonnetValue::array(result))
    }

    fn intersection(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        if args.is_empty() {
            return Ok(JsonnetValue::array(vec![]));
        }

        let first = args[0].as_array()?;
        let mut result = first.clone();

        for arg in &args[1..] {
            let other = arg.as_array()?;
            let other_set: std::collections::HashSet<String> = other.iter()
                .map(|v| format!("{:?}", v))
                .collect();

            result.retain(|item| other_set.contains(&format!("{:?}", item)));
        }

        Ok(JsonnetValue::array(result))
    }

    fn symmetric_difference(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "symmetricDifference")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        let a_set: std::collections::HashSet<String> = a.iter()
            .map(|v| format!("{:?}", v))
            .collect();
        let b_set: std::collections::HashSet<String> = b.iter()
            .map(|v| format!("{:?}", v))
            .collect();

        let symmetric_diff: std::collections::HashSet<_> = a_set.symmetric_difference(&b_set).cloned().collect();

        let result: Vec<JsonnetValue> = a.iter()
            .filter(|item| symmetric_diff.contains(&format!("{:?}", item)))
            .chain(b.iter().filter(|item| symmetric_diff.contains(&format!("{:?}", item))))
            .cloned()
            .collect();

        Ok(JsonnetValue::array(result))
    }

    fn is_subset(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "isSubset")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        let b_set: std::collections::HashSet<String> = b.iter()
            .map(|v| format!("{:?}", v))
            .collect();

        let is_subset = a.iter().all(|item| b_set.contains(&format!("{:?}", item)));

        Ok(JsonnetValue::boolean(is_subset))
    }

    fn is_superset(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "isSuperset")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        let a_set: std::collections::HashSet<String> = a.iter()
            .map(|v| format!("{:?}", v))
            .collect();

        let is_superset = b.iter().all(|item| a_set.contains(&format!("{:?}", item)));

        Ok(JsonnetValue::boolean(is_superset))
    }

    fn is_disjoint(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "isDisjoint")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        let a_set: std::collections::HashSet<String> = a.iter()
            .map(|v| format!("{:?}", v))
            .collect();
        let b_set: std::collections::HashSet<String> = b.iter()
            .map(|v| format!("{:?}", v))
            .collect();

        let is_disjoint = a_set.intersection(&b_set).count() == 0;

        Ok(JsonnetValue::boolean(is_disjoint))
    }

    fn cartesian(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "cartesian")?;
        let arrays = args[0].as_array()?;

        if arrays.is_empty() {
            return Ok(JsonnetValue::array(vec![JsonnetValue::array(vec![])]));
        }

        // Convert to vectors
        let mut vec_arrays = Vec::new();
        for arr in arrays {
            vec_arrays.push(arr.as_array()?.clone());
        }

        fn cartesian_product(arrays: &[Vec<JsonnetValue>]) -> Vec<Vec<JsonnetValue>> {
            if arrays.is_empty() {
                return vec![vec![]];
            }

            let mut result = Vec::new();
            let first = &arrays[0];
            let rest = &arrays[1..];

            for item in first {
                for mut combo in cartesian_product(rest) {
                    combo.insert(0, item.clone());
                    result.push(combo);
                }
            }

            result
        }

        let products = cartesian_product(&vec_arrays);
        let result: Vec<JsonnetValue> = products.into_iter()
            .map(|combo| JsonnetValue::array(combo))
            .collect();

        Ok(JsonnetValue::array(result))
    }

    fn cross(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "cross")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        let mut result = Vec::new();
        for item_a in a {
            for item_b in b {
                result.push(JsonnetValue::array(vec![item_a.clone(), item_b.clone()]));
            }
        }

        Ok(JsonnetValue::array(result))
    }

    fn dot(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "dot")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        if a.len() != b.len() {
            return Err(JsonnetError::invalid_function_call("dot() arrays must have same length".to_string()));
        }

        let mut sum = 0.0;
        for (x, y) in a.iter().zip(b.iter()) {
            sum += x.as_number()? * y.as_number()?;
        }

        Ok(JsonnetValue::number(sum))
    }

    fn norm(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "norm")?;
        let arr = args[0].as_array()?;

        let mut sum_squares = 0.0;
        for item in arr {
            let val = item.as_number()?;
            sum_squares += val * val;
        }

        Ok(JsonnetValue::number(sum_squares.sqrt()))
    }

    fn normalize(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "normalize")?;
        let arr = args[0].as_array()?;

        // Calculate norm directly to avoid recursion
        let mut sum_squares = 0.0;
        for item in arr {
            let val = item.as_number()?;
            sum_squares += val * val;
        }
        let norm_val = sum_squares.sqrt();

        if norm_val == 0.0 {
            return Ok(args[0].clone());
        }

        let mut result = Vec::new();
        for item in arr {
            let val = item.as_number()?;
            result.push(JsonnetValue::number(val / norm_val));
        }

        Ok(JsonnetValue::array(result))
    }

    fn distance(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "distance")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        if a.len() != b.len() {
            return Err(JsonnetError::invalid_function_call("distance() arrays must have same length".to_string()));
        }

        let mut sum_squares = 0.0;
        for (x, y) in a.iter().zip(b.iter()) {
            let diff = x.as_number()? - y.as_number()?;
            sum_squares += diff * diff;
        }

        Ok(JsonnetValue::number(sum_squares.sqrt()))
    }

    fn angle(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "angle")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        if a.len() != b.len() {
            return Err(JsonnetError::invalid_function_call("angle() arrays must have same length".to_string()));
        }

        // Calculate dot product directly
        let mut dot_product = 0.0;
        for (x, y) in a.iter().zip(b.iter()) {
            dot_product += x.as_number()? * y.as_number()?;
        }

        // Calculate norms directly
        let mut norm_a_sq = 0.0;
        for item in a {
            let val = item.as_number()?;
            norm_a_sq += val * val;
        }
        let norm_a = norm_a_sq.sqrt();

        let mut norm_b_sq = 0.0;
        for item in b {
            let val = item.as_number()?;
            norm_b_sq += val * val;
        }
        let norm_b = norm_b_sq.sqrt();

        if norm_a == 0.0 || norm_b == 0.0 {
            return Ok(JsonnetValue::number(0.0));
        }

        let cos_theta = dot_product / (norm_a * norm_b);
        let cos_theta = cos_theta.max(-1.0).min(1.0); // Clamp to avoid floating point errors

        Ok(JsonnetValue::number(cos_theta.acos()))
    }

    fn rotate(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "rotate")?;
        let point = args[0].as_array()?;
        let angle = args[1].as_number()?;

        if point.len() != 2 {
            return Err(JsonnetError::invalid_function_call("rotate() point must be 2D".to_string()));
        }

        let center = if args.len() > 2 {
            args[2].as_array()?.to_vec()
        } else {
            vec![JsonnetValue::number(0.0), JsonnetValue::number(0.0)]
        };

        if center.len() != 2 {
            return Err(JsonnetError::invalid_function_call("rotate() center must be 2D".to_string()));
        }

        let x = point[0].as_number()? - center[0].as_number()?;
        let y = point[1].as_number()? - center[1].as_number()?;

        let cos_a = angle.cos();
        let sin_a = angle.sin();

        let new_x = x * cos_a - y * sin_a + center[0].as_number()?;
        let new_y = x * sin_a + y * cos_a + center[1].as_number()?;

        Ok(JsonnetValue::array(vec![JsonnetValue::number(new_x), JsonnetValue::number(new_y)]))
    }

    fn scale(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "scale")?;
        let point = args[0].as_array()?;
        let factor = args[1].as_number()?;

        if point.len() != 2 {
            return Err(JsonnetError::invalid_function_call("scale() point must be 2D".to_string()));
        }

        let center = if args.len() > 2 {
            args[2].as_array()?.to_vec()
        } else {
            vec![JsonnetValue::number(0.0), JsonnetValue::number(0.0)]
        };

        if center.len() != 2 {
            return Err(JsonnetError::invalid_function_call("scale() center must be 2D".to_string()));
        }

        let x = point[0].as_number()? - center[0].as_number()?;
        let y = point[1].as_number()? - center[1].as_number()?;

        let new_x = x * factor + center[0].as_number()?;
        let new_y = y * factor + center[1].as_number()?;

        Ok(JsonnetValue::array(vec![JsonnetValue::number(new_x), JsonnetValue::number(new_y)]))
    }

    fn translate(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "translate")?;
        let point = args[0].as_array()?;
        let offset = args[1].as_array()?;

        if point.len() != 2 || offset.len() != 2 {
            return Err(JsonnetError::invalid_function_call("translate() requires 2D point and offset".to_string()));
        }

        let new_x = point[0].as_number()? + offset[0].as_number()?;
        let new_y = point[1].as_number()? + offset[1].as_number()?;

        Ok(JsonnetValue::array(vec![JsonnetValue::number(new_x), JsonnetValue::number(new_y)]))
    }

    fn reflect(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "reflect")?;
        let point = args[0].as_array()?;
        let axis = args[1].as_number()?; // angle of reflection axis in radians

        if point.len() != 2 {
            return Err(JsonnetError::invalid_function_call("reflect() point must be 2D".to_string()));
        }

        let x = point[0].as_number()?;
        let y = point[1].as_number()?;

        let cos_2a = (2.0 * axis).cos();
        let sin_2a = (2.0 * axis).sin();

        let new_x = x * cos_2a + y * sin_2a;
        let new_y = x * sin_2a - y * cos_2a;

        Ok(JsonnetValue::array(vec![JsonnetValue::number(new_x), JsonnetValue::number(new_y)]))
    }

    fn affine(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "affine")?;
        let point = args[0].as_array()?;
        let matrix = args[1].as_array()?;

        if point.len() != 2 {
            return Err(JsonnetError::invalid_function_call("affine() point must be 2D".to_string()));
        }

        if matrix.len() != 6 {
            return Err(JsonnetError::invalid_function_call("affine() matrix must be 6 elements [a,b,c,d,e,f]".to_string()));
        }

        let x = point[0].as_number()?;
        let y = point[1].as_number()?;

        let a = matrix[0].as_number()?;
        let b = matrix[1].as_number()?;
        let c = matrix[2].as_number()?;
        let d = matrix[3].as_number()?;
        let e = matrix[4].as_number()?;
        let f = matrix[5].as_number()?;

        let new_x = a * x + b * y + e;
        let new_y = c * x + d * y + f;

        Ok(JsonnetValue::array(vec![JsonnetValue::number(new_x), JsonnetValue::number(new_y)]))
    }

    fn split_limit(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 3, "splitLimit")?;
        let s = args[0].as_string()?;
        let sep = args[1].as_string()?;
        let limit = args[2].as_number()? as usize;

        if sep.is_empty() {
            // Split into characters
            let chars: Vec<String> = s.chars().take(limit).map(|c| c.to_string()).collect();
            let result: Vec<JsonnetValue> = chars.into_iter().map(JsonnetValue::string).collect();
            return Ok(JsonnetValue::array(result));
        }

        let mut parts: Vec<&str> = s.splitn(limit + 1, &sep).collect();
        if parts.len() > limit {
            // Join the remaining parts
            let remaining = parts.split_off(limit);
            parts.push(&s[(s.len() - remaining.join(&sep).len())..]);
        }

        let result: Vec<JsonnetValue> = parts.into_iter().map(|s| JsonnetValue::string(s.to_string())).collect();
        Ok(JsonnetValue::array(result))
    }

    fn join_variadic(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        if args.is_empty() {
            return Err(JsonnetError::invalid_function_call("join() expects at least one argument".to_string()));
        }

        let sep = args[0].as_string()?;
        let arrays: Result<Vec<Vec<JsonnetValue>>> = args[1..].iter()
            .map(|arg| arg.as_array().cloned())
            .collect();

        let arrays = arrays?;
        let mut result = Vec::new();

        for (i, arr) in arrays.iter().enumerate() {
            if i > 0 && !sep.is_empty() {
                result.push(JsonnetValue::string(sep.clone()));
            }
            result.extend(arr.iter().cloned());
        }

        Ok(JsonnetValue::array(result))
    }

    fn replace(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 3, "replace")?;
        let s = args[0].as_string()?;
        let old = args[1].as_string()?;
        let new = args[2].as_string()?;

        let result = s.replace(&old, &new);
        Ok(JsonnetValue::string(result))
    }

    fn contains_variadic(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "contains")?;

        match &args[0] {
            JsonnetValue::Array(arr) => {
                // Simple linear search with string comparison
                let target = format!("{:?}", &args[1]);
                for item in arr {
                    if format!("{:?}", item) == target {
                        return Ok(JsonnetValue::boolean(true));
                    }
                }
                Ok(JsonnetValue::boolean(false))
            }
            JsonnetValue::String(s) => {
                let substr = args[1].as_string()?;
                Ok(JsonnetValue::boolean(s.contains(&substr)))
            }
            JsonnetValue::Object(obj) => {
                let key = args[1].as_string()?;
                Ok(JsonnetValue::boolean(obj.contains_key(&*key)))
            }
            _ => Err(JsonnetError::invalid_function_call("contains() expects array, string, or object".to_string())),
        }
    }

    // Placeholder implementations for functions requiring function callbacks
    fn sort_by(&mut self, _args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Err(JsonnetError::runtime_error("sortBy() requires function calling mechanism - placeholder implementation".to_string()))
    }

    fn group_by(&mut self, _args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Err(JsonnetError::runtime_error("groupBy() requires function calling mechanism - placeholder implementation".to_string()))
    }

    fn partition(&mut self, _args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Err(JsonnetError::runtime_error("partition() requires function calling mechanism - placeholder implementation".to_string()))
    }
}

impl StdLib {
    /// Dispatches a standard library function call.
    pub fn dispatch(
        &self,
        func_name: &str,
        args: &[JsonnetValue],
    ) -> Result<JsonnetValue> {
        match func_name {
            // AI Functions (Stubbed)
            "ai.httpGet" => Ok(JsonnetValue::string("ai.httpGet stub")),
            "ai.httpPost" => Ok(JsonnetValue::string("ai.httpPost stub")),
            "ai.callModel" => Ok(JsonnetValue::string("ai.callModel stub")),

            // Tool Functions (Stubbed)
            "tool.execute" => Ok(JsonnetValue::string("tool.execute stub")),

            // Memory Functions (Stubbed)
            "memory.get" => Ok(JsonnetValue::string("memory.get stub")),
            "memory.set" => Ok(JsonnetValue::string("memory.set stub")),

            // Agent Functions (Stubbed)
            "agent.create" => Ok(JsonnetValue::string("agent.create stub")),
            "agent.execute" => Ok(JsonnetValue::string("agent.execute stub")),

            // Chain Functions (Stubbed)
            "chain.create" => Ok(JsonnetValue::string("chain.create stub")),
            "chain.execute" => Ok(JsonnetValue::string("chain.execute stub")),

            // Existing functions...
            "std.extVar" => self.std_ext_var(args.to_vec()),
            "std.manifestJson" => self.std_manifest_json(args.to_vec()),
            // ... existing code ...

            _ => Err(JsonnetError::runtime_error(format!("Unknown std function: {}", func_name))),
        }
    }

    // ==========================================
    // Missing AI Agent Functions Implementation
    // ==========================================

    /// ai.httpGet(url, headers?) - HTTP GET request
    pub fn ai_http_get(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "ai.httpGet")?;
        let url = args[0].as_string()?;
        let headers = if args.len() > 1 {
            args[1].as_object()?
        } else {
            &std::collections::HashMap::new()
        };

        // Stub implementation - return mock response
        let result = json!({
            "url": url,
            "method": "GET",
            "headers": headers,
            "status": "pending",
            "response": "HTTP GET will be handled by AI runtime"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// ai.httpPost(url, body, headers?) - HTTP POST request
    pub fn ai_http_post(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "ai.httpPost")?;
        let url = args[0].as_string()?;
        let body = &args[1];
        let headers = if args.len() > 2 {
            args[2].as_object()?
        } else {
            &std::collections::HashMap::new()
        };

        // Stub implementation - return mock response
        let result = json!({
            "url": url,
            "method": "POST",
            "body": body,
            "headers": headers,
            "status": "pending",
            "response": "HTTP POST will be handled by AI runtime"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// ai.callModel(model, prompt, options?) - Call AI model
    pub fn ai_call_model(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "ai.callModel")?;
        let model = args[0].as_string()?;
        let prompt = args[1].as_string()?;
        let options = if args.len() > 2 {
            args[2].as_object()?
        } else {
            &std::collections::HashMap::new()
        };

        // Stub implementation - return mock response
        let result = json!({
            "model": model,
            "prompt": prompt,
            "options": options,
            "status": "pending",
            "response": "AI model call will be handled by AI runtime"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// tool.execute(name, args) - Execute external tool
    pub fn tool_execute(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "tool.execute")?;
        let name = args[0].as_string()?;
        let tool_args = &args[1];

        // Stub implementation - return mock response
        let result = json!({
            "tool": name,
            "args": tool_args,
            "status": "pending",
            "output": "Tool execution will be handled by runtime"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// memory.get(key) - Get value from memory
    pub fn memory_get(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "memory.get")?;
        let key = args[0].as_string()?;

        // Stub implementation - return mock response
        let result = json!({
            "key": key,
            "operation": "get",
            "status": "pending",
            "value": "Memory access will be handled by runtime"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// memory.set(key, value) - Set value in memory
    pub fn memory_set(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "memory.set")?;
        let key = args[0].as_string()?;
        let value = &args[1];

        // Stub implementation - return mock response
        let result = json!({
            "key": key,
            "value": value,
            "operation": "set",
            "status": "success"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// agent.create(config) - Create AI agent
    pub fn agent_create(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "agent.create")?;
        let config = args[0].as_object()?;

        // Stub implementation - return mock response
        let result = json!({
            "config": config,
            "operation": "create",
            "status": "pending",
            "agent_id": "mock-agent-id"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// std.extVar(name) - Get external variable
    pub fn std_ext_var(&self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "std.extVar")?;
        let name = args[0].as_string()?;

        // Stub implementation - return mock external variable
        let result = json!({
            "variable": name,
            "value": "External variable will be resolved by runtime",
            "status": "pending"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// std.manifestJson(value, indent?) - JSON manifest with optional indentation
    pub fn std_manifest_json(&self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "std.manifestJson")?;
        let value = &args[0];
        let indent = if args.len() > 1 {
            args[1].as_number()? as usize
        } else {
            0
        };

        // Convert JsonnetValue to JSON string
        match serde_json::to_string_pretty(&value) {
            Ok(json_str) => {
                if indent > 0 {
                    Ok(JsonnetValue::string(json_str))
                } else {
                    Ok(JsonnetValue::string(serde_json::to_string(&value).unwrap_or_default()))
                }
            }
            Err(_) => Err(JsonnetError::runtime_error("Failed to serialize to JSON")),
        }
    }

    /// std.length(x) - returns length of array, string, or object
    pub fn length(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "length")?;
        match &args[0] {
            JsonnetValue::Array(arr) => Ok(JsonnetValue::number(arr.len() as f64)),
            JsonnetValue::String(s) => Ok(JsonnetValue::number(s.len() as f64)),
            JsonnetValue::Object(obj) => Ok(JsonnetValue::number(obj.len() as f64)),
            _ => Err(JsonnetError::type_error("length() requires array, string, or object")),
        }
    }

    /// std.toString(x) - converts value to string
    pub fn to_string(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "toString")?;
        Ok(JsonnetValue::string(args[0].to_string()))
    }

    /// std.join(sep, arr) - joins array elements with separator
    pub fn join(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "join")?;
        let sep = args[0].as_string()?;
        let arr = args[1].as_array()?;

        let mut result = String::new();
        for (i, item) in arr.iter().enumerate() {
            if i > 0 {
                result.push_str(&sep);
            }
            result.push_str(&item.to_string());
        }

        Ok(JsonnetValue::string(result))
    }

    /// std.substr(s, from, len) - extracts substring
    pub fn substr(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 3, "substr")?;
        let s = args[0].as_string()?;
        let from = args[1].as_number()? as usize;
        let len = args[2].as_number()? as usize;

        if from >= s.len() {
            Ok(JsonnetValue::string(String::new()))
        } else {
            let end = (from + len).min(s.len());
            Ok(JsonnetValue::string(s[from..end].to_string()))
        }
    }

    /// std.split(str, sep) - splits string by separator
    pub fn split(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "split")?;
        let s = args[0].as_string()?;
        let sep = args[1].as_string()?;

        let parts: Vec<JsonnetValue> = s.split(&sep)
            .map(|part| JsonnetValue::string(part.to_string()))
            .collect();

        Ok(JsonnetValue::array(parts))
    }

    /// std.startsWith(str, prefix) - checks if string starts with prefix
    pub fn starts_with(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "startsWith")?;
        let s = args[0].as_string()?;
        let prefix = args[1].as_string()?;

        Ok(JsonnetValue::boolean(s.starts_with(&prefix)))
    }

    /// std.endsWith(str, suffix) - checks if string ends with suffix
    pub fn ends_with(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "endsWith")?;
        let s = args[0].as_string()?;
        let suffix = args[1].as_string()?;

        Ok(JsonnetValue::boolean(s.ends_with(&suffix)))
    }

    /// std.stringChars(str) - splits string into array of characters
    pub fn string_chars(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "stringChars")?;
        let s = args[0].as_string()?;

        let chars: Vec<JsonnetValue> = s.chars()
            .map(|c| JsonnetValue::string(c.to_string()))
            .collect();

        Ok(JsonnetValue::array(chars))
    }

    /// std.asciiLower(str) - converts ASCII characters to lowercase
    pub fn ascii_lower(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "asciiLower")?;
        let s = args[0].as_string()?;
        Ok(JsonnetValue::string(s.to_ascii_lowercase()))
    }

    /// std.asciiUpper(str) - converts ASCII characters to uppercase
    pub fn ascii_upper(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "asciiUpper")?;
        let s = args[0].as_string()?;
        Ok(JsonnetValue::string(s.to_ascii_uppercase()))
    }

    /// std.flatMap(func, arr) - apply function to each element and flatten result
    pub fn flat_map(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "flatMap")?;
        // Simplified implementation: just return the input array for now
        // Full implementation would require function call capability
        let arr = args[1].as_array()?;
        Ok(JsonnetValue::array(arr.clone()))
    }

    /// std.mapWithIndex(func, arr) - map array with index
    pub fn map_with_index(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "mapWithIndex")?;
        // Simplified implementation: return [index, value] pairs for each element
        let arr = args[1].as_array()?;

        let mut result = Vec::new();
        for (i, item) in arr.iter().enumerate() {
            let pair = JsonnetValue::array(vec![
                JsonnetValue::number(i as f64),
                item.clone()
            ]);
            result.push(pair);
        }

        Ok(JsonnetValue::array(result))
    }

    /// std.lstripChars(str, chars) - strip characters from left
    pub fn lstrip_chars(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "lstripChars")?;
        let s = args[0].as_string()?;
        let chars = args[1].as_string()?;

        let trimmed = s.trim_start_matches(|c| chars.contains(c));
        Ok(JsonnetValue::string(trimmed.to_string()))
    }

    /// std.rstripChars(str, chars) - strip characters from right
    pub fn rstrip_chars(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "rstripChars")?;
        let s = args[0].as_string()?;
        let chars = args[1].as_string()?;

        let trimmed = s.trim_end_matches(|c| chars.contains(c));
        Ok(JsonnetValue::string(trimmed.to_string()))
    }

    /// std.stripChars(str, chars) - strip characters from both sides
    pub fn strip_chars(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "stripChars")?;
        let s = args[0].as_string()?;
        let chars = args[1].as_string()?;

        let trimmed = s.trim_matches(|c| chars.contains(c));
        Ok(JsonnetValue::string(trimmed.to_string()))
    }

    /// std.findSubstr(pat, str) - find all positions of substring
    pub fn find_substr(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "findSubstr")?;
        let pat = args[0].as_string()?;
        let s = args[1].as_string()?;

        let mut positions = Vec::new();
        let mut start = 0;

        while let Some(pos) = s[start..].find(&pat) {
            positions.push(JsonnetValue::number((start + pos) as f64));
            start += pos + pat.len();
            if start >= s.len() {
                break;
            }
        }

        Ok(JsonnetValue::array(positions))
    }

    /// std.repeat(what, count) - repeat value or array
    pub fn repeat(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "repeat")?;
        let what = &args[0];
        let count = args[1].as_number()? as usize;

        match what {
            JsonnetValue::String(s) => {
                let repeated = s.repeat(count);
                Ok(JsonnetValue::string(repeated))
            }
            JsonnetValue::Array(arr) => {
                let mut result = Vec::new();
                for _ in 0..count {
                    result.extend(arr.clone());
                }
                Ok(JsonnetValue::array(result))
            }
            _ => Err(JsonnetError::type_error("repeat expects string or array as first argument")),
        }
    }

    /// std.set(arr) - remove duplicates from array
    pub fn set(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "set")?;
        let arr = args[0].as_array()?;

        let mut seen = std::collections::HashSet::new();
        let mut result = Vec::new();

        for item in arr {
            // Use a string representation for comparison
            // This is a simple implementation - full Jsonnet would need proper equality
            let key = format!("{:?}", item);
            if seen.insert(key) {
                result.push(item.clone());
            }
        }

        Ok(JsonnetValue::array(result))
    }

    /// std.setMember(x, arr) - check if x is in the set arr
    pub fn set_member(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "setMember")?;
        let x = &args[0];
        let arr = args[1].as_array()?;

        let contains = arr.iter().any(|item| item.equals(x));
        Ok(JsonnetValue::boolean(contains))
    }

    /// std.setInter(a, b) - intersection of two sets
    pub fn set_inter(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "setInter")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        let mut result = Vec::new();
        for item_a in a {
            if b.iter().any(|item_b| item_a.equals(item_b)) && !result.iter().any(|item_r| item_a.equals(item_r)) {
                result.push(item_a.clone());
            }
        }

        Ok(JsonnetValue::array(result))
    }

    /// std.setUnion(a, b) - union of two sets
    pub fn set_union(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "setUnion")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        let mut result = a.clone();

        for item_b in b {
            if !result.iter().any(|item_r| item_b.equals(item_r)) {
                result.push(item_b.clone());
            }
        }

        Ok(JsonnetValue::array(result))
    }

    /// std.setDiff(a, b) - difference of two sets (a - b)
    pub fn set_diff(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "setDiff")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        let mut result = Vec::new();
        for item_a in a {
            if !b.iter().any(|item_b| item_a.equals(item_b)) {
                result.push(item_a.clone());
            }
        }

        Ok(JsonnetValue::array(result))
    }

    /// std.type(x) - returns type of value as string
    fn type_of(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "type")?;
        let type_str = args[0].type_name();
        Ok(JsonnetValue::string(type_str))
    }

    /// std.makeArray(n, func) - creates array by calling func n times
    fn make_array(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "makeArray")?;
        let n = args[0].as_number()? as usize;
        let _func = &args[1];

        // For now, create a simple array [0, 1, 2, ..., n-1]
        // TODO: Implement proper function calling
        let mut result = Vec::new();
        for i in 0..n {
            // Since we can't call functions yet, just create an array of indices
            result.push(JsonnetValue::number(i as f64));
        }

        Ok(JsonnetValue::array(result))
    }

    /// std.filter(func, arr) - filters array using predicate function
    fn filter(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "filter")?;
        let _func = &args[0];
        let _arr = args[1].as_array()?;
        // TODO: Implement function calling for higher-order functions
        // For now, return original array
        Ok(args[1].clone())
    }

    /// std.map(func, arr) - maps function over array
    fn map(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "map")?;
        let _func = &args[0];
        let _arr = args[1].as_array()?;
        // TODO: Implement function calling for higher-order functions
        // For now, return original array
        Ok(args[1].clone())
    }

    /// std.foldl(func, arr, init) - left fold
    fn foldl(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 3, "foldl")?;
        let _func = &args[0];
        let _arr = args[1].as_array()?;
        // TODO: Implement function calling for higher-order functions
        // For now, return initial value
        Ok(args[2].clone())
    }

    /// std.foldr(func, arr, init) - right fold
    fn foldr(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 3, "foldr")?;
        let _func = &args[0];
        let _arr = args[1].as_array()?;
        // TODO: Implement function calling for higher-order functions
        // For now, return initial value
        Ok(args[2].clone())
    }

    /// std.range(n) - creates array [0, 1, ..., n-1]
    fn range(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "range")?;
        let n = args[0].as_number()? as usize;
        let arr: Vec<JsonnetValue> = (0..n).map(|i| JsonnetValue::number(i as f64)).collect();
        Ok(JsonnetValue::array(arr))
    }



    /// std.contains(arr, elem) - checks if array contains element
    fn contains(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "contains")?;
        let arr = args[0].as_array()?;
        let contains = arr.iter().any(|item| item.equals(&args[1]));
        Ok(JsonnetValue::boolean(contains))
    }




    /// std.char(n) - returns character for codepoint
    fn char_fn(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "char")?;
        let n = args[0].as_number()? as u32;
        match char::from_u32(n) {
            Some(c) => Ok(JsonnetValue::string(c.to_string())),
            None => Err(JsonnetError::runtime_error("Invalid codepoint")),
        }
    }

    /// std.codepoint(str) - returns codepoint of first character
    fn codepoint(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "codepoint")?;
        let s = args[0].as_string()?;
        match s.chars().next() {
            Some(c) => Ok(JsonnetValue::number(c as u32 as f64)),
            None => Err(JsonnetError::runtime_error("Empty string")),
        }
    }


    /// std.parseInt(str) - parses string as integer
    fn parse_int(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "parseInt")?;
        let s = args[0].as_string()?;
        match s.parse::<f64>() {
            Ok(n) => Ok(JsonnetValue::number(n)),
            Err(_) => Err(JsonnetError::runtime_error("Invalid number format")),
        }
    }

    /// std.parseJson(str) - parses JSON string
    fn parse_json(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "parseJson")?;
        let s = args[0].as_string()?;
        match serde_json::from_str::<serde_json::Value>(s) {
            Ok(value) => Ok(JsonnetValue::from_json_value(value)),
            Err(_) => Err(JsonnetError::runtime_error("Invalid JSON")),
        }
    }

    /// std.encodeUTF8(str) - encodes string as UTF-8 bytes
    fn encode_utf8(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "encodeUTF8")?;
        let s = args[0].as_string()?;
        let bytes: Vec<JsonnetValue> = s.as_bytes().iter().map(|&b| JsonnetValue::number(b as f64)).collect();
        Ok(JsonnetValue::array(bytes))
    }

    /// std.decodeUTF8(arr) - decodes UTF-8 bytes to string
    fn decode_utf8(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "decodeUTF8")?;
        let arr = args[0].as_array()?;
        let mut bytes = Vec::new();
        for item in arr {
            let b = item.as_number()? as u8;
            bytes.push(b);
        }
        match String::from_utf8(bytes) {
            Ok(s) => Ok(JsonnetValue::string(s)),
            Err(_) => Err(JsonnetError::runtime_error("Invalid UTF-8 sequence")),
        }
    }

    /// std.md5(str) - computes MD5 hash
    fn md5(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "md5")?;
        let s = args[0].as_string()?;
        use md5::{Md5, Digest};
        let mut hasher = Md5::new();
        hasher.update(s.as_bytes());
        let result = hasher.finalize();
        Ok(JsonnetValue::string(format!("{:x}", result)))
    }

    /// std.base64(str) - base64 encodes string
    fn base64(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "base64")?;
        let s = args[0].as_string()?;
        use base64::{Engine as _, engine::general_purpose};
        let encoded = general_purpose::STANDARD.encode(s.as_bytes());
        Ok(JsonnetValue::string(encoded))
    }

    /// std.base64Decode(str) - base64 decodes string
    fn base64_decode(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "base64Decode")?;
        let s = args[0].as_string()?;
        use base64::{Engine as _, engine::general_purpose};
        match general_purpose::STANDARD.decode(s.as_bytes()) {
            Ok(bytes) => match String::from_utf8(bytes) {
                Ok(decoded) => Ok(JsonnetValue::string(decoded)),
                Err(_) => Err(JsonnetError::runtime_error("Invalid UTF-8 in decoded data")),
            },
            Err(_) => Err(JsonnetError::runtime_error("Invalid base64")),
        }
    }

    /// std.manifestJson(x) - pretty prints value as JSON
    fn manifest_json(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "manifestJson")?;
        let json = serde_json::to_string_pretty(&args[0].to_json_value())?;
        Ok(JsonnetValue::string(json))
    }

    /// std.manifestJsonEx(x, indent) - pretty prints value as JSON with custom indent
    fn manifest_json_ex(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "manifestJsonEx")?;
        let value = &args[0];
        let indent = args[1].as_string()?;

        // Simple implementation with custom indentation
        // For now, just use serde_json with the indent string
        match serde_json::to_string_pretty(&value.to_json_value()) {
            Ok(json) => {
                if indent.is_empty() {
                    Ok(JsonnetValue::string(json))
                } else {
                    // Replace default 2-space indentation with custom indent
                    let indented = json.lines()
                        .map(|line| {
                            let leading_spaces = line.chars().take_while(|c| *c == ' ').count();
                            if leading_spaces > 0 {
                                let indent_level = leading_spaces / 2;
                                format!("{}{}", indent.repeat(indent_level), &line[leading_spaces..])
                            } else {
                                line.to_string()
                            }
                        })
                        .collect::<Vec<_>>()
                        .join("\n");
                    Ok(JsonnetValue::string(indented))
                }
            }
            Err(_) => Err(JsonnetError::runtime_error("Failed to serialize to JSON")),
        }
    }

    /// std.manifestYaml(x) - pretty prints value as YAML
    #[cfg(feature = "yaml")]
    fn manifest_yaml(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "manifestYaml")?;
        let yaml = serde_yaml::to_string(&args[0].to_json_value())?;
        Ok(JsonnetValue::string(yaml))
    }

    /// std.manifestYaml(x) - pretty prints value as YAML (fallback when yaml feature disabled)
    #[cfg(not(feature = "yaml"))]
    fn manifest_yaml(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "manifestYaml")?;
        // Fallback to JSON when YAML feature is disabled
        Self::manifest_json(args)
    }

    // String escaping functions
    fn escape_string_json(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "escapeStringJson")?;
        let s = args[0].as_string()?;
        let escaped = serde_json::to_string(s)?;
        Ok(JsonnetValue::string(escaped))
    }

    fn escape_string_yaml(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "escapeStringYaml")?;
        let s = args[0].as_string()?;

        // Basic YAML string escaping
        // YAML requires escaping certain characters in strings
        let mut escaped = String::new();
        for ch in s.chars() {
            match ch {
                '"' => escaped.push_str("\\\""),
                '\\' => escaped.push_str("\\\\"),
                '\n' => escaped.push_str("\\n"),
                '\r' => escaped.push_str("\\r"),
                '\t' => escaped.push_str("\\t"),
                '\0' => escaped.push_str("\\0"),
                _ => escaped.push(ch),
            }
        }

        // Wrap in quotes if the string contains special characters
        let needs_quotes = s.contains(' ') || s.contains('\t') || s.contains('\n') ||
                          s.contains(':') || s.contains('#') || s.contains('-') ||
                          s.starts_with('[') || s.starts_with('{') ||
                          s.starts_with('"') || s.starts_with('\'');

        if needs_quotes {
            Ok(JsonnetValue::string(format!("\"{}\"", escaped)))
        } else {
            Ok(JsonnetValue::string(escaped))
        }
    }

    fn escape_string_python(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "escapeStringPython")?;
        let s = args[0].as_string()?;
        let escaped = s.escape_default().to_string();
        Ok(JsonnetValue::string(format!("'{}'", escaped)))
    }

    fn escape_string_bash(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "escapeStringBash")?;
        let s = args[0].as_string()?;
        let escaped = s.replace("'", "'\"'\"'").replace("\\", "\\\\");
        Ok(JsonnetValue::string(format!("'{}'", escaped)))
    }

    fn escape_string_dollars(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "escapeStringDollars")?;
        let s = args[0].as_string()?;
        let escaped = s.replace("$$", "$").replace("$", "$$");
        Ok(JsonnetValue::string(escaped))
    }


    fn string_bytes(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "stringBytes")?;
        let s = args[0].as_string()?;
        let bytes: Vec<JsonnetValue> = s.as_bytes().iter().map(|&b| JsonnetValue::number(b as f64)).collect();
        Ok(JsonnetValue::array(bytes))
    }

    fn format(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "format")?;
        let format_str = args[0].as_string()?;
        let values = args[1].as_array()?;

        // Simple format implementation - replace %1, %2, etc. with values
        let mut result = format_str.to_string();
        for (i, value) in values.iter().enumerate() {
            let placeholder = format!("%{}", i + 1);
            let value_str = match value {
                JsonnetValue::String(s) => s.clone(),
                JsonnetValue::Number(n) => n.to_string(),
                JsonnetValue::Boolean(b) => b.to_string(),
                _ => value.to_string(),
            };
            result = result.replace(&placeholder, &value_str);
        }

        Ok(JsonnetValue::string(result))
    }

    // Type checking functions
    fn is_array(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "isArray")?;
        Ok(JsonnetValue::boolean(matches!(args[0], JsonnetValue::Array(_))))
    }

    fn is_boolean(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "isBoolean")?;
        Ok(JsonnetValue::boolean(matches!(args[0], JsonnetValue::Boolean(_))))
    }

    fn is_function(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "isFunction")?;
        Ok(JsonnetValue::boolean(matches!(args[0], JsonnetValue::Function(_))))
    }

    fn is_number(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "isNumber")?;
        Ok(JsonnetValue::boolean(matches!(args[0], JsonnetValue::Number(_))))
    }

    fn is_object(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "isObject")?;
        Ok(JsonnetValue::boolean(matches!(args[0], JsonnetValue::Object(_))))
    }

    fn is_string(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "isString")?;
        Ok(JsonnetValue::boolean(matches!(args[0], JsonnetValue::String(_))))
    }

    // Array functions
    fn count(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "count")?;
        let arr = args[0].as_array()?;
        let elem = &args[1];
        let count = arr.iter().filter(|item| item.equals(elem)).count() as f64;
        Ok(JsonnetValue::number(count))
    }

    fn find(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "find")?;
        match (&args[0], &args[1]) {
            (JsonnetValue::Array(arr), value) => {
                let mut indices = Vec::new();
                for (i, item) in arr.iter().enumerate() {
                    if item == value {
                        indices.push(JsonnetValue::Number(i as f64));
                    }
                }
                Ok(JsonnetValue::array(indices))
            }
            _ => Err(JsonnetError::runtime_error("find expects array and search value")),
        }
    }

    fn member(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::contains(args)
    }

    // Math functions
    fn modulo(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "modulo")?;
        let a = args[0].as_number()?;
        let b = args[1].as_number()?;
        if b == 0.0 {
            return Err(JsonnetError::DivisionByZero);
        }
        Ok(JsonnetValue::number(a % b))
    }

    fn pow(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "pow")?;
        let a = args[0].as_number()?;
        let b = args[1].as_number()?;
        Ok(JsonnetValue::number(a.powf(b)))
    }

    fn exp(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "exp")?;
        let x = args[0].as_number()?;
        Ok(JsonnetValue::number(x.exp()))
    }

    fn log(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "log")?;
        let x = args[0].as_number()?;
        if x <= 0.0 {
            return Err(JsonnetError::runtime_error("log of non-positive number"));
        }
        Ok(JsonnetValue::number(x.ln()))
    }

    fn sqrt(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "sqrt")?;
        let x = args[0].as_number()?;
        if x < 0.0 {
            return Err(JsonnetError::runtime_error("sqrt of negative number"));
        }
        Ok(JsonnetValue::number(x.sqrt()))
    }

    fn sin(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "sin")?;
        let x = args[0].as_number()?;
        Ok(JsonnetValue::number(x.sin()))
    }

    fn cos(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "cos")?;
        let x = args[0].as_number()?;
        Ok(JsonnetValue::number(x.cos()))
    }

    fn tan(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "tan")?;
        let x = args[0].as_number()?;
        Ok(JsonnetValue::number(x.tan()))
    }

    fn asin(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "asin")?;
        let x = args[0].as_number()?;
        Ok(JsonnetValue::number(x.asin()))
    }

    fn acos(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "acos")?;
        let x = args[0].as_number()?;
        Ok(JsonnetValue::number(x.acos()))
    }

    fn atan(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "atan")?;
        let x = args[0].as_number()?;
        Ok(JsonnetValue::number(x.atan()))
    }

    fn floor(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "floor")?;
        let x = args[0].as_number()?;
        Ok(JsonnetValue::number(x.floor()))
    }

    fn ceil(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "ceil")?;
        let x = args[0].as_number()?;
        Ok(JsonnetValue::number(x.ceil()))
    }

    fn round(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "round")?;
        let x = args[0].as_number()?;
        Ok(JsonnetValue::number(x.round()))
    }

    fn abs(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "abs")?;
        let x = args[0].as_number()?;
        Ok(JsonnetValue::number(x.abs()))
    }

    fn max(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "max")?;
        let arr = args[0].as_array()?;
        if arr.is_empty() {
            return Err(JsonnetError::runtime_error("max() called on empty array"));
        }
        let mut max_val = f64::NEG_INFINITY;
        for item in arr {
            let val = item.as_number()?;
            if val > max_val {
                max_val = val;
            }
        }
        Ok(JsonnetValue::number(max_val))
    }

    fn min(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "min")?;
        let arr = args[0].as_array()?;
        if arr.is_empty() {
            return Err(JsonnetError::runtime_error("min() called on empty array"));
        }
        let mut min_val = f64::INFINITY;
        for item in arr {
            let val = item.as_number()?;
            if val < min_val {
                min_val = val;
            }
        }
        Ok(JsonnetValue::number(min_val))
    }

    fn clamp(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 3, "clamp")?;
        let x = args[0].as_number()?;
        let min = args[1].as_number()?;
        let max = args[2].as_number()?;
        let clamped = x.max(min).min(max);
        Ok(JsonnetValue::number(clamped))
    }

    fn assert_equal(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "assertEqual")?;
        if !args[0].equals(&args[1]) {
            return Err(JsonnetError::assertion_failed(format!(
                "Assertion failed: {} != {}\n  Left: {:?}\n  Right: {:?}",
                args[0], args[1], args[0], args[1]
            )));
        }
        Ok(JsonnetValue::boolean(true))
    }

    fn trace(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "trace")?;
        // Print the second argument to stderr for tracing
        eprintln!("TRACE: {:?}", args[1]);
        // Return the first argument
        Ok(args[0].clone())
    }

    // Array manipulation functions
    fn sort(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "sort")?;
        let arr = args[0].as_array()?;

        if arr.is_empty() {
            return Ok(JsonnetValue::array(vec![]));
        }

        // Implement proper Jsonnet sorting
        // Jsonnet sorts by comparing values directly, not by string representation
        let mut sorted = arr.clone();
        sorted.sort_by(|a, b| Self::compare_values(a, b));

        Ok(JsonnetValue::array(sorted))
    }

    fn compare_values(a: &JsonnetValue, b: &JsonnetValue) -> std::cmp::Ordering {
        match (a, b) {
            (JsonnetValue::Null, JsonnetValue::Null) => std::cmp::Ordering::Equal,
            (JsonnetValue::Null, _) => std::cmp::Ordering::Less,
            (_, JsonnetValue::Null) => std::cmp::Ordering::Greater,
            (JsonnetValue::Boolean(x), JsonnetValue::Boolean(y)) => x.cmp(y),
            (JsonnetValue::Boolean(_), _) => std::cmp::Ordering::Less,
            (_, JsonnetValue::Boolean(_)) => std::cmp::Ordering::Greater,
            (JsonnetValue::Number(x), JsonnetValue::Number(y)) => {
                x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal)
            }
            (JsonnetValue::Number(_), _) => std::cmp::Ordering::Less,
            (_, JsonnetValue::Number(_)) => std::cmp::Ordering::Greater,
            (JsonnetValue::String(x), JsonnetValue::String(y)) => x.cmp(y),
            (JsonnetValue::String(_), _) => std::cmp::Ordering::Less,
            (_, JsonnetValue::String(_)) => std::cmp::Ordering::Greater,
            (JsonnetValue::Array(x), JsonnetValue::Array(y)) => {
                for (_i, (a_item, b_item)) in x.iter().zip(y.iter()).enumerate() {
                    let cmp = Self::compare_values(a_item, b_item);
                    if cmp != std::cmp::Ordering::Equal {
                        return cmp;
                    }
                }
                x.len().cmp(&y.len())
            }
            (JsonnetValue::Array(_), _) => std::cmp::Ordering::Less,
            (_, JsonnetValue::Array(_)) => std::cmp::Ordering::Greater,
            (JsonnetValue::Object(x), JsonnetValue::Object(y)) => {
                // Compare by sorted keys and values
                let mut x_keys: Vec<_> = x.keys().collect();
                let mut y_keys: Vec<_> = y.keys().collect();
                x_keys.sort();
                y_keys.sort();

                for (x_key, y_key) in x_keys.iter().zip(y_keys.iter()) {
                    let key_cmp = x_key.cmp(y_key);
                    if key_cmp != std::cmp::Ordering::Equal {
                        return key_cmp;
                    }
                    if let (Some(x_val), Some(y_val)) = (x.get(*x_key), y.get(*y_key)) {
                        let val_cmp = Self::compare_values(x_val, y_val);
                        if val_cmp != std::cmp::Ordering::Equal {
                            return val_cmp;
                        }
                    }
                }
                x.len().cmp(&y.len())
            }
            _ => std::cmp::Ordering::Equal, // Functions are considered equal for sorting
        }
    }

    fn uniq(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "uniq")?;
        let arr = args[0].as_array()?;

        let mut result: Vec<JsonnetValue> = Vec::new();
        for item in arr {
            // Check if item is already in result
            let mut found = false;
            for existing in &result {
                if existing.equals(item) {
                    found = true;
                    break;
                }
            }
            if !found {
                result.push(item.clone());
            }
        }

        Ok(JsonnetValue::array(result))
    }

    fn reverse(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "reverse")?;
        let arr = args[0].as_array()?;
        let reversed: Vec<JsonnetValue> = arr.iter().rev().cloned().collect();
        Ok(JsonnetValue::array(reversed))
    }

    // Object functions
    fn merge_patch(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "mergePatch")?;
        let target = args[0].as_object()?;
        let patch = args[1].as_object()?;

        let mut result = target.clone();

        for (key, patch_value) in patch {
            match patch_value {
                JsonnetValue::Null => {
                    // null values remove the key
                    result.remove(key);
                }
                JsonnetValue::Object(patch_obj) => {
                    // If both target and patch have objects, recursively merge
                    if let Some(JsonnetValue::Object(target_obj)) = result.get(key) {
                        let merged = Self::merge_patch(vec![
                            JsonnetValue::object(target_obj.clone()),
                            JsonnetValue::object(patch_obj.clone())
                        ])?;
                        if let JsonnetValue::Object(merged_obj) = merged {
                            result.insert(key.clone(), JsonnetValue::object(merged_obj));
                        }
                    } else {
                        // Target doesn't have an object, use patch object
                        result.insert(key.clone(), JsonnetValue::object(patch_obj.clone()));
                    }
                }
                _ => {
                    // For other values, just replace
                    result.insert(key.clone(), patch_value.clone());
                }
            }
        }

        Ok(JsonnetValue::object(result))
    }

    fn get(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 3, "get")?;
        let obj = args[0].as_object()?;
        let key = args[1].as_string()?;
        let default = &args[2];
        Ok(obj.get(key).unwrap_or(default).clone())
    }

    fn object_fields(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "objectFields")?;
        let obj = args[0].as_object()?;
        let fields: Vec<JsonnetValue> = obj.keys()
            .filter(|&k| !k.starts_with('_')) // Filter out hidden fields
            .map(|k| JsonnetValue::string(k.clone()))
            .collect();
        Ok(JsonnetValue::array(fields))
    }

    fn object_fields_all(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "objectFieldsAll")?;
        let obj = args[0].as_object()?;
        let fields: Vec<JsonnetValue> = obj.keys()
            .map(|k| JsonnetValue::string(k.clone()))
            .collect();
        Ok(JsonnetValue::array(fields))
    }

    fn object_has(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "objectHas")?;
        let obj = args[0].as_object()?;
        let key = args[1].as_string()?;
        Ok(JsonnetValue::boolean(obj.contains_key(key) && !key.starts_with('_')))
    }

    fn object_has_all(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "objectHasAll")?;
        let obj = args[0].as_object()?;
        let key = args[1].as_string()?;
        Ok(JsonnetValue::boolean(obj.contains_key(key)))
    }

    fn object_values(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "objectValues")?;
        let obj = args[0].as_object()?;
        let values: Vec<JsonnetValue> = obj.iter()
            .filter(|(k, _)| !k.starts_with('_'))
            .map(|(_, v)| v.clone())
            .collect();
        Ok(JsonnetValue::array(values))
    }

    fn object_values_all(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "objectValuesAll")?;
        let obj = args[0].as_object()?;
        let values: Vec<JsonnetValue> = obj.values().cloned().collect();
        Ok(JsonnetValue::array(values))
    }

    fn prune(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "prune")?;
        Self::prune_value(&args[0])
    }

    fn prune_value(value: &JsonnetValue) -> Result<JsonnetValue> {
        match value {
            JsonnetValue::Null => Ok(JsonnetValue::Null),
            JsonnetValue::Array(arr) => {
                let pruned: Vec<JsonnetValue> = arr.iter()
                    .map(|item| Self::prune_value(item))
                    .collect::<Result<Vec<_>>>()?
                    .into_iter()
                    .filter(|item| !matches!(item, JsonnetValue::Null))
                    .collect();
                Ok(JsonnetValue::array(pruned))
            }
            JsonnetValue::Object(obj) => {
                let mut pruned_obj = HashMap::new();
                for (key, val) in obj {
                    let pruned_val = Self::prune_value(val)?;
                    if !matches!(pruned_val, JsonnetValue::Null) {
                        pruned_obj.insert(key.clone(), pruned_val);
                    }
                }
                Ok(JsonnetValue::object(pruned_obj))
            }
            _ => Ok(value.clone()),
        }
    }

    fn map_with_key(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "mapWithKey")?;
        let _func = &args[0];
        let obj = args[1].as_object()?;

        // For now, return a simple transformation
        // TODO: Implement proper function calling
        let mut result = HashMap::new();
        for (key, value) in obj {
            if !key.starts_with('_') {
                // Simple transformation: wrap key-value in array
                // In full implementation, this would call the function with (key, value)
                result.insert(key.clone(), JsonnetValue::array(vec![
                    JsonnetValue::string(key.clone()),
                    value.clone()
                ]));
            }
        }

        Ok(JsonnetValue::object(result))
    }

    fn object_fields_ex(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "objectFieldsEx")?;
        let obj = args[0].as_object()?;
        let include_hidden = args[1].as_boolean()?;

        let fields: Vec<JsonnetValue> = obj.keys()
            .filter(|&k| include_hidden || !k.starts_with('_'))
            .map(|k| JsonnetValue::string(k.clone()))
            .collect();

        Ok(JsonnetValue::array(fields))
    }

    fn object_values_ex(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "objectValuesEx")?;
        let obj = args[0].as_object()?;
        let include_hidden = args[1].as_boolean()?;

        let values: Vec<JsonnetValue> = obj.iter()
            .filter(|(k, _)| include_hidden || !k.starts_with('_'))
            .map(|(_, v)| v.clone())
            .collect();

        Ok(JsonnetValue::array(values))
    }

    fn to_lower(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "toLower")?;
        match &args[0] {
            JsonnetValue::String(s) => Ok(JsonnetValue::string(s.to_lowercase())),
            _ => Err(JsonnetError::runtime_error("toLower expects a string argument")),
        }
    }

    fn to_upper(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "toUpper")?;
        match &args[0] {
            JsonnetValue::String(s) => Ok(JsonnetValue::string(s.to_uppercase())),
            _ => Err(JsonnetError::runtime_error("toUpper expects a string argument")),
        }
    }

    fn trim(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "trim")?;
        match &args[0] {
            JsonnetValue::String(s) => Ok(JsonnetValue::string(s.trim().to_string())),
            _ => Err(JsonnetError::runtime_error("trim expects a string argument")),
        }
    }

    fn all(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "all")?;
        match &args[0] {
            JsonnetValue::Array(arr) => {
                let result = arr.iter().all(|item| item.is_truthy());
                Ok(JsonnetValue::boolean(result))
            }
            _ => Err(JsonnetError::runtime_error("all expects an array argument")),
        }
    }

    fn any(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "any")?;
        match &args[0] {
            JsonnetValue::Array(arr) => {
                let result = arr.iter().any(|item| item.is_truthy());
                Ok(JsonnetValue::boolean(result))
            }
            _ => Err(JsonnetError::runtime_error("any expects an array argument")),
        }
    }

    fn id(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "id")?;
        Ok(args[0].clone())
    }

    fn equals(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "equals")?;
        let a = &args[0];
        let b = &args[1];

        // First check primitive equality
        if a == b {
            return Ok(JsonnetValue::boolean(true));
        }

        // Check types
        let ta = a.type_name();
        let tb = b.type_name();
        if ta != tb {
            return Ok(JsonnetValue::boolean(false));
        }

        match (a, b) {
            (JsonnetValue::Array(arr_a), JsonnetValue::Array(arr_b)) => {
                if arr_a.len() != arr_b.len() {
                    return Ok(JsonnetValue::boolean(false));
                }
                for (i, item_a) in arr_a.iter().enumerate() {
                    let eq_args = vec![item_a.clone(), arr_b[i].clone()];
                    if let Ok(JsonnetValue::Boolean(false)) = Self::equals(eq_args) {
                        return Ok(JsonnetValue::boolean(false));
                    }
                }
                Ok(JsonnetValue::boolean(true))
            }
            (JsonnetValue::Object(obj_a), JsonnetValue::Object(obj_b)) => {
                // Get field names
                let fields_a: Vec<String> = obj_a.keys().cloned().collect();
                let fields_b: Vec<String> = obj_b.keys().cloned().collect();

                if fields_a.len() != fields_b.len() {
                    return Ok(JsonnetValue::boolean(false));
                }

                // Sort for comparison
                let mut sorted_a = fields_a.clone();
                sorted_a.sort();
                let mut sorted_b = fields_b.clone();
                sorted_b.sort();

                if sorted_a != sorted_b {
                    return Ok(JsonnetValue::boolean(false));
                }

                // Compare all field values
                for field in sorted_a {
                    let val_a = &obj_a[&field];
                    let val_b = &obj_b[&field];
                    let eq_args = vec![val_a.clone(), val_b.clone()];
                    if let Ok(JsonnetValue::Boolean(false)) = Self::equals(eq_args) {
                        return Ok(JsonnetValue::boolean(false));
                    }
                }
                Ok(JsonnetValue::boolean(true))
            }
            _ => Ok(JsonnetValue::boolean(false)),
        }
    }

    fn lines(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "lines")?;
        match &args[0] {
            JsonnetValue::Array(arr) => {
                let mut lines = Vec::new();
                for item in arr {
                    // Convert to string representation like Jsonnet does
                    match item {
                        JsonnetValue::String(s) => lines.push(s.clone()),
                        JsonnetValue::Number(n) => lines.push(n.to_string()),
                        JsonnetValue::Boolean(b) => lines.push(b.to_string()),
                        _ => lines.push(format!("{}", item)),
                    }
                }
                lines.push("".to_string()); // Add trailing newline
                Ok(JsonnetValue::string(lines.join("\n")))
            }
            _ => Err(JsonnetError::runtime_error("lines expects an array argument")),
        }
    }

    fn str_replace(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 3, "strReplace")?;

        let str_val = &args[0];
        let from_val = &args[1];
        let to_val = &args[2];

        let str = str_val.as_string()?.to_string();
        let from = from_val.as_string()?.to_string();
        let to = to_val.as_string()?.to_string();

        if from.is_empty() {
            return Err(JsonnetError::runtime_error("'from' string must not be zero length"));
        }

        // Simple implementation using Rust's string replace
        // For now, we'll use a simple approach. Full implementation would need
        // the complex recursive logic from Google Jsonnet
        let result = str.replace(&from, &to);
        Ok(JsonnetValue::string(result))
    }

    fn sha1(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "sha1")?;
        let input = args[0].as_string()?.as_bytes();
        let mut hasher = Sha1::new();
        hasher.update(input);
        let result = hasher.finalize();
        Ok(JsonnetValue::string(hex::encode(result)))
    }

    fn sha256(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "sha256")?;
        let input = args[0].as_string()?.as_bytes();
        let mut hasher = Sha256::new();
        hasher.update(input);
        let result = hasher.finalize();
        Ok(JsonnetValue::string(hex::encode(result)))
    }

    fn sha3(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "sha3")?;
        let input = args[0].as_string()?.as_bytes();
        let mut hasher = Sha3_256::new();
        hasher.update(input);
        let result = hasher.finalize();
        Ok(JsonnetValue::string(hex::encode(result)))
    }

    fn sha512(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "sha512")?;
        let input = args[0].as_string()?.as_bytes();
        let mut hasher = Sha512::new();
        hasher.update(input);
        let result = hasher.finalize();
        Ok(JsonnetValue::string(hex::encode(result)))
    }














    // Phase 4: Advanced Features

    // Manifest functions
    fn manifest_ini(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "manifestIni")?;
        // Simplified INI format - convert object to INI-like format
        match &args[0] {
            JsonnetValue::Object(obj) => {
                let mut result = String::new();
                for (key, value) in obj {
                    if !key.starts_with('_') {
                        result.push_str(&format!("[{}]\n", key));
                        if let JsonnetValue::Object(section) = value {
                            for (k, v) in section {
                                if !k.starts_with('_') {
                                    result.push_str(&format!("{}={}\n", k, v));
                                }
                            }
                        }
                        result.push('\n');
                    }
                }
                Ok(JsonnetValue::string(result.trim().to_string()))
            }
            _ => Err(JsonnetError::runtime_error("manifestIni expects an object")),
        }
    }

    fn manifest_python(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "manifestPython")?;
        // Generate Python dict representation
        let json_str = serde_json::to_string(&args[0].to_json_value())?;
        // Simple conversion - replace JSON syntax with Python dict syntax
        let python_str = json_str
            .replace("null", "None")
            .replace("true", "True")
            .replace("false", "False");
        Ok(JsonnetValue::string(python_str))
    }

    fn manifest_cpp(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "manifestCpp")?;
        // Simplified C++ code generation
        let json_str = serde_json::to_string(&args[0].to_json_value())?;
        let cpp_str = format!("// Generated C++ code\nconst char* jsonData = R\"json(\n{}\n)json\";", json_str);
        Ok(JsonnetValue::string(cpp_str))
    }

    fn manifest_xml_jsonml(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "manifestXmlJsonml")?;
        // JsonML format: [tagName, {attributes}, ...children]
        match &args[0] {
            JsonnetValue::Array(arr) if !arr.is_empty() => {
                if let JsonnetValue::String(tag) = &arr[0] {
                    let mut xml = format!("<{}", tag);

                    // Attributes (second element if it's an object)
                    let mut child_start = 1;
                    if arr.len() > 1 {
                        if let JsonnetValue::Object(attrs) = &arr[1] {
                            for (key, value) in attrs {
                                if !key.starts_with('_') {
                                    let value_str = match value {
                                        JsonnetValue::String(s) => s.clone(),
                                        _ => format!("{}", value),
                                    };
                                    xml.push_str(&format!(" {}=\"{}\"", key, value_str));
                                }
                            }
                            child_start = 2;
                        }
                    }

                    xml.push('>');

                    // Children
                    for child in &arr[child_start..] {
                        match child {
                            JsonnetValue::String(s) => xml.push_str(s),
                            JsonnetValue::Array(_) => {
                                // Recursively process child arrays
                                let child_xml = Self::manifest_xml_jsonml(vec![child.clone()])?;
                                if let JsonnetValue::String(child_str) = child_xml {
                                    xml.push_str(&child_str);
                                }
                            }
                            _ => xml.push_str(&format!("{}", child)),
                        }
                    }

                    xml.push_str(&format!("</{}>", tag));
                    Ok(JsonnetValue::string(xml))
                } else {
                    Err(JsonnetError::runtime_error("JsonML array must start with string tag name"))
                }
            }
            _ => Err(JsonnetError::runtime_error("manifestXmlJsonml expects a JsonML array")),
        }
    }

    // Advanced math functions
    fn log2(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "log2")?;
        let x = args[0].as_number()?;
        if x <= 0.0 {
            return Err(JsonnetError::runtime_error("log2 of non-positive number"));
        }
        Ok(JsonnetValue::number(x.log2()))
    }

    fn log10(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "log10")?;
        let x = args[0].as_number()?;
        if x <= 0.0 {
            return Err(JsonnetError::runtime_error("log10 of non-positive number"));
        }
        Ok(JsonnetValue::number(x.log10()))
    }

    fn log1p(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "log1p")?;
        let x = args[0].as_number()?;
        if x < -1.0 {
            return Err(JsonnetError::runtime_error("log1p of number less than -1"));
        }
        Ok(JsonnetValue::number((x + 1.0).ln()))
    }

    fn expm1(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "expm1")?;
        let x = args[0].as_number()?;
        Ok(JsonnetValue::number(x.exp() - 1.0))
    }

    // Phase 5: Remaining Core Functions

    // Array manipulation functions
    fn remove(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "remove")?;
        let arr = args[0].as_array()?;
        let value_to_remove = &args[1];

        let filtered: Vec<JsonnetValue> = arr.iter()
            .filter(|item| !item.equals(value_to_remove))
            .cloned()
            .collect();

        Ok(JsonnetValue::array(filtered))
    }

    fn remove_at(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "removeAt")?;
        let arr = args[0].as_array()?;
        let index = args[1].as_number()? as usize;

        if index >= arr.len() {
            return Err(JsonnetError::runtime_error("Index out of bounds"));
        }

        let mut result = arr.clone();
        result.remove(index);
        Ok(JsonnetValue::array(result))
    }

    fn flatten_arrays(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "flattenArrays")?;
        let arr = args[0].as_array()?;

        let mut result = Vec::new();
        Self::flatten_array_recursive(arr, &mut result);
        Ok(JsonnetValue::array(result))
    }

    fn flatten_array_recursive(arr: &[JsonnetValue], result: &mut Vec<JsonnetValue>) {
        for item in arr {
            match item {
                JsonnetValue::Array(sub_arr) => {
                    Self::flatten_array_recursive(sub_arr, result);
                }
                _ => result.push(item.clone()),
            }
        }
    }

    // Object manipulation functions
    fn object_keys_values(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "objectKeysValues")?;
        let obj = args[0].as_object()?;

        let mut result = Vec::new();
        for (key, value) in obj {
            if !key.starts_with('_') {
                result.push(JsonnetValue::object(HashMap::from([
                    ("key".to_string(), JsonnetValue::string(key.clone())),
                    ("value".to_string(), value.clone()),
                ])));
            }
        }

        Ok(JsonnetValue::array(result))
    }

    fn object_remove_key(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 2, "objectRemoveKey")?;
        let obj = args[0].as_object()?;
        let key_to_remove = args[1].as_string()?;

        let mut result = obj.clone();
        result.remove(key_to_remove);
        Ok(JsonnetValue::object(result))
    }

    // Additional type checking functions
    fn is_integer(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "isInteger")?;
        match &args[0] {
            JsonnetValue::Number(n) => Ok(JsonnetValue::boolean(n.fract() == 0.0)),
            _ => Ok(JsonnetValue::boolean(false)),
        }
    }

    fn is_decimal(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "isDecimal")?;
        match &args[0] {
            JsonnetValue::Number(n) => Ok(JsonnetValue::boolean(n.fract() != 0.0)),
            _ => Ok(JsonnetValue::boolean(false)),
        }
    }

    fn is_even(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "isEven")?;
        match &args[0] {
            JsonnetValue::Number(n) if n.fract() == 0.0 => {
                Ok(JsonnetValue::boolean((*n as i64) % 2 == 0))
            }
            _ => Ok(JsonnetValue::boolean(false)),
        }
    }

    fn is_odd(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        Self::check_args(&args, 1, "isOdd")?;
        match &args[0] {
            JsonnetValue::Number(n) if n.fract() == 0.0 => {
                Ok(JsonnetValue::boolean((*n as i64) % 2 != 0))
            }
            _ => Ok(JsonnetValue::boolean(false)),
        }
    }

    /// Helper function to check argument count
    fn check_args(args: &[JsonnetValue], expected: usize, func_name: &str) -> Result<()> {
        if args.len() != expected {
            return Err(JsonnetError::invalid_function_call(format!(
                "{}() expects {} arguments, got {}",
                func_name, expected, args.len()
            )));
        }
        Ok(())
    }

    /// Helper function to check argument count range
    fn check_args_range(args: &[JsonnetValue], min: usize, max: usize, func_name: &str) -> Result<()> {
        if args.len() < min || args.len() > max {
            return Err(JsonnetError::invalid_function_call(format!(
                "{}() expects {} to {} arguments, got {}",
                func_name, min, max, args.len()
            )));
        }
        Ok(())
    }

    /// Call a standard library function (static method)
    pub fn call_function(name: &str, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        // Simple implementation - just return an error for now
        // This should dispatch to the appropriate std function
        Err(JsonnetError::runtime_error(format!("StdLib function '{}' not implemented", name)))
    }
}

impl JsonnetValue {
    /// Convert from serde_json::Value to JsonnetValue
    pub fn from_json_value(value: serde_json::Value) -> Self {
        match value {
            serde_json::Value::Null => JsonnetValue::Null,
            serde_json::Value::Bool(b) => JsonnetValue::boolean(b),
            serde_json::Value::Number(n) => JsonnetValue::number(n.as_f64().unwrap_or(0.0)),
            serde_json::Value::String(s) => JsonnetValue::string(s),
            serde_json::Value::Array(arr) => {
                let jsonnet_arr: Vec<JsonnetValue> = arr.into_iter()
                    .map(JsonnetValue::from_json_value)
                    .collect();
                JsonnetValue::array(jsonnet_arr)
            }
            serde_json::Value::Object(obj) => {
                let mut jsonnet_obj = HashMap::new();
                for (k, v) in obj {
                    jsonnet_obj.insert(k, JsonnetValue::from_json_value(v));
                }
                JsonnetValue::object(jsonnet_obj)
            }
        }
    }

    // ===== NEW FUNCTIONS FOR COMPLETE COMPATIBILITY =====

    /// slice(array|string, start, [end]) - Extract slice from array or string
    pub fn slice(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "slice")?;
        let start = args[1].as_number()? as usize;

        match &args[0] {
            JsonnetValue::Array(arr) => {
                let end = if args.len() > 2 {
                    args[2].as_number()? as usize
                } else {
                    arr.len()
                };
                let start = start.min(arr.len());
                let end = end.min(arr.len());
                if start > end {
                    Ok(JsonnetValue::array(vec![]))
                } else {
                    Ok(JsonnetValue::array(arr[start..end].to_vec()))
                }
            }
            JsonnetValue::String(s) => {
                let end = if args.len() > 2 {
                    args[2].as_number()? as usize
                } else {
                    s.chars().count()
                };
                let chars: Vec<char> = s.chars().collect();
                let start = start.min(chars.len());
                let end = end.min(chars.len());
                if start > end {
                    Ok(JsonnetValue::string("".to_string()))
                } else {
                    let sliced: String = chars[start..end].iter().collect();
                    Ok(JsonnetValue::string(sliced))
                }
            }
            _ => Err(JsonnetError::invalid_function_call("slice() expects array or string as first argument".to_string())),
        }
    }

    /// zip(arrays...) - Zip multiple arrays together
    pub fn zip(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        if args.is_empty() {
            return Err(JsonnetError::invalid_function_call("zip() expects at least one argument".to_string()));
        }

        // Convert all arguments to arrays
        let arrays: Result<Vec<Vec<JsonnetValue>>> = args.into_iter()
            .map(|arg| arg.as_array().cloned())
            .collect();

        let arrays = arrays?;
        if arrays.is_empty() {
            return Ok(JsonnetValue::array(vec![]));
        }

        // Find minimum length
        let min_len = arrays.iter().map(|arr| arr.len()).min().unwrap_or(0);

        // Create zipped result
        let mut result = Vec::new();
        for i in 0..min_len {
            let mut tuple = Vec::new();
            for arr in &arrays {
                tuple.push(arr[i].clone());
            }
            result.push(JsonnetValue::array(tuple));
        }

        Ok(JsonnetValue::array(result))
    }

    /// transpose(matrix) - Transpose a matrix (array of arrays)
    pub fn transpose(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "transpose")?;
        let matrix = args[0].as_array()?;

        if matrix.is_empty() {
            return Ok(JsonnetValue::array(vec![]));
        }

        // Check if all elements are arrays and get dimensions
        let mut max_len = 0;
        for row in matrix {
            match row {
                JsonnetValue::Array(arr) => {
                    max_len = max_len.max(arr.len());
                }
                _ => return Err(JsonnetError::invalid_function_call("transpose() expects array of arrays".to_string())),
            }
        }

        if max_len == 0 {
            return Ok(JsonnetValue::array(vec![]));
        }

        // Create transposed matrix
        let mut result = Vec::new();
        for col in 0..max_len {
            let mut new_row = Vec::new();
            for row in matrix {
                if let JsonnetValue::Array(arr) = row {
                    if col < arr.len() {
                        new_row.push(arr[col].clone());
                    } else {
                        new_row.push(JsonnetValue::Null);
                    }
                }
            }
            result.push(JsonnetValue::array(new_row));
        }

        Ok(JsonnetValue::array(result))
    }

    /// flatten(array, [depth]) - Completely flatten nested arrays
    pub fn flatten(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "flatten")?;
        let depth = if args.len() > 1 {
            args[1].as_number()? as usize
        } else {
            usize::MAX
        };

        fn flatten_recursive(arr: &Vec<JsonnetValue>, current_depth: usize, max_depth: usize) -> Vec<JsonnetValue> {
            let mut result = Vec::new();
            for item in arr {
                match item {
                    JsonnetValue::Array(nested) if current_depth < max_depth => {
                        result.extend(flatten_recursive(nested, current_depth + 1, max_depth));
                    }
                    _ => result.push(item.clone()),
                }
            }
            result
        }

        let arr = args[0].as_array()?;
        let flattened = flatten_recursive(arr, 0, depth);
        Ok(JsonnetValue::array(flattened))
    }

    /// sum(array) - Sum all numbers in array
    pub fn sum(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "sum")?;
        let arr = args[0].as_array()?;

        let mut total = 0.0;
        for item in arr {
            total += item.as_number()?;
        }

        Ok(JsonnetValue::number(total))
    }

    /// product(array) - Product of all numbers in array
    pub fn product(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "product")?;
        let arr = args[0].as_array()?;

        let mut result = 1.0;
        for item in arr {
            result *= item.as_number()?;
        }

        Ok(JsonnetValue::number(result))
    }

    /// all(array) - Check if all elements are truthy
    pub fn all(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "all")?;
        let arr = args[0].as_array()?;

        for item in arr {
            if !item.is_truthy() {
                return Ok(JsonnetValue::boolean(false));
            }
        }

        Ok(JsonnetValue::boolean(true))
    }

    /// any(array) - Check if any element is truthy
    pub fn any(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "any")?;
        let arr = args[0].as_array()?;

        for item in arr {
            if item.is_truthy() {
                return Ok(JsonnetValue::boolean(true));
            }
        }

        Ok(JsonnetValue::boolean(false))
    }

    /// sortBy(array, keyFunc) - Sort array by key function
    pub fn sort_by(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "sortBy")?;
        let _arr = args[0].as_array()?.clone();
        let _key_func = &args[1];

        // For now, implement a simple version that assumes the key function returns numbers
        // Full implementation would require function calling callback
        Err(JsonnetError::runtime_error("sortBy() requires function calling mechanism - placeholder implementation".to_string()))
    }

    /// groupBy(array, keyFunc) - Group array elements by key function
    pub fn group_by(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "groupBy")?;
        // Placeholder implementation
        Err(JsonnetError::runtime_error("groupBy() requires function calling mechanism - placeholder implementation".to_string()))
    }

    /// partition(array, predFunc) - Partition array by predicate function
    pub fn partition(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "partition")?;
        // Placeholder implementation
        Err(JsonnetError::runtime_error("partition() requires function calling mechanism - placeholder implementation".to_string()))
    }

    /// chunk(array, size) - Split array into chunks of given size
    pub fn chunk(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "chunk")?;
        let arr = args[0].as_array()?;
        let size = args[1].as_number()? as usize;

        if size == 0 {
            return Err(JsonnetError::invalid_function_call("chunk() size must be positive".to_string()));
        }

        let mut result = Vec::new();
        for chunk in arr.chunks(size) {
            result.push(JsonnetValue::array(chunk.to_vec()));
        }

        Ok(JsonnetValue::array(result))
    }

    /// unique(array) - Remove duplicates from array (alternative to uniq)
    pub fn unique(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "unique")?;
        let arr = args[0].as_array()?;

        let mut seen = std::collections::HashSet::new();
        let mut result = Vec::new();

        for item in arr {
            // Simple equality check - in real Jsonnet this uses deep equality
            if !seen.contains(&format!("{:?}", item)) {
                seen.insert(format!("{:?}", item));
                result.push(item.clone());
            }
        }

        Ok(JsonnetValue::array(result))
    }

    /// difference(arrays...) - Set difference of arrays
    pub fn difference(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        if args.is_empty() {
            return Ok(JsonnetValue::array(vec![]));
        }

        let first = args[0].as_array()?;
        let mut result = first.clone();

        for arg in &args[1..] {
            let other = arg.as_array()?;
            let other_set: std::collections::HashSet<String> = other.iter()
                .map(|v| format!("{:?}", v))
                .collect();

            result.retain(|item| !other_set.contains(&format!("{:?}", item)));
        }

        Ok(JsonnetValue::array(result))
    }

    /// intersection(arrays...) - Set intersection of arrays
    pub fn intersection(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        if args.is_empty() {
            return Ok(JsonnetValue::array(vec![]));
        }

        let first = args[0].as_array()?;
        let mut result = first.clone();

        for arg in &args[1..] {
            let other = arg.as_array()?;
            let other_set: std::collections::HashSet<String> = other.iter()
                .map(|v| format!("{:?}", v))
                .collect();

            result.retain(|item| other_set.contains(&format!("{:?}", item)));
        }

        Ok(JsonnetValue::array(result))
    }

    /// symmetricDifference(a, b) - Symmetric difference of two arrays
    pub fn symmetric_difference(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "symmetricDifference")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        let a_set: std::collections::HashSet<String> = a.iter()
            .map(|v| format!("{:?}", v))
            .collect();
        let b_set: std::collections::HashSet<String> = b.iter()
            .map(|v| format!("{:?}", v))
            .collect();

        let symmetric_diff: std::collections::HashSet<_> = a_set.symmetric_difference(&b_set).cloned().collect();

        let mut result: Vec<JsonnetValue> = a.iter()
            .filter(|item| symmetric_diff.contains(&format!("{:?}", item)))
            .chain(b.iter().filter(|item| symmetric_diff.contains(&format!("{:?}", item))))
            .cloned()
            .collect();

        Ok(JsonnetValue::array(result))
    }

    /// isSubset(a, b) - Check if a is subset of b
    pub fn is_subset(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "isSubset")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        let b_set: std::collections::HashSet<String> = b.iter()
            .map(|v| format!("{:?}", v))
            .collect();

        let is_subset = a.iter().all(|item| b_set.contains(&format!("{:?}", item)));

        Ok(JsonnetValue::boolean(is_subset))
    }

    /// isSuperset(a, b) - Check if a is superset of b
    pub fn is_superset(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "isSuperset")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        let a_set: std::collections::HashSet<String> = a.iter()
            .map(|v| format!("{:?}", v))
            .collect();

        let is_superset = b.iter().all(|item| a_set.contains(&format!("{:?}", item)));

        Ok(JsonnetValue::boolean(is_superset))
    }

    /// isDisjoint(a, b) - Check if a and b are disjoint
    pub fn is_disjoint(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "isDisjoint")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        let a_set: std::collections::HashSet<String> = a.iter()
            .map(|v| format!("{:?}", v))
            .collect();
        let b_set: std::collections::HashSet<String> = b.iter()
            .map(|v| format!("{:?}", v))
            .collect();

        let is_disjoint = a_set.intersection(&b_set).count() == 0;

        Ok(JsonnetValue::boolean(is_disjoint))
    }

    /// cartesian(arrays) - Cartesian product of arrays
    pub fn cartesian(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "cartesian")?;
        let arrays = args[0].as_array()?;

        if arrays.is_empty() {
            return Ok(JsonnetValue::array(vec![JsonnetValue::array(vec![])]));
        }

        // Convert to vectors
        let mut vec_arrays = Vec::new();
        for arr in arrays {
            vec_arrays.push(arr.as_array()?.clone());
        }

        fn cartesian_product(arrays: &[Vec<JsonnetValue>]) -> Vec<Vec<JsonnetValue>> {
            if arrays.is_empty() {
                return vec![vec![]];
            }

            let mut result = Vec::new();
            let first = &arrays[0];
            let rest = &arrays[1..];

            for item in first {
                for mut combo in cartesian_product(rest) {
                    combo.insert(0, item.clone());
                    result.push(combo);
                }
            }

            result
        }

        let products = cartesian_product(&vec_arrays);
        let result: Vec<JsonnetValue> = products.into_iter()
            .map(|combo| JsonnetValue::array(combo))
            .collect();

        Ok(JsonnetValue::array(result))
    }

    /// cross(a, b) - Cross product of two arrays
    pub fn cross(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "cross")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        let mut result = Vec::new();
        for item_a in a {
            for item_b in b {
                result.push(JsonnetValue::array(vec![item_a.clone(), item_b.clone()]));
            }
        }

        Ok(JsonnetValue::array(result))
    }

    /// dot(a, b) - Dot product of two numeric arrays
    pub fn dot(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "dot")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        if a.len() != b.len() {
            return Err(JsonnetError::invalid_function_call("dot() arrays must have same length".to_string()));
        }

        let mut sum = 0.0;
        for (x, y) in a.iter().zip(b.iter()) {
            sum += x.as_number()? * y.as_number()?;
        }

        Ok(JsonnetValue::number(sum))
    }

    /// norm(array) - Euclidean norm of numeric array
    pub fn norm(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "norm")?;
        let arr = args[0].as_array()?;

        let mut sum_squares = 0.0;
        for item in arr {
            let val = item.as_number()?;
            sum_squares += val * val;
        }

        Ok(JsonnetValue::number(sum_squares.sqrt()))
    }

    /// normalize(array) - Normalize numeric array
    pub fn normalize(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "normalize")?;
        let arr = args[0].as_array()?;

        // Calculate norm directly to avoid recursion
        let mut sum_squares = 0.0;
        for item in arr {
            let val = item.as_number()?;
            sum_squares += val * val;
        }
        let norm_val = sum_squares.sqrt();
        if norm_val == 0.0 {
            return Ok(args[0].clone());
        }

        let mut result = Vec::new();
        for item in arr {
            let val = item.as_number()?;
            result.push(JsonnetValue::number(val / norm_val));
        }

        Ok(JsonnetValue::array(result))
    }

    /// distance(a, b) - Euclidean distance between two points
    pub fn distance(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "distance")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        if a.len() != b.len() {
            return Err(JsonnetError::invalid_function_call("distance() arrays must have same length".to_string()));
        }

        let mut sum_squares = 0.0;
        for (x, y) in a.iter().zip(b.iter()) {
            let diff = x.as_number()? - y.as_number()?;
            sum_squares += diff * diff;
        }

        Ok(JsonnetValue::number(sum_squares.sqrt()))
    }

    /// angle(a, b) - Angle between two vectors
    pub fn angle(&mut self, args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "angle")?;
        let a = args[0].as_array()?;
        let b = args[1].as_array()?;

        if a.len() != b.len() {
            return Err(JsonnetError::invalid_function_call("angle() arrays must have same length".to_string()));
        }

        // Calculate dot product directly
        let mut dot_product = 0.0;
        for (x, y) in a.iter().zip(b.iter()) {
            dot_product += x.as_number()? * y.as_number()?;
        }

        // Calculate norms directly
        let mut norm_a_sq = 0.0;
        for item in a {
            let val = item.as_number()?;
            norm_a_sq += val * val;
        }
        let norm_a = norm_a_sq.sqrt();

        let mut norm_b_sq = 0.0;
        for item in b {
            let val = item.as_number()?;
            norm_b_sq += val * val;
        }
        let norm_b = norm_b_sq.sqrt();

        if norm_a == 0.0 || norm_b == 0.0 {
            return Ok(JsonnetValue::number(0.0));
        }

        let cos_theta = dot_product / (norm_a * norm_b);
        let cos_theta = cos_theta.max(-1.0).min(1.0); // Clamp to avoid floating point errors

        Ok(JsonnetValue::number(cos_theta.acos()))
    }

    /// rotate(point, angle, [center]) - Rotate 2D point
    pub fn rotate(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "rotate")?;
        let point = args[0].as_array()?;
        let angle = args[1].as_number()?;

        if point.len() != 2 {
            return Err(JsonnetError::invalid_function_call("rotate() point must be 2D".to_string()));
        }

        let center = if args.len() > 2 {
            args[2].as_array()?.to_vec()
        } else {
            vec![JsonnetValue::number(0.0), JsonnetValue::number(0.0)]
        };

        if center.len() != 2 {
            return Err(JsonnetError::invalid_function_call("rotate() center must be 2D".to_string()));
        }

        let x = point[0].as_number()? - center[0].as_number()?;
        let y = point[1].as_number()? - center[1].as_number()?;

        let cos_a = angle.cos();
        let sin_a = angle.sin();

        let new_x = x * cos_a - y * sin_a + center[0].as_number()?;
        let new_y = x * sin_a + y * cos_a + center[1].as_number()?;

        Ok(JsonnetValue::array(vec![JsonnetValue::number(new_x), JsonnetValue::number(new_y)]))
    }

    /// scale(point, factor, [center]) - Scale 2D point
    pub fn scale(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "scale")?;
        let point = args[0].as_array()?;
        let factor = args[1].as_number()?;

        if point.len() != 2 {
            return Err(JsonnetError::invalid_function_call("scale() point must be 2D".to_string()));
        }

        let center = if args.len() > 2 {
            args[2].as_array()?.to_vec()
        } else {
            vec![JsonnetValue::number(0.0), JsonnetValue::number(0.0)]
        };

        if center.len() != 2 {
            return Err(JsonnetError::invalid_function_call("scale() center must be 2D".to_string()));
        }

        let x = point[0].as_number()? - center[0].as_number()?;
        let y = point[1].as_number()? - center[1].as_number()?;

        let new_x = x * factor + center[0].as_number()?;
        let new_y = y * factor + center[1].as_number()?;

        Ok(JsonnetValue::array(vec![JsonnetValue::number(new_x), JsonnetValue::number(new_y)]))
    }

    /// translate(point, offset) - Translate 2D point
    pub fn translate(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "translate")?;
        let point = args[0].as_array()?;
        let offset = args[1].as_array()?;

        if point.len() != 2 || offset.len() != 2 {
            return Err(JsonnetError::invalid_function_call("translate() requires 2D point and offset".to_string()));
        }

        let new_x = point[0].as_number()? + offset[0].as_number()?;
        let new_y = point[1].as_number()? + offset[1].as_number()?;

        Ok(JsonnetValue::array(vec![JsonnetValue::number(new_x), JsonnetValue::number(new_y)]))
    }

    /// reflect(point, axis) - Reflect 2D point over axis
    pub fn reflect(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "reflect")?;
        let point = args[0].as_array()?;
        let axis = args[1].as_number()?; // angle of reflection axis in radians

        if point.len() != 2 {
            return Err(JsonnetError::invalid_function_call("reflect() point must be 2D".to_string()));
        }

        let x = point[0].as_number()?;
        let y = point[1].as_number()?;

        let cos_2a = (2.0 * axis).cos();
        let sin_2a = (2.0 * axis).sin();

        let new_x = x * cos_2a + y * sin_2a;
        let new_y = x * sin_2a - y * cos_2a;

        Ok(JsonnetValue::array(vec![JsonnetValue::number(new_x), JsonnetValue::number(new_y)]))
    }

    /// affine(point, matrix) - Apply affine transformation
    pub fn affine(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "affine")?;
        let point = args[0].as_array()?;
        let matrix = args[1].as_array()?;

        if point.len() != 2 {
            return Err(JsonnetError::invalid_function_call("affine() point must be 2D".to_string()));
        }

        if matrix.len() != 6 {
            return Err(JsonnetError::invalid_function_call("affine() matrix must be 6 elements [a,b,c,d,e,f]".to_string()));
        }

        let x = point[0].as_number()?;
        let y = point[1].as_number()?;

        let a = matrix[0].as_number()?;
        let b = matrix[1].as_number()?;
        let c = matrix[2].as_number()?;
        let d = matrix[3].as_number()?;
        let e = matrix[4].as_number()?;
        let f = matrix[5].as_number()?;

        let new_x = a * x + b * y + e;
        let new_y = c * x + d * y + f;

        Ok(JsonnetValue::array(vec![JsonnetValue::number(new_x), JsonnetValue::number(new_y)]))
    }

    /// splitLimit(string, sep, limit) - Split string with limit
    pub fn split_limit(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 3, "splitLimit")?;
        let s = args[0].as_string()?;
        let sep = args[1].as_string()?;
        let limit = args[2].as_number()? as usize;

        if sep.is_empty() {
            // Split into characters
            let chars: Vec<String> = s.chars().take(limit).map(|c| c.to_string()).collect();
            let result: Vec<JsonnetValue> = chars.into_iter().map(JsonnetValue::string).collect();
            return Ok(JsonnetValue::array(result));
        }

        let mut parts: Vec<&str> = s.splitn(limit + 1, &sep).collect();
        if parts.len() > limit {
            // Join the remaining parts
            let remaining = parts.split_off(limit);
            parts.push(&s[(s.len() - remaining.join(&sep).len())..]);
        }

        let result: Vec<JsonnetValue> = parts.into_iter().map(|s| JsonnetValue::string(s.to_string())).collect();
        Ok(JsonnetValue::array(result))
    }

    /// join(sep, arrays...) - Join arrays with separator (variadic version)
    pub fn join_variadic(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        if args.is_empty() {
            return Err(JsonnetError::invalid_function_call("join() expects at least one argument".to_string()));
        }

        let sep = args[0].as_string()?;
        let arrays: Result<Vec<Vec<JsonnetValue>>> = args[1..].iter()
            .map(|arg| arg.as_array().cloned())
            .collect();

        let arrays = arrays?;
        let mut result = Vec::new();

        for (i, arr) in arrays.iter().enumerate() {
            if i > 0 && !sep.is_empty() {
                result.push(JsonnetValue::string(sep.clone()));
            }
            result.extend(arr.iter().cloned());
        }

        Ok(JsonnetValue::array(result))
    }

    /// replace(string, old, new) - Replace all occurrences
    pub fn replace(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 3, "replace")?;
        let s = args[0].as_string()?;
        let old = args[1].as_string()?;
        let new = args[2].as_string()?;

        let result = s.replace(&old, &new);
        Ok(JsonnetValue::string(result))
    }

    /// contains(container, element) - Check if container contains element
    pub fn contains_variadic(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "contains")?;

        match &args[0] {
            JsonnetValue::Array(arr) => {
                // Simple linear search with string comparison
                let target = format!("{:?}", &args[1]);
                for item in arr {
                    if format!("{:?}", item) == target {
                        return Ok(JsonnetValue::boolean(true));
                    }
                }
                Ok(JsonnetValue::boolean(false))
            }
            JsonnetValue::String(s) => {
                let substr = args[1].as_string()?;
                Ok(JsonnetValue::boolean(s.contains(&substr)))
            }
            JsonnetValue::Object(obj) => {
                let key = args[1].as_string()?;
                Ok(JsonnetValue::boolean(obj.contains_key(&*key)))
            }
            _ => Err(JsonnetError::invalid_function_call("contains() expects array, string, or object".to_string())),
        }
    }

    // ==========================================
    // AI Agent Functions (Manimani)
    // ==========================================

    /// ai.httpGet(url, headers={}) - Make HTTP GET request
    pub fn ai_http_get(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args_range(&args, 1, 2, "ai.httpGet")?;
        let url = args[0].as_string()?;
        let headers = if args.len() > 1 {
            args[1].as_object()?.clone()
        } else {
            HashMap::new()
        };

        // This would be implemented as an external function call
        // For now, return a placeholder
        let result = json!({
            "url": url,
            "method": "GET",
            "headers": headers,
            "status": "pending",
            "body": "HTTP request will be executed by runtime"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// ai.httpPost(url, body, headers={}) - Make HTTP POST request
    pub fn ai_http_post(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args_range(&args, 2, 3, "ai.httpPost")?;
        let url = args[0].as_string()?;
        let body = args[1].clone();
        let headers = if args.len() > 2 {
            args[2].as_object()?.clone()
        } else {
            HashMap::new()
        };

        // This would be implemented as an external function call
        let result = json!({
            "url": url,
            "method": "POST",
            "body": body,
            "headers": headers,
            "status": "pending"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// ai.callModel(model, messages, options={}) - Call AI model
    pub fn ai_call_model(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args_range(&args, 2, 3, "ai.callModel")?;
        let model = args[0].as_string()?;
        let messages = args[1].as_array()?.clone();
        let options = if args.len() > 2 {
            args[2].as_object()?.clone()
        } else {
            HashMap::new()
        };

        // This would call the AI model API
        let result = json!({
            "model": model,
            "messages": messages,
            "options": options,
            "status": "pending",
            "response": "AI model response will be generated by runtime"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// tool.execute(command, args=[], env={}) - Execute external command
    pub fn tool_execute(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args_range(&args, 1, 3, "tool.execute")?;
        let command = args[0].as_string()?;
        let cmd_args = if args.len() > 1 {
            args[1].as_array()?.clone()
        } else {
            Vec::new()
        };
        let env = if args.len() > 2 {
            args[2].as_object()?.clone()
        } else {
            HashMap::new()
        };

        // This would execute the external command
        let result = json!({
            "command": command,
            "args": cmd_args,
            "env": env,
            "status": "pending",
            "output": "Command will be executed by runtime"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// memory.get(key) - Get value from memory
    pub fn memory_get(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "memory.get")?;
        let key = args[0].as_string()?;

        // This would retrieve from memory store
        let result = json!({
            "key": key,
            "operation": "get",
            "status": "pending",
            "value": null
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// memory.set(key, value) - Set value in memory
    pub fn memory_set(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "memory.set")?;
        let key = args[0].as_string()?;
        let value = args[1].clone();

        // This would store in memory store
        let result = json!({
            "key": key,
            "value": value,
            "operation": "set",
            "status": "pending"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// agent.create(type, config) - Create an AI agent
    pub fn agent_create(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "agent.create")?;
        let agent_type = args[0].as_string()?;
        let config = args[1].as_object()?.clone();

        // This would create an agent instance
        let result = json!({
            "type": agent_type,
            "config": config,
            "id": "agent_id_placeholder",
            "status": "created"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// agent.execute(agent, input) - Execute agent with input
    pub fn agent_execute(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "agent.execute")?;
        let agent = args[0].clone();
        let input = args[1].as_string()?;

        // This would execute the agent
        let result = json!({
            "agent": agent,
            "input": input,
            "status": "pending",
            "output": "Agent execution will be handled by runtime"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// chain.create(steps) - Create a processing chain
    pub fn chain_create(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 1, "chain.create")?;
        let steps = args[0].as_array()?.clone();

        // This would create a processing chain
        let result = json!({
            "steps": steps,
            "id": "chain_id_placeholder",
            "status": "created"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

    /// chain.execute(chain, input) - Execute a processing chain
    pub fn chain_execute(args: Vec<JsonnetValue>) -> Result<JsonnetValue> {
        StdLib::check_args(&args, 2, "chain.execute")?;
        let chain = args[0].clone();
        let input = args[1].clone();

        // This would execute the chain
        let result = json!({
            "chain": chain,
            "input": input,
            "status": "pending",
            "output": "Chain execution will be handled by runtime"
        });
        Ok(JsonnetValue::from_json_value(result))
    }

}