poe2-agent 0.2.0

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
//! 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::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 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,
        }))
    }

    /// 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,
    }
}