poe2-agent 0.2.1

AI agent for Path of Exile 2 build analysis
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
//! Path of Building 2 headless integration.
//!
//! Provides a Rust interface to Path of Building 2's
//! calculation engine via embedded Lua.

use mlua::{Lua, Result as LuaResult};
use std::collections::{HashMap, HashSet, VecDeque};
use std::path::Path;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum PobError {
    #[error("Lua error: {0}")]
    Lua(#[from] mlua::Error),

    #[error("PoB not initialized")]
    NotInitialized,

    #[error("Invalid build code: {0}")]
    InvalidBuildCode(String),

    #[error("Calculation failed: {0}")]
    CalculationFailed(String),

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

/// Path of Building headless instance.
pub struct PobHeadless {
    lua: Lua,
    initialized: bool,
    /// PoB `src/` directory — needed as CWD for Lua calls that trigger Build:Init.
    pob_src_path: Option<std::path::PathBuf>,
}

/// Build statistics from PoB calculations.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct BuildStats {
    #[serde(rename = "dps")]
    pub total_dps: f64,
    pub effective_hp: f64,
    pub life: f64,
    pub energy_shield: f64,
    pub armour: f64,
    pub evasion: f64,
    pub fire_res: i32,
    pub cold_res: i32,
    pub lightning_res: i32,
    pub chaos_res: i32,
}

impl PobHeadless {
    /// Create a new PoB headless instance.
    pub fn new() -> LuaResult<Self> {
        let lua = Lua::new();
        Ok(Self {
            lua,
            initialized: false,
            pob_src_path: None,
        })
    }

    /// Initialize PoB with the path to PoB2 installation.
    ///
    /// `pob_path` should point to the PoB2 root directory (containing `src/`).
    pub fn init(&mut self, pob_path: &str) -> Result<(), PobError> {
        let pob_path = Path::new(pob_path);
        let pob_src_path = pob_path.join("src");
        let pob_runtime_lua = pob_path.join("runtime/lua");

        // PoB's Lua files use relative dofile() calls, so we must change to src/
        let original_cwd = std::env::current_dir()?;
        std::env::set_current_dir(&pob_src_path)?;

        tracing::info!("Initializing PoB from {:?}", pob_src_path);

        // Set up Lua package.path to include PoB's runtime/lua directory
        // This is where xml.lua and other dependencies live
        let runtime_lua_path = pob_runtime_lua
            .to_str()
            .ok_or_else(|| PobError::CalculationFailed("Invalid path".to_owned()))?;

        self.lua
            .load(format!(
                r#"package.path = package.path .. ";{0}/?.lua;{0}/?/init.lua""#,
                runtime_lua_path
            ))
            .exec()?;

        // Provide a minimal lua-utf8 stub since it's a C module we can't load in safe mode
        // This provides basic string operations that fall back to regular string functions
        self.lua
            .load(
                r#"
                package.preload['lua-utf8'] = function()
                    local utf8 = {}
                    utf8.reverse = string.reverse
                    utf8.gsub = string.gsub
                    utf8.find = string.find
                    utf8.sub = string.sub
                    utf8.match = string.match
                    utf8.len = string.len
                    function utf8.next(s, i, offset)
                        if offset == -1 then
                            return i > 1 and i - 1 or nil
                        else
                            return i < #s and i + 1 or nil
                        end
                    end
                    return utf8
                end
                "#,
            )
            .exec()?;

        // Provide empty arg table (command line arguments)
        self.lua.load("arg = {}").exec()?;

        // Load HeadlessWrapper.lua which bootstraps everything
        let result = self.lua.load("dofile('HeadlessWrapper.lua')").exec();

        // Always restore the original working directory
        std::env::set_current_dir(original_cwd)?;

        result?;

        self.initialized = true;
        self.pob_src_path = Some(pob_src_path.to_owned());
        tracing::info!("PoB headless initialized successfully");
        Ok(())
    }

    /// Load a build from XML export.
    pub fn load_build_xml(&self, xml: &str) -> Result<(), PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }

        // loadBuildFromXML triggers Build:Init which re-creates all tabs via
        // LoadModule (relative paths).  CWD must be the PoB src/ directory.
        let result = self.with_pob_cwd(|lua| {
            let load_fn: mlua::Function = lua.globals().get("loadBuildFromXML")?;
            load_fn.call::<()>((xml, "imported_build"))
        })?;

        tracing::debug!("Build loaded from XML");
        Ok(result)
    }

    /// Import a build from a PoB code (base64 encoded).
    pub fn import_build(&self, _code: &str) -> Result<(), PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }

        // TODO: Decode and import build (requires Inflate support)
        Err(PobError::InvalidBuildCode(
            "Build code import not yet implemented (requires Inflate)".to_owned(),
        ))
    }

    /// Calculate build statistics from the currently loaded build.
    pub fn calculate(&self) -> Result<BuildStats, PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }

        // Navigate: build.calcsTab.mainOutput
        let build: mlua::Table = self.lua.globals().get("build")?;
        let calcs_tab: mlua::Table = build.get("calcsTab")?;
        let main_output: mlua::Table = calcs_tab.get("mainOutput")?;

        // For EHP, we need calcsOutput
        let calcs_output: mlua::Table = calcs_tab.get("calcsOutput")?;

        // Extract stats with safe defaults
        let total_dps = main_output
            .get::<f64>("TotalDPS")
            .or_else(|_| main_output.get::<f64>("CombinedDPS"))
            .unwrap_or(0.0);

        let life = main_output.get::<f64>("Life").unwrap_or(0.0);
        let energy_shield = main_output.get::<f64>("EnergyShield").unwrap_or(0.0);
        let armour = main_output.get::<f64>("Armour").unwrap_or(0.0);
        let evasion = main_output.get::<f64>("Evasion").unwrap_or(0.0);

        // Resistances
        let fire_res = main_output.get::<i32>("FireResist").unwrap_or(0);
        let cold_res = main_output.get::<i32>("ColdResist").unwrap_or(0);
        let lightning_res = main_output.get::<i32>("LightningResist").unwrap_or(0);
        let chaos_res = main_output.get::<i32>("ChaosResist").unwrap_or(0);

        // EHP from calcsOutput
        let effective_hp = calcs_output
            .get::<f64>("PhysicalMaximumHitTaken")
            .unwrap_or(0.0);

        Ok(BuildStats {
            total_dps,
            effective_hp,
            life,
            energy_shield,
            armour,
            evasion,
            fire_res,
            cold_res,
            lightning_res,
            chaos_res,
        })
    }

    /// Query extended build stats (~40 fields) grouped by category.
    ///
    /// Reads from `mainOutput` and `calcsOutput`, returning a JSON object
    /// with keys: offense, defense, resources, speed, charges.
    pub fn query_build_stats(&self) -> Result<serde_json::Value, PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }

        let build: mlua::Table = self.lua.globals().get("build")?;
        let calcs_tab: mlua::Table = build.get("calcsTab")?;
        let main_output: mlua::Table = calcs_tab.get("mainOutput")?;
        let calcs_output: mlua::Table = calcs_tab.get("calcsOutput")?;

        let offense_fields = &[
            "TotalDPS",
            "CombinedDPS",
            "AverageHit",
            "Speed",
            "CritChance",
            "CritMultiplier",
            "HitChance",
            "TotalDot",
            "BleedDPS",
            "IgniteDPS",
            "PoisonDPS",
            "FullDPS",
            "WithPoisonDPS",
            "WithIgniteDPS",
            "WithBleedDPS",
            "TotalDotDPS",
            "Damage",
            "PhysicalDamage",
            "ElementalDamage",
            "FireDamage",
            "ColdDamage",
            "LightningDamage",
            "ChaosDamage",
        ];

        let defense_fields = &[
            "TotalEHP",
            "PhysicalMaximumHitTaken",
            "FireMaximumHitTaken",
            "ColdMaximumHitTaken",
            "LightningMaximumHitTaken",
            "ChaosMaximumHitTaken",
            "Armour",
            "PhysicalDamageReduction",
            "Evasion",
            "EvadeChance",
            "BlockChance",
            "SpellBlockChance",
            "SpellSuppressionChance",
            "FireResist",
            "ColdResist",
            "LightningResist",
            "ChaosResist",
            "FireResistOverCap",
            "ColdResistOverCap",
            "LightningResistOverCap",
            "ChaosResistOverCap",
        ];

        let resource_fields = &[
            "Life",
            "LifeUnreserved",
            "LifeRegenRecovery",
            "Mana",
            "ManaUnreserved",
            "ManaRegenRecovery",
            "EnergyShield",
            "EnergyShieldRegenRecovery",
            "Spirit",
        ];

        let speed_fields = &[
            "EffectiveMovementSpeedMod",
            "AreaOfEffectRadiusMetres",
            "Duration",
            "ManaCost",
        ];

        let charge_fields = &[
            "PowerChargesMax",
            "FrenzyChargesMax",
            "EnduranceChargesMax",
        ];

        let offense = read_fields(&main_output, offense_fields);
        let mut defense = read_fields(&main_output, defense_fields);
        // TotalEHP and MaxHitTaken fields come from calcsOutput
        merge_fields(&mut defense, &read_fields(&calcs_output, defense_fields));
        let resources = read_fields(&main_output, resource_fields);
        let speed = read_fields(&main_output, speed_fields);
        let charges = read_fields(&main_output, charge_fields);

        Ok(serde_json::json!({
            "offense": offense,
            "defense": defense,
            "resources": resources,
            "speed": speed,
            "charges": charges,
        }))
    }

    /// Query the list of skills with their DPS and gem links.
    ///
    /// Reads from `SkillDPS` array in `mainOutput` and
    /// `socketGroupList` in `skillsTab`.
    pub fn query_skill_list(&self) -> Result<serde_json::Value, PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }

        let build: mlua::Table = self.lua.globals().get("build")?;
        let calcs_tab: mlua::Table = build.get("calcsTab")?;
        let main_output: mlua::Table = calcs_tab.get("mainOutput")?;

        // Read SkillDPS array from mainOutput
        let mut skill_dps_list = Vec::new();
        if let Ok(skill_dps_table) = main_output.get::<mlua::Table>("SkillDPS") {
            let len = skill_dps_table.raw_len();
            for i in 1..=len {
                if let Ok(entry) = skill_dps_table.get::<mlua::Table>(i) {
                    let mut skill = serde_json::Map::new();
                    if let Ok(name) = entry.get::<String>("name") {
                        skill.insert("name".to_owned(), serde_json::Value::String(name));
                    }
                    if let Ok(dps) = entry.get::<f64>("dps") {
                        skill.insert(
                            "dps".to_owned(),
                            serde_json::Value::Number(
                                serde_json::Number::from_f64(dps)
                                    .unwrap_or_else(|| serde_json::Number::from(0)),
                            ),
                        );
                    }
                    if let Ok(count) = entry.get::<i64>("count") {
                        skill.insert(
                            "count".to_owned(),
                            serde_json::Value::Number(count.into()),
                        );
                    }
                    if let Ok(trigger) = entry.get::<String>("trigger") {
                        skill.insert("trigger".to_owned(), serde_json::Value::String(trigger));
                    }
                    if let Ok(skill_part) = entry.get::<String>("skillPart") {
                        skill.insert(
                            "skillPart".to_owned(),
                            serde_json::Value::String(skill_part),
                        );
                    }
                    if !skill.is_empty() {
                        skill_dps_list.push(serde_json::Value::Object(skill));
                    }
                }
            }
        }

        // Read socket group list from skillsTab
        let mut socket_groups = Vec::new();
        if let Ok(skills_tab) = build.get::<mlua::Table>("skillsTab") {
            if let Ok(group_list) = skills_tab.get::<mlua::Table>("socketGroupList") {
                let len = group_list.raw_len();
                for i in 1..=len {
                    if let Ok(group) = group_list.get::<mlua::Table>(i) {
                        let mut group_obj = serde_json::Map::new();

                        if let Ok(label) = group.get::<String>("displayLabel") {
                            group_obj.insert(
                                "label".to_owned(),
                                serde_json::Value::String(label),
                            );
                        }
                        if let Ok(enabled) = group.get::<bool>("enabled") {
                            group_obj
                                .insert("enabled".to_owned(), serde_json::Value::Bool(enabled));
                        }
                        if let Ok(slot) = group.get::<String>("slot") {
                            group_obj.insert("slot".to_owned(), serde_json::Value::String(slot));
                        }

                        // Read gem list for this group
                        let mut gems = Vec::new();
                        if let Ok(gem_list) = group.get::<mlua::Table>("gemList") {
                            let gem_len = gem_list.raw_len();
                            for j in 1..=gem_len {
                                if let Ok(gem) = gem_list.get::<mlua::Table>(j) {
                                    let mut gem_obj = serde_json::Map::new();
                                    if let Ok(name) = gem.get::<String>("nameSpec") {
                                        gem_obj.insert(
                                            "name".to_owned(),
                                            serde_json::Value::String(name),
                                        );
                                    }
                                    if let Ok(level) = gem.get::<i64>("level") {
                                        gem_obj.insert(
                                            "level".to_owned(),
                                            serde_json::Value::Number(level.into()),
                                        );
                                    }
                                    if let Ok(quality) = gem.get::<i64>("quality") {
                                        gem_obj.insert(
                                            "quality".to_owned(),
                                            serde_json::Value::Number(quality.into()),
                                        );
                                    }
                                    if let Ok(enabled) = gem.get::<bool>("enabled") {
                                        gem_obj.insert(
                                            "enabled".to_owned(),
                                            serde_json::Value::Bool(enabled),
                                        );
                                    }
                                    if !gem_obj.is_empty() {
                                        gems.push(serde_json::Value::Object(gem_obj));
                                    }
                                }
                            }
                        }
                        if !gems.is_empty() {
                            group_obj
                                .insert("gems".to_owned(), serde_json::Value::Array(gems));
                        }

                        if !group_obj.is_empty() {
                            socket_groups.push(serde_json::Value::Object(group_obj));
                        }
                    }
                }
            }
        }

        Ok(serde_json::json!({
            "skill_dps": skill_dps_list,
            "socket_groups": socket_groups,
        }))
    }

    /// Query the build configuration flags.
    ///
    /// Reads `build.configTab.input` as flat key-value pairs.
    pub fn query_config(&self) -> Result<serde_json::Value, PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }

        let build: mlua::Table = self.lua.globals().get("build")?;
        let config_tab: mlua::Table = build.get("configTab")?;
        let input: mlua::Table = config_tab.get("input")?;

        let mut config = serde_json::Map::new();
        for pair in input.pairs::<String, mlua::Value>() {
            let (key, value) = pair?;
            let json_val = match value {
                mlua::Value::Boolean(b) => serde_json::Value::Bool(b),
                mlua::Value::Integer(n) => serde_json::Value::Number(n.into()),
                mlua::Value::Number(n) => {
                    if let Some(num) = serde_json::Number::from_f64(n) {
                        serde_json::Value::Number(num)
                    } else {
                        continue;
                    }
                }
                mlua::Value::String(s) => {
                    serde_json::Value::String(
                        s.to_str().map(|s| s.to_owned()).unwrap_or_default(),
                    )
                }
                _ => continue,
            };
            config.insert(key, json_val);
        }

        Ok(serde_json::Value::Object(config))
    }

    /// Query the item equipped in the given slot.
    ///
    /// Returns a JSON object with the item's name, base type, rarity, quality,
    /// spirit, sockets, and all mod lines (implicit, explicit, enchant, rune).
    /// If the slot is empty, returns `{ "slot": "<name>", "empty": true }`.
    pub fn query_item(&self, slot: &str) -> Result<serde_json::Value, PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }

        let build: mlua::Table = self.lua.globals().get("build")?;
        let items_tab: mlua::Table = build.get("itemsTab")?;
        let active_item_set: mlua::Table = items_tab.get("activeItemSet")?;

        // Look up the slot in the active item set
        let slot_entry: mlua::Table = match active_item_set.get::<mlua::Table>(slot) {
            Ok(t) => t,
            Err(_) => return Ok(serde_json::json!({ "slot": slot, "empty": true })),
        };

        // Read selItemId — if nil or 0, the slot is empty
        let sel_item_id: i64 = slot_entry.get::<i64>("selItemId").unwrap_or(0);
        if sel_item_id == 0 {
            return Ok(serde_json::json!({ "slot": slot, "empty": true }));
        }

        // Look up the item in items[selItemId]
        let items: mlua::Table = items_tab.get("items")?;
        let item: mlua::Table = match items.get::<mlua::Table>(sel_item_id) {
            Ok(t) => t,
            Err(_) => return Ok(serde_json::json!({ "slot": slot, "empty": true })),
        };

        let name = item.get::<String>("name").unwrap_or_default();
        let base_name = item
            .get::<mlua::Table>("base")
            .and_then(|b| b.get::<String>("name"))
            .unwrap_or_default();
        let rarity = item.get::<String>("rarity").unwrap_or_default();
        let quality = item.get::<i64>("quality").unwrap_or(0);
        let spirit = item.get::<i64>("spiritValue").unwrap_or(0);
        let sockets = item.get::<i64>("itemSocketCount").unwrap_or(0);

        let implicits = read_mod_lines(&item, "implicitModLines");
        let explicits = read_mod_lines(&item, "explicitModLines");
        let enchants = read_mod_lines(&item, "enchantModLines");
        let runes = read_mod_lines(&item, "runeModLines");

        Ok(serde_json::json!({
            "slot": slot,
            "name": name,
            "base": base_name,
            "rarity": rarity,
            "quality": quality,
            "spirit": spirit,
            "sockets": sockets,
            "implicits": implicits,
            "explicits": explicits,
            "enchants": enchants,
            "runes": runes,
        }))
    }

    /// Query all equipment slots: which are empty and which have items.
    ///
    /// Returns a JSON object with `empty_slots` (names), `filled_slots`
    /// (name, item, rarity), and counts for each.
    pub fn query_empty_slots(&self) -> Result<serde_json::Value, PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }

        const ALL_SLOTS: &[&str] = &[
            "Weapon 1",
            "Weapon 2",
            "Helmet",
            "Body Armour",
            "Gloves",
            "Boots",
            "Amulet",
            "Ring 1",
            "Ring 2",
            "Ring 3",
            "Belt",
            "Charm 1",
            "Charm 2",
            "Charm 3",
            "Flask 1",
            "Flask 2",
        ];

        let build: mlua::Table = self.lua.globals().get("build")?;
        let items_tab: mlua::Table = build.get("itemsTab")?;
        let active_item_set: mlua::Table = items_tab.get("activeItemSet")?;
        let items: mlua::Table = items_tab.get("items")?;

        let mut empty_slots = Vec::new();
        let mut filled_slots = Vec::new();

        for &slot in ALL_SLOTS {
            let sel_item_id: i64 = active_item_set
                .get::<mlua::Table>(slot)
                .and_then(|entry| entry.get::<i64>("selItemId"))
                .unwrap_or(0);

            if sel_item_id == 0 {
                empty_slots.push(slot);
                continue;
            }

            let (name, rarity) = match items.get::<mlua::Table>(sel_item_id) {
                Ok(item) => (
                    item.get::<String>("name").unwrap_or_default(),
                    item.get::<String>("rarity").unwrap_or_default(),
                ),
                Err(_) => {
                    empty_slots.push(slot);
                    continue;
                }
            };

            filled_slots.push(serde_json::json!({
                "slot": slot,
                "item": name,
                "rarity": rarity,
            }));
        }

        Ok(serde_json::json!({
            "empty_slots": empty_slots,
            "filled_slots": filled_slots,
            "total_empty": empty_slots.len(),
            "total_filled": filled_slots.len(),
        }))
    }

    /// Query a jewel socketed in a passive tree socket node.
    ///
    /// Returns a JSON object with the jewel's name, base type, rarity, quality,
    /// and all mod lines. If the socket is empty or invalid, returns
    /// `{ "socket_id": N, "empty": true }`.
    pub fn query_jewel(&self, socket_id: i64) -> Result<serde_json::Value, PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }

        let build: mlua::Table = self.lua.globals().get("build")?;
        let spec: mlua::Table = build.get("spec")?;

        // build.spec.jewels[socketNodeId] → itemId
        let jewels: mlua::Table = match spec.get::<mlua::Table>("jewels") {
            Ok(t) => t,
            Err(_) => return Ok(serde_json::json!({ "socket_id": socket_id, "empty": true })),
        };

        let item_id: i64 = match jewels.get::<i64>(socket_id) {
            Ok(id) if id != 0 => id,
            _ => return Ok(serde_json::json!({ "socket_id": socket_id, "empty": true })),
        };

        // build.itemsTab.items[itemId] → jewel item object
        let items_tab: mlua::Table = build.get("itemsTab")?;
        let items: mlua::Table = items_tab.get("items")?;
        let item: mlua::Table = match items.get::<mlua::Table>(item_id) {
            Ok(t) => t,
            Err(_) => return Ok(serde_json::json!({ "socket_id": socket_id, "empty": true })),
        };

        let name = item.get::<String>("name").unwrap_or_default();
        let base_name = item
            .get::<mlua::Table>("base")
            .and_then(|b| b.get::<String>("name"))
            .unwrap_or_default();
        let rarity = item.get::<String>("rarity").unwrap_or_default();
        let quality = item.get::<i64>("quality").unwrap_or(0);

        let implicits = read_mod_lines(&item, "implicitModLines");
        let explicits = read_mod_lines(&item, "explicitModLines");
        let enchants = read_mod_lines(&item, "enchantModLines");
        let runes = read_mod_lines(&item, "runeModLines");

        Ok(serde_json::json!({
            "socket_id": socket_id,
            "name": name,
            "base": base_name,
            "rarity": rarity,
            "quality": quality,
            "implicits": implicits,
            "explicits": explicits,
            "enchants": enchants,
            "runes": runes,
        }))
    }

    /// Query the allocated passive tree nodes.
    ///
    /// Returns class, ascendancy, total node count, and categorized node lists:
    /// keystones, notables, ascendancy nodes, masteries, and jewel sockets.
    pub fn query_passive_tree(&self) -> Result<serde_json::Value, PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }

        let build: mlua::Table = self.lua.globals().get("build")?;
        let spec: mlua::Table = build.get("spec")?;

        let class_name = spec.get::<String>("curClassName").unwrap_or_default();
        let ascendancy_name = spec.get::<String>("curAscendClassName").unwrap_or_default();

        let alloc_nodes: mlua::Table = spec.get("allocNodes")?;

        let mut keystones = Vec::new();
        let mut notables = Vec::new();
        let mut ascendancy_nodes = Vec::new();
        let mut masteries = Vec::new();
        let mut jewel_sockets = Vec::new();
        let mut total_allocated: u32 = 0;

        for pair in alloc_nodes.pairs::<mlua::Value, mlua::Table>() {
            let (key, node) = pair?;
            total_allocated += 1;

            let node_type = node.get::<String>("type").unwrap_or_default();
            let name = node.get::<String>("dn").unwrap_or_default();
            let asc_name: Option<String> = node.get::<String>("ascendancyName").ok();

            // Ascendancy nodes go into their own bucket regardless of type
            if asc_name.is_some() {
                let stats = read_node_stats(&node);
                let mut entry = serde_json::json!({
                    "name": name,
                    "type": node_type,
                });
                if !stats.is_empty() {
                    entry["stats"] = serde_json::Value::Array(
                        stats.into_iter().map(serde_json::Value::String).collect(),
                    );
                }
                ascendancy_nodes.push(entry);
                continue;
            }

            match node_type.as_str() {
                "Keystone" => {
                    let stats = read_node_stats(&node);
                    let mut entry = serde_json::json!({ "name": name });
                    if !stats.is_empty() {
                        entry["stats"] = serde_json::Value::Array(
                            stats.into_iter().map(serde_json::Value::String).collect(),
                        );
                    }
                    keystones.push(entry);
                }
                "Notable" => {
                    let stats = read_node_stats(&node);
                    let mut entry = serde_json::json!({ "name": name });
                    if !stats.is_empty() {
                        entry["stats"] = serde_json::Value::Array(
                            stats.into_iter().map(serde_json::Value::String).collect(),
                        );
                    }
                    notables.push(entry);
                }
                "Mastery" => {
                    let stats = read_node_stats(&node);
                    let mut entry = serde_json::json!({ "name": name });
                    if !stats.is_empty() {
                        entry["stats"] = serde_json::Value::Array(
                            stats.into_iter().map(serde_json::Value::String).collect(),
                        );
                    }
                    masteries.push(entry);
                }
                "Socket" => {
                    let node_id = lua_value_to_i64(&key).unwrap_or(0);
                    jewel_sockets.push(serde_json::json!({
                        "node_id": node_id,
                        "name": name,
                    }));
                }
                // Normal, ClassStart, AscendClassStart — counted but not listed
                _ => {}
            }
        }

        Ok(serde_json::json!({
            "class": class_name,
            "ascendancy": ascendancy_name,
            "total_allocated": total_allocated,
            "keystones": keystones,
            "notables": notables,
            "ascendancy_nodes": ascendancy_nodes,
            "masteries": masteries,
            "jewel_sockets": jewel_sockets,
        }))
    }

    /// Query how much of a stat comes from allocated passives and what's nearby.
    ///
    /// Performs case-insensitive substring matching on passive node stat descriptions.
    /// Uses multi-source BFS from allocated nodes to find nearby unallocated nodes
    /// with matching stats within `radius` hops.
    pub fn query_passive_stats(
        &self,
        stat: &str,
        radius: u32,
    ) -> Result<serde_json::Value, PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }

        let pattern = stat.to_lowercase();
        let build: mlua::Table = self.lua.globals().get("build")?;
        let spec: mlua::Table = build.get("spec")?;
        let alloc_nodes: mlua::Table = spec.get("allocNodes")?;
        let all_nodes: mlua::Table = spec.get("nodes")?;

        // Phase A: Collect allocated node IDs and find matching stats
        let mut allocated_ids = HashSet::new();
        let mut allocated_nodes = Vec::new();
        let mut allocated_total: f64 = 0.0;

        for pair in alloc_nodes.pairs::<mlua::Value, mlua::Table>() {
            let (key, node) = pair?;
            let node_id = lua_value_to_i64(&key).unwrap_or(0);
            allocated_ids.insert(node_id);

            let (matching_stats, value) = match_node_stats(&node, &pattern);
            if !matching_stats.is_empty() {
                let name = node.get::<String>("dn").unwrap_or_default();
                allocated_total += value;
                allocated_nodes.push(serde_json::json!({
                    "name": name,
                    "value": value,
                    "matching_stats": matching_stats,
                }));
            }
        }

        // Phase B: Build adjacency graph from all nodes
        let mut adjacency: HashMap<i64, Vec<i64>> = HashMap::new();

        for pair in all_nodes.pairs::<mlua::Value, mlua::Table>() {
            let (key, node) = pair?;
            let node_id = lua_value_to_i64(&key).unwrap_or(0);

            let mut neighbors = Vec::new();
            if let Ok(linked_ids) = node.get::<mlua::Table>("linkedId") {
                for i in 1..=linked_ids.raw_len() {
                    if let Ok(linked_id) = linked_ids.get::<i64>(i) {
                        neighbors.push(linked_id);
                    }
                }
            }
            adjacency.insert(node_id, neighbors);
        }

        // Phase C: Multi-source BFS from allocated nodes
        let mut visited = allocated_ids.clone();
        let mut queue = VecDeque::new();

        for &id in &allocated_ids {
            queue.push_back((id, 0u32));
        }

        let mut nearby_nodes = Vec::new();
        let mut nearby_total: f64 = 0.0;

        while let Some((current_id, dist)) = queue.pop_front() {
            if let Some(neighbors) = adjacency.get(&current_id) {
                for &neighbor_id in neighbors {
                    if visited.contains(&neighbor_id) {
                        continue;
                    }
                    visited.insert(neighbor_id);

                    let next_dist = dist + 1;

                    // Check this unallocated node for matching stats
                    if let Ok(node) = all_nodes.get::<mlua::Table>(neighbor_id) {
                        let (matching_stats, value) = match_node_stats(&node, &pattern);
                        if !matching_stats.is_empty() {
                            let name = node.get::<String>("dn").unwrap_or_default();
                            nearby_total += value;
                            nearby_nodes.push(serde_json::json!({
                                "name": name,
                                "value": value,
                                "distance": next_dist,
                                "matching_stats": matching_stats,
                            }));
                        }
                    }

                    if next_dist < radius {
                        queue.push_back((neighbor_id, next_dist));
                    }
                }
            }
        }

        // Sort nearby nodes by distance, then by value descending
        nearby_nodes.sort_by(|a, b| {
            let da = a["distance"].as_u64().unwrap_or(0);
            let db = b["distance"].as_u64().unwrap_or(0);
            da.cmp(&db).then_with(|| {
                let va = b["value"].as_f64().unwrap_or(0.0);
                let vb = a["value"].as_f64().unwrap_or(0.0);
                va.partial_cmp(&vb).unwrap_or(std::cmp::Ordering::Equal)
            })
        });

        Ok(serde_json::json!({
            "stat": stat,
            "allocated": {
                "total_value": allocated_total,
                "nodes": allocated_nodes,
            },
            "nearby_available": {
                "total_value": nearby_total,
                "nodes": nearby_nodes,
            },
        }))
    }

    /// Query ascendancy nodes: which are allocated and which are available.
    ///
    /// Returns primary and secondary ascendancy names, lists of allocated and
    /// available nodes with stats, and point counts for each ascendancy.
    pub fn query_unallocated_ascendancy(&self) -> Result<serde_json::Value, PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }

        let build: mlua::Table = self.lua.globals().get("build")?;
        let spec: mlua::Table = build.get("spec")?;
        let tree: mlua::Table = spec.get("tree")?;

        // Read ascendancy class names
        let primary_name = spec
            .get::<String>("curAscendClassName")
            .unwrap_or_else(|_| "None".to_owned());
        let secondary_name = spec
            .get::<String>("curSecondaryAscendClassName")
            .unwrap_or_else(|_| "None".to_owned());

        // Build set of secondary ascendancy names for classification
        let secondary_asc_names: HashSet<String> =
            if let Ok(map) = tree.get::<mlua::Table>("secondaryAscendNameMap") {
                map.pairs::<String, mlua::Value>()
                    .filter_map(|pair| pair.ok().map(|(k, _)| k))
                    .collect()
            } else {
                HashSet::new()
            };

        // Collect allocated node IDs for fast lookup
        let alloc_nodes: mlua::Table = spec.get("allocNodes")?;
        let mut allocated_ids = HashSet::new();
        for pair in alloc_nodes.pairs::<mlua::Value, mlua::Table>() {
            let (key, _) = pair?;
            if let Some(id) = lua_value_to_i64(&key) {
                allocated_ids.insert(id);
            }
        }

        // Determine which ascendancy names belong to this build
        let has_primary = primary_name != "None" && !primary_name.is_empty();
        let has_secondary = secondary_name != "None" && !secondary_name.is_empty();

        let mut primary_allocated = Vec::new();
        let mut primary_available = Vec::new();
        let mut secondary_allocated = Vec::new();
        let mut secondary_available = Vec::new();
        let mut primary_points_spent: u32 = 0;
        let mut secondary_points_spent: u32 = 0;

        // Iterate all nodes, filter for ascendancy nodes belonging to this build
        let all_nodes: mlua::Table = spec.get("nodes")?;
        for pair in all_nodes.pairs::<mlua::Value, mlua::Table>() {
            let (key, node) = pair?;
            let node_id = lua_value_to_i64(&key).unwrap_or(0);

            let asc_name = match node.get::<String>("ascendancyName") {
                Ok(name) => name,
                Err(_) => continue, // Not an ascendancy node
            };

            // Skip nodes that don't belong to this build's ascendancies
            let is_secondary = secondary_asc_names.contains(&asc_name);
            let belongs = if is_secondary {
                has_secondary && asc_name == secondary_name
            } else {
                has_primary && asc_name == primary_name
            };
            if !belongs {
                continue;
            }

            // Skip start nodes — they're auto-allocated and don't cost points
            let node_type = node.get::<String>("type").unwrap_or_default();
            if node_type == "AscendClassStart" {
                continue;
            }

            let name = node.get::<String>("dn").unwrap_or_default();
            let stats = read_node_stats(&node);
            let is_multiple_choice_option = node
                .get::<bool>("isMultipleChoiceOption")
                .unwrap_or(false);

            let entry = {
                let mut e = serde_json::json!({
                    "name": name,
                    "type": node_type,
                });
                if !stats.is_empty() {
                    e["stats"] = serde_json::Value::Array(
                        stats.into_iter().map(serde_json::Value::String).collect(),
                    );
                }
                e
            };

            let is_allocated = allocated_ids.contains(&node_id);

            if is_secondary {
                if is_allocated {
                    secondary_allocated.push(entry);
                    if !is_multiple_choice_option {
                        secondary_points_spent += 1;
                    }
                } else {
                    secondary_available.push(entry);
                }
            } else {
                if is_allocated {
                    primary_allocated.push(entry);
                    if !is_multiple_choice_option {
                        primary_points_spent += 1;
                    }
                } else {
                    primary_available.push(entry);
                }
            }
        }

        let mut result = serde_json::json!({
            "primary_ascendancy": primary_name,
            "primary_allocated": primary_allocated,
            "primary_available": primary_available,
            "primary_points_spent": primary_points_spent,
        });

        if has_secondary {
            result["secondary_ascendancy"] = serde_json::Value::String(secondary_name);
            result["secondary_allocated"] = serde_json::Value::Array(secondary_allocated);
            result["secondary_available"] = serde_json::Value::Array(secondary_available);
            result["secondary_points_spent"] = serde_json::json!(secondary_points_spent);
        }

        Ok(result)
    }

    /// Run a closure with CWD set to the PoB `src/` directory,
    /// restoring the original CWD afterwards.
    fn with_pob_cwd<F, R>(&self, f: F) -> Result<R, PobError>
    where
        F: FnOnce(&Lua) -> LuaResult<R>,
    {
        let pob_src = self
            .pob_src_path
            .as_ref()
            .ok_or(PobError::NotInitialized)?;
        let original_cwd = std::env::current_dir()?;
        std::env::set_current_dir(pob_src)?;
        let result = f(&self.lua);
        std::env::set_current_dir(original_cwd)?;
        Ok(result?)
    }

    /// Export current build to PoB code.
    pub fn export_build(&self) -> Result<String, PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }

        // TODO: Generate PoB export code
        Ok(String::new())
    }

    /// Modify the passive tree.
    pub fn set_passive_tree(&self, _tree_data: &str) -> Result<(), PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }
        // TODO: Update passive tree in PoB
        Ok(())
    }

    /// Set the main skill.
    pub fn set_main_skill(&self, _skill_name: &str) -> Result<(), PobError> {
        if !self.initialized {
            return Err(PobError::NotInitialized);
        }
        // TODO: Set main skill in PoB
        Ok(())
    }
}

impl Default for PobHeadless {
    fn default() -> Self {
        Self::new().expect("Failed to create Lua runtime")
    }
}

// SAFETY: PobHeadless is !Send because mlua::Lua with LuaJIT is !Send.
// PobParser handles this by pinning it to a dedicated OS thread.

/// Read numeric fields from a Lua table into a JSON map.
/// Tries f64 first, then i64, skipping nil/missing values.
fn read_fields(table: &mlua::Table, fields: &[&str]) -> serde_json::Map<String, serde_json::Value> {
    let mut map = serde_json::Map::new();
    for &field in fields {
        if let Ok(v) = table.get::<f64>(field) {
            if v != 0.0 {
                if let Some(num) = serde_json::Number::from_f64(v) {
                    map.insert(field.to_owned(), serde_json::Value::Number(num));
                }
            }
        } else if let Ok(v) = table.get::<i64>(field) {
            if v != 0 {
                map.insert(
                    field.to_owned(),
                    serde_json::Value::Number(v.into()),
                );
            }
        }
    }
    map
}

/// Read mod line strings from an item's mod array (e.g. `explicitModLines`).
///
/// Each entry in the Lua array is a table with a `line` field.
/// Returns an empty vec if the field is missing or has no entries.
fn read_mod_lines(item: &mlua::Table, field: &str) -> Vec<String> {
    let table = match item.get::<mlua::Table>(field) {
        Ok(t) => t,
        Err(_) => return Vec::new(),
    };
    (1..=table.raw_len())
        .filter_map(|i| table.get::<mlua::Table>(i).ok())
        .filter_map(|entry| entry.get::<String>("line").ok())
        .collect()
}

/// Merge entries from `src` into `dst`, preferring values already in `dst`.
fn merge_fields(
    dst: &mut serde_json::Map<String, serde_json::Value>,
    src: &serde_json::Map<String, serde_json::Value>,
) {
    for (key, value) in src {
        dst.entry(key.clone()).or_insert_with(|| value.clone());
    }
}

/// Read the `sd` (stat description) array from a passive tree node table.
///
/// Returns an empty vec if the field is missing or has no entries.
fn read_node_stats(node: &mlua::Table) -> Vec<String> {
    let table = match node.get::<mlua::Table>("sd") {
        Ok(t) => t,
        Err(_) => return Vec::new(),
    };
    (1..=table.raw_len())
        .filter_map(|i| table.get::<String>(i).ok())
        .collect()
}

/// Extract an i64 from a Lua value (Integer or Number).
fn lua_value_to_i64(val: &mlua::Value) -> Option<i64> {
    match val {
        mlua::Value::Integer(n) => Some(*n),
        mlua::Value::Number(n) => Some(*n as i64),
        _ => None,
    }
}

/// Check a node's `sd` lines for case-insensitive substring matches against `pattern`.
///
/// Returns the matching stat line strings and the sum of extracted numeric values.
fn match_node_stats(node: &mlua::Table, pattern: &str) -> (Vec<String>, f64) {
    let sd = match node.get::<mlua::Table>("sd") {
        Ok(t) => t,
        Err(_) => return (Vec::new(), 0.0),
    };

    let mut matching = Vec::new();
    let mut total = 0.0;

    for i in 1..=sd.raw_len() {
        if let Ok(line) = sd.get::<String>(i) {
            if line.to_lowercase().contains(pattern) {
                total += extract_stat_value(&line);
                matching.push(line);
            }
        }
    }

    (matching, total)
}

/// Extract the first numeric value from a stat description line.
///
/// Handles integers and decimals, e.g. "+25% increased Fire Damage" → 25.0,
/// "0.5% of Fire Damage Leeched as Life" → 0.5. Returns 0.0 if no number found.
fn extract_stat_value(line: &str) -> f64 {
    let mut start = None;
    let mut has_dot = false;

    for (i, ch) in line.char_indices() {
        match ch {
            '0'..='9' => {
                if start.is_none() {
                    start = Some(i);
                }
            }
            '.' if start.is_some() && !has_dot => {
                has_dot = true;
            }
            _ => {
                if let Some(s) = start {
                    if let Ok(val) = line[s..i].parse::<f64>() {
                        return val;
                    }
                    start = None;
                    has_dot = false;
                }
            }
        }
    }

    // Check if the number extends to end of string
    if let Some(s) = start {
        line[s..].parse::<f64>().unwrap_or(0.0)
    } else {
        0.0
    }
}