poe2-agent 0.5.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
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
//! PoE2 Trade API client with rate limiting and stat resolution.
//!
//! Provides [`TradeClient`] for searching items and checking currency exchange
//! rates on the official Path of Exile 2 trade site.

use std::collections::HashMap;
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};
use tokio::sync::{Mutex, OnceCell};
use tracing::{debug, warn};

const BASE_URL: &str = "https://www.pathofexile.com";
const USER_AGENT: &str = "OAuth poe2-agent/0.4.0 (contact: github.com/SFerenczy/poe2-agent)";

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Errors from the trade API.
#[derive(Debug, thiserror::Error)]
pub enum TradeError {
    #[error("HTTP error: {0}")]
    Http(#[from] reqwest::Error),

    #[error("rate limited — retry after {0:?}")]
    RateLimited(Duration),

    #[error("API error {code}: {message}")]
    Api { code: u64, message: String },

    #[error("failed to parse response JSON: {0}")]
    Parse(#[from] serde_json::Error),

    #[error("no results found")]
    NoResults,
}

// ---------------------------------------------------------------------------
// Response types
// ---------------------------------------------------------------------------

/// Response from `POST /api/trade2/search/poe2/{league}`.
#[derive(Debug, Deserialize)]
pub struct SearchResponse {
    #[serde(default)]
    pub id: Option<String>,
    #[serde(default)]
    pub total: u64,
    #[serde(default)]
    pub result: Vec<String>,
    #[serde(default)]
    pub error: Option<ApiError>,
}

/// Response from `GET /api/trade2/fetch/{hashes}?query={id}`.
#[derive(Debug, Deserialize)]
pub struct FetchResponse {
    #[serde(default)]
    pub result: Vec<FetchedItem>,
}

/// A single item from a fetch response.
#[derive(Debug, Deserialize)]
pub struct FetchedItem {
    #[serde(default)]
    pub listing: Listing,
    #[serde(default)]
    pub item: ItemInfo,
}

#[derive(Debug, Default, Deserialize)]
pub struct Listing {
    #[serde(default)]
    pub price: Option<Price>,
}

#[derive(Debug, Deserialize)]
pub struct Price {
    #[serde(default)]
    pub amount: f64,
    #[serde(default)]
    pub currency: String,
}

#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ItemInfo {
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub type_line: String,
    #[serde(default)]
    pub base_type: String,
    #[serde(default)]
    pub ilvl: u32,
    #[serde(default)]
    pub frame_type: u8,
    #[serde(default)]
    pub explicit_mods: Vec<String>,
    #[serde(default)]
    pub implicit_mods: Vec<String>,
}

impl ItemInfo {
    /// Map `frameType` to a human-readable rarity string.
    pub fn rarity(&self) -> &'static str {
        match self.frame_type {
            0 => "Normal",
            1 => "Magic",
            2 => "Rare",
            3 => "Unique",
            _ => "Unknown",
        }
    }

    /// Display name: for uniques "Name TypeLine", for others just the typeLine.
    pub fn display_name(&self) -> String {
        if self.name.is_empty() {
            self.type_line.clone()
        } else {
            format!("{} {}", self.name, self.type_line)
        }
    }
}

/// Exchange endpoint response.
#[derive(Debug, Deserialize)]
pub struct ExchangeResponse {
    #[serde(default)]
    pub result: HashMap<String, ExchangeEntry>,
    #[serde(default)]
    pub total: u64,
    #[serde(default)]
    pub error: Option<ApiError>,
}

#[derive(Debug, Deserialize)]
pub struct ExchangeEntry {
    #[serde(default)]
    pub listing: ExchangeListing,
}

#[derive(Debug, Default, Deserialize)]
pub struct ExchangeListing {
    #[serde(default)]
    pub offers: Vec<ExchangeOffer>,
}

#[derive(Debug, Deserialize)]
pub struct ExchangeOffer {
    #[serde(default)]
    pub exchange: ExchangeSide,
    #[serde(default)]
    pub item: ExchangeItemSide,
}

#[derive(Debug, Default, Deserialize)]
pub struct ExchangeSide {
    #[serde(default)]
    pub currency: String,
    #[serde(default)]
    pub amount: f64,
}

#[derive(Debug, Default, Deserialize)]
pub struct ExchangeItemSide {
    #[serde(default)]
    pub currency: String,
    #[serde(default)]
    pub amount: f64,
    #[serde(default)]
    pub stock: u64,
}

/// API error body.
#[derive(Debug, Deserialize)]
pub struct ApiError {
    #[serde(default)]
    pub code: u64,
    #[serde(default)]
    pub message: String,
}

/// League entry from `/data/leagues`.
#[derive(Debug, Deserialize)]
pub struct LeagueEntry {
    pub id: String,
    #[serde(default)]
    pub realm: String,
    #[serde(default)]
    pub text: String,
}

/// Stat group from `/data/stats`.
#[derive(Debug, Clone, Deserialize)]
pub struct StatGroup {
    #[serde(default)]
    pub label: String,
    #[serde(default)]
    pub entries: Vec<StatEntry>,
}

/// Individual stat entry.
#[derive(Debug, Clone, Deserialize)]
pub struct StatEntry {
    pub id: String,
    pub text: String,
    #[serde(rename = "type", default)]
    pub stat_type: String,
}

/// Resolved stat filter for building search queries.
#[derive(Debug, Clone, Serialize)]
pub struct StatFilter {
    pub id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<StatFilterValue>,
}

#[derive(Debug, Clone, Serialize)]
pub struct StatFilterValue {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max: Option<f64>,
}

// ---------------------------------------------------------------------------
// Rate limit tracking
// ---------------------------------------------------------------------------

/// Tracks rate limit state for a single policy (e.g. search, fetch, exchange).
#[derive(Debug)]
pub struct RateLimitTracker {
    windows: Vec<RateLimitWindow>,
    last_updated: Instant,
}

#[derive(Debug, Clone)]
struct RateLimitWindow {
    max_hits: u64,
    /// Period length and penalty duration stored for diagnostics/logging.
    #[allow(dead_code)]
    period_secs: u64,
    #[allow(dead_code)]
    penalty_secs: u64,
    current_hits: u64,
    current_period: u64,
    penalty_remaining: u64,
}

impl RateLimitTracker {
    fn new() -> Self {
        Self {
            windows: Vec::new(),
            last_updated: Instant::now(),
        }
    }

    /// Parse the limit definition header (e.g. `5:10:60,15:60:300`).
    fn parse_limits(header: &str) -> Vec<(u64, u64, u64)> {
        header
            .split(',')
            .filter_map(|w| {
                let parts: Vec<&str> = w.trim().split(':').collect();
                if parts.len() == 3 {
                    Some((
                        parts[0].parse().ok()?,
                        parts[1].parse().ok()?,
                        parts[2].parse().ok()?,
                    ))
                } else {
                    None
                }
            })
            .collect()
    }

    /// Parse the state header (e.g. `1:10:0,3:60:0`).
    fn parse_state(header: &str) -> Vec<(u64, u64, u64)> {
        // Same format: current:period:penalty_remaining
        Self::parse_limits(header)
    }

    /// Update tracker state from response headers.
    fn update_from_headers(&mut self, limits_header: &str, state_header: &str) {
        let limits = Self::parse_limits(limits_header);
        let states = Self::parse_state(state_header);

        self.windows.clear();
        for (i, (max_hits, period, penalty)) in limits.iter().enumerate() {
            let (current, current_period, penalty_remaining) =
                states.get(i).copied().unwrap_or((0, *period, 0));
            self.windows.push(RateLimitWindow {
                max_hits: *max_hits,
                period_secs: *period,
                penalty_secs: *penalty,
                current_hits: current,
                current_period,
                penalty_remaining,
            });
        }
        self.last_updated = Instant::now();
    }

    /// Check if we need to wait before making a request.
    /// Returns `Some(duration)` if we should sleep first.
    fn check_wait(&self) -> Option<Duration> {
        let mut max_wait = Duration::ZERO;

        for w in &self.windows {
            // If there's an active penalty, wait it out.
            if w.penalty_remaining > 0 {
                let penalty = Duration::from_secs(w.penalty_remaining);
                if penalty > max_wait {
                    max_wait = penalty;
                }
                continue;
            }

            // If we're at (max - 1), leave a 1-request buffer but still allow.
            // If we're at max, we need to wait for the window to roll over.
            if w.current_hits >= w.max_hits {
                // Estimate time remaining in the window based on when we last updated.
                let elapsed = self.last_updated.elapsed();
                let window_duration = Duration::from_secs(w.current_period);
                if elapsed < window_duration {
                    let remaining = window_duration - elapsed;
                    if remaining > max_wait {
                        max_wait = remaining;
                    }
                }
            }
        }

        if max_wait > Duration::ZERO {
            Some(max_wait)
        } else {
            None
        }
    }
}

/// Parse rate limit headers from a response and update the appropriate tracker.
fn update_rate_limits(
    rate_limiters: &mut HashMap<String, RateLimitTracker>,
    headers: &reqwest::header::HeaderMap,
) {
    let policy = match headers
        .get("x-rate-limit-policy")
        .and_then(|v| v.to_str().ok())
    {
        Some(p) => p.to_string(),
        None => return,
    };

    let rules = match headers
        .get("x-rate-limit-rules")
        .and_then(|v| v.to_str().ok())
    {
        Some(r) => r.to_string(),
        None => return,
    };

    let tracker = rate_limiters
        .entry(policy.clone())
        .or_insert_with(RateLimitTracker::new);

    // Parse each rule's limits and state.
    for rule in rules.split(',') {
        let rule = rule.trim();
        let limits_key = format!("x-rate-limit-{}", rule.to_lowercase());
        let state_key = format!("x-rate-limit-{}-state", rule.to_lowercase());

        let limits = headers
            .get(limits_key.as_str())
            .and_then(|v| v.to_str().ok());
        let state = headers
            .get(state_key.as_str())
            .and_then(|v| v.to_str().ok());

        if let (Some(l), Some(s)) = (limits, state) {
            tracker.update_from_headers(l, s);
        }
    }
}

// ---------------------------------------------------------------------------
// Search parameters
// ---------------------------------------------------------------------------

/// Parameters for an item search.
pub struct SearchParams {
    pub name: Option<String>,
    pub item_type: Option<String>,
    pub category: Option<String>,
    pub rarity: Option<String>,
    pub stats: Vec<(String, Option<f64>, Option<f64>)>,
    pub max_price: Option<(f64, String)>,
    pub league: Option<String>,
}

// ---------------------------------------------------------------------------
// Trade client
// ---------------------------------------------------------------------------

/// Client for the PoE2 trade API.
///
/// Handles rate limiting, stat ID resolution, and compact response formatting.
pub struct TradeClient {
    http: reqwest::Client,
    base_url: String,
    rate_limiters: Mutex<HashMap<String, RateLimitTracker>>,
    stats_cache: OnceCell<Vec<StatGroup>>,
    default_league: OnceCell<String>,
}

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

impl TradeClient {
    /// Create a new trade client with the required User-Agent header.
    pub fn new() -> Self {
        Self::new_with_base_url(BASE_URL)
    }

    /// Create a trade client pointing at a custom base URL (for testing).
    pub fn new_with_base_url(base_url: &str) -> Self {
        let http = reqwest::Client::builder()
            .user_agent(USER_AGENT)
            .build()
            .expect("failed to build HTTP client");

        Self {
            http,
            base_url: base_url.trim_end_matches('/').to_string(),
            rate_limiters: Mutex::new(HashMap::new()),
            stats_cache: OnceCell::new(),
            default_league: OnceCell::new(),
        }
    }

    // -----------------------------------------------------------------------
    // Internal: rate-limit-aware request
    // -----------------------------------------------------------------------

    /// Wait if the given policy's rate limit requires it.
    async fn wait_for_rate_limit(&self, policy: &str) {
        let limiters = self.rate_limiters.lock().await;
        if let Some(tracker) = limiters.get(policy) {
            if let Some(wait) = tracker.check_wait() {
                drop(limiters); // release lock before sleeping
                warn!(policy, ?wait, "rate limit — sleeping before request");
                tokio::time::sleep(wait).await;
            }
        }
    }

    /// After a response, update the rate limiter from headers.
    async fn record_rate_limits(&self, headers: &reqwest::header::HeaderMap) {
        let mut limiters = self.rate_limiters.lock().await;
        update_rate_limits(&mut limiters, headers);
    }

    /// Deserialize a response as JSON, logging the raw body on failure.
    async fn parse_response<T: serde::de::DeserializeOwned>(
        resp: reqwest::Response,
    ) -> Result<T, TradeError> {
        let status = resp.status();
        let body = resp.text().await?;
        debug!(status = %status, body_len = body.len(), "trade API response");
        serde_json::from_str(&body).map_err(|e| {
            warn!(
                status = %status,
                body = %body.chars().take(2000).collect::<String>(),
                "failed to parse trade API response"
            );
            TradeError::Parse(e)
        })
    }

    /// Perform a GET request with rate limit handling.
    async fn rate_limited_get(
        &self,
        url: &str,
        policy: &str,
    ) -> Result<reqwest::Response, TradeError> {
        self.wait_for_rate_limit(policy).await;
        debug!(url, "GET");

        let resp = self.http.get(url).send().await?;
        self.record_rate_limits(resp.headers()).await;

        if resp.status() == reqwest::StatusCode::TOO_MANY_REQUESTS {
            // Try to parse retry-after from headers.
            let retry_secs = resp
                .headers()
                .get("retry-after")
                .and_then(|v| v.to_str().ok())
                .and_then(|v| v.parse::<u64>().ok())
                .unwrap_or(60);
            return Err(TradeError::RateLimited(Duration::from_secs(retry_secs)));
        }

        Ok(resp)
    }

    /// Perform a POST request with rate limit handling.
    async fn rate_limited_post(
        &self,
        url: &str,
        body: &serde_json::Value,
        policy: &str,
    ) -> Result<reqwest::Response, TradeError> {
        self.wait_for_rate_limit(policy).await;
        debug!(url, "POST");

        let resp = self.http.post(url).json(body).send().await?;
        self.record_rate_limits(resp.headers()).await;

        if resp.status() == reqwest::StatusCode::TOO_MANY_REQUESTS {
            let retry_secs = resp
                .headers()
                .get("retry-after")
                .and_then(|v| v.to_str().ok())
                .and_then(|v| v.parse::<u64>().ok())
                .unwrap_or(60);
            return Err(TradeError::RateLimited(Duration::from_secs(retry_secs)));
        }

        Ok(resp)
    }

    // -----------------------------------------------------------------------
    // League resolution
    // -----------------------------------------------------------------------

    /// Resolve the league to use: provided value, or fetch the default.
    async fn resolve_league(&self, league: Option<&str>) -> Result<String, TradeError> {
        if let Some(l) = league {
            return Ok(l.to_string());
        }

        let base_url = &self.base_url;
        self.default_league
            .get_or_try_init(|| async {
                let url = format!("{base_url}/api/trade2/data/leagues");
                debug!("fetching league list");
                let resp = self.http.get(&url).send().await?;
                let data: serde_json::Value = resp.json().await?;

                // Find first non-HC, non-Standard league from poe2 realm.
                let leagues: Vec<LeagueEntry> =
                    serde_json::from_value(data["result"].clone()).unwrap_or_default();

                for league in &leagues {
                    if league.realm == "poe2"
                        && !league.id.starts_with("HC")
                        && league.id != "Standard"
                        && league.id != "Hardcore"
                    {
                        debug!(league = %league.id, "resolved default league");
                        return Ok(league.id.clone());
                    }
                }

                // Fallback to Standard.
                debug!("no challenge league found, falling back to Standard");
                Ok("Standard".to_string())
            })
            .await
            .cloned()
    }

    // -----------------------------------------------------------------------
    // Stat resolution
    // -----------------------------------------------------------------------

    /// Fetch and cache the stat data from the API.
    async fn fetch_stats(&self) -> Result<&Vec<StatGroup>, TradeError> {
        let base_url = &self.base_url;
        self.stats_cache
            .get_or_try_init(|| async {
                let url = format!("{base_url}/api/trade2/data/stats");
                debug!("fetching stat data");
                let resp = self.http.get(&url).send().await?;
                let data: serde_json::Value = resp.json().await?;
                let groups: Vec<StatGroup> =
                    serde_json::from_value(data["result"].clone()).unwrap_or_default();
                debug!(groups = groups.len(), "stat data loaded");
                Ok(groups)
            })
            .await
    }

    /// Resolve human-readable stat names to stat filter IDs.
    ///
    /// Uses case-insensitive substring matching. Prefers pseudo stats when
    /// available (e.g. "maximum life" matches `pseudo.pseudo_total_life`).
    async fn resolve_stat_ids(
        &self,
        stat_names: &[(String, Option<f64>, Option<f64>)],
    ) -> Result<Vec<StatFilter>, TradeError> {
        let groups = self.fetch_stats().await?;
        let mut filters = Vec::new();

        for (name, min, max) in stat_names {
            let needle = name.to_lowercase();
            let mut best_match: Option<&StatEntry> = None;
            let mut best_is_pseudo = false;

            for group in groups {
                for entry in &group.entries {
                    let haystack = entry.text.to_lowercase();
                    if haystack.contains(&needle) {
                        let is_pseudo = entry.id.starts_with("pseudo.");
                        // Prefer pseudo stats over explicit/implicit.
                        if best_match.is_none()
                            || (is_pseudo && !best_is_pseudo)
                            || (is_pseudo == best_is_pseudo
                                && haystack.len() < best_match.unwrap().text.len())
                        {
                            best_match = Some(entry);
                            best_is_pseudo = is_pseudo;
                        }
                    }
                }
            }

            if let Some(entry) = best_match {
                debug!(name, id = %entry.id, "resolved stat");
                let value = if min.is_some() || max.is_some() {
                    Some(StatFilterValue {
                        min: *min,
                        max: *max,
                    })
                } else {
                    None
                };
                filters.push(StatFilter {
                    id: entry.id.clone(),
                    value,
                });
            } else {
                warn!(name, "could not resolve stat ID — skipping");
            }
        }

        Ok(filters)
    }

    // -----------------------------------------------------------------------
    // Search
    // -----------------------------------------------------------------------

    /// Search for items on the trade site.
    ///
    /// Builds a query from `params`, posts to the search endpoint, fetches up
    /// to 10 results, and returns a compact JSON summary.
    pub async fn search(&self, params: SearchParams) -> Result<serde_json::Value, TradeError> {
        let base_url = &self.base_url;
        let league = self.resolve_league(params.league.as_deref()).await?;

        // Resolve stat names to IDs.
        let stat_filters = if !params.stats.is_empty() {
            self.resolve_stat_ids(&params.stats).await?
        } else {
            Vec::new()
        };

        // Build query JSON.
        let mut query = serde_json::json!({
            "status": {"option": "available"}
        });

        if let Some(ref name) = params.name {
            query["name"] = serde_json::json!(name);
        }
        if let Some(ref item_type) = params.item_type {
            query["type"] = serde_json::json!(item_type);
        }

        // Type filters (category, rarity).
        let mut type_filters = serde_json::Map::new();
        if let Some(ref category) = params.category {
            type_filters.insert(
                "category".to_string(),
                serde_json::json!({"option": category}),
            );
        }
        if let Some(ref rarity) = params.rarity {
            type_filters.insert("rarity".to_string(), serde_json::json!({"option": rarity}));
        }
        if !type_filters.is_empty() {
            query["filters"] = serde_json::json!({
                "type_filters": {
                    "filters": type_filters
                }
            });
        }

        // Trade filters (max price).
        if let Some((amount, ref currency)) = params.max_price {
            let trade_filter = serde_json::json!({
                "filters": {
                    "price": {"max": amount, "option": currency}
                }
            });
            if let Some(filters) = query.get_mut("filters").and_then(|v| v.as_object_mut()) {
                filters.insert("trade_filters".to_string(), trade_filter);
            } else {
                query["filters"] = serde_json::json!({
                    "trade_filters": trade_filter
                });
            }
        }

        // Stat filters.
        if !stat_filters.is_empty() {
            query["stats"] = serde_json::json!([{
                "type": "and",
                "filters": stat_filters
            }]);
        }

        let body = serde_json::json!({
            "query": query,
            "sort": {"price": "asc"}
        });

        debug!(league, "searching trade");

        // POST search.
        let url = format!("{base_url}/api/trade2/search/poe2/{league}");
        let resp = self
            .rate_limited_post(&url, &body, "trade-search-request-limit")
            .await?;
        let search: SearchResponse = Self::parse_response(resp).await?;

        // Check for API errors.
        if let Some(err) = search.error {
            return Err(TradeError::Api {
                code: err.code,
                message: err.message,
            });
        }

        if search.result.is_empty() {
            return Err(TradeError::NoResults);
        }

        // Fetch first 10 results.
        let query_id = search.id.as_deref().unwrap_or("");
        let hashes: Vec<&str> = search.result.iter().take(10).map(|s| s.as_str()).collect();
        let hashes_str = hashes.join(",");
        let fetch_url = format!("{base_url}/api/trade2/fetch/{hashes_str}?query={query_id}",);

        let fetch_resp = self
            .rate_limited_get(&fetch_url, "trade-fetch-request-limit")
            .await?;
        let fetched: FetchResponse = Self::parse_response(fetch_resp).await?;

        // Format compact results.
        let results: Vec<serde_json::Value> = fetched
            .result
            .iter()
            .map(|item| {
                let mut mods: Vec<String> = item.item.implicit_mods.clone();
                mods.extend(item.item.explicit_mods.clone());

                let price = item
                    .listing
                    .price
                    .as_ref()
                    .map(|p| format!("{} {}", p.amount, p.currency))
                    .unwrap_or_else(|| "unlisted".to_string());

                serde_json::json!({
                    "name": item.item.display_name(),
                    "base_type": item.item.base_type,
                    "ilvl": item.item.ilvl,
                    "rarity": item.item.rarity(),
                    "price": price,
                    "mods": mods
                })
            })
            .collect();

        Ok(serde_json::json!({
            "total": search.total,
            "results": results
        }))
    }

    // -----------------------------------------------------------------------
    // Exchange
    // -----------------------------------------------------------------------

    /// Check currency exchange rates.
    ///
    /// Posts to the exchange endpoint and returns a compact rate summary.
    pub async fn exchange(
        &self,
        have: &str,
        want: &str,
        league: Option<&str>,
    ) -> Result<serde_json::Value, TradeError> {
        let base_url = &self.base_url;
        let league = self.resolve_league(league).await?;

        let body = serde_json::json!({
            "query": {
                "status": {"option": "online"},
                "have": [have],
                "want": [want]
            },
            "sort": {"have": "asc"},
            "engine": "new"
        });

        debug!(league, have, want, "exchange query");

        let url = format!("{base_url}/api/trade2/exchange/poe2/{league}");
        let resp = self
            .rate_limited_post(&url, &body, "trade-exchange-request-limit")
            .await?;
        let exchange: ExchangeResponse = Self::parse_response(resp).await?;

        if let Some(err) = exchange.error {
            return Err(TradeError::Api {
                code: err.code,
                message: err.message,
            });
        }

        if exchange.result.is_empty() {
            return Err(TradeError::NoResults);
        }

        // Build compact rate summary from offers.
        let mut rates: Vec<serde_json::Value> = Vec::new();
        for entry in exchange.result.values() {
            for offer in &entry.listing.offers {
                let give_amount = offer.exchange.amount;
                let get_amount = offer.item.amount;
                let ratio = if get_amount > 0.0 {
                    format!(
                        "{} {} \u{2192} {} {}",
                        give_amount, offer.exchange.currency, get_amount, offer.item.currency
                    )
                } else {
                    "unknown ratio".to_string()
                };
                rates.push(serde_json::json!({
                    "ratio": ratio,
                    "stock": offer.item.stock
                }));
            }
        }

        // Limit to first 5 rates to keep response compact.
        rates.truncate(5);

        Ok(serde_json::json!({
            "have": have,
            "want": want,
            "rates": rates,
            "total_sellers": exchange.total
        }))
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::{method, path_regex};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    /// Helper: create a TradeClient pointing at the mock server with a
    /// pre-seeded default league so tests skip the league resolution request.
    async fn test_client(server: &MockServer) -> TradeClient {
        let client = TradeClient::new_with_base_url(&server.uri());
        client.default_league.set("TestLeague".to_string()).unwrap();
        client
    }

    fn search_params(name: &str) -> SearchParams {
        SearchParams {
            name: Some(name.to_string()),
            item_type: None,
            category: None,
            rarity: None,
            stats: Vec::new(),
            max_price: None,
            league: Some("TestLeague".to_string()),
        }
    }

    // -- Search: API error response ------------------------------------------

    #[tokio::test]
    async fn search_api_error_returns_trade_error() {
        // Given the trade API returns an error-only response (no id/total/result)
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path_regex(r"/api/trade2/search/.*"))
            .respond_with(ResponseTemplate::new(400).set_body_json(
                serde_json::json!({"error": {"code": 2, "message": "Unknown item base type"}}),
            ))
            .mount(&server)
            .await;

        let client = test_client(&server).await;

        // When we search
        let result = client.search(search_params("Nonexistent Item")).await;

        // Then we get a structured API error, not a parse failure
        let err = result.unwrap_err();
        assert!(
            matches!(err, TradeError::Api { code: 2, .. }),
            "expected TradeError::Api, got: {err}"
        );
    }

    // -- Search: successful flow ---------------------------------------------

    #[tokio::test]
    async fn search_success_returns_results() {
        let server = MockServer::start().await;

        // Given the search endpoint returns a valid response with one result hash
        Mock::given(method("POST"))
            .and(path_regex(r"/api/trade2/search/.*"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "abc123",
                "total": 1,
                "result": ["hash1"]
            })))
            .mount(&server)
            .await;

        // And the fetch endpoint returns item details
        Mock::given(method("GET"))
            .and(path_regex(r"/api/trade2/fetch/.*"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "result": [{
                    "listing": {"price": {"amount": 10.0, "currency": "chaos"}},
                    "item": {
                        "name": "Test Ring",
                        "typeLine": "Gold Ring",
                        "baseType": "Gold Ring",
                        "ilvl": 80,
                        "frameType": 3,
                        "explicitMods": ["+20 to Maximum Life"],
                        "implicitMods": []
                    }
                }]
            })))
            .mount(&server)
            .await;

        let client = test_client(&server).await;

        // When we search
        let result = client.search(search_params("Test Ring")).await;

        // Then we get properly formatted results
        let value = result.expect("search should succeed");
        assert_eq!(value["total"], 1);
        let results = value["results"].as_array().unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0]["name"], "Test Ring Gold Ring");
        assert_eq!(results[0]["price"], "10 chaos");
    }

    // -- Search: no results --------------------------------------------------

    #[tokio::test]
    async fn search_empty_results_returns_no_results_error() {
        let server = MockServer::start().await;

        // Given the search returns zero results
        Mock::given(method("POST"))
            .and(path_regex(r"/api/trade2/search/.*"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "id": "abc123",
                "total": 0,
                "result": []
            })))
            .mount(&server)
            .await;

        let client = test_client(&server).await;
        let result = client.search(search_params("Nothing")).await;

        assert!(matches!(result, Err(TradeError::NoResults)));
    }

    // -- Search: non-JSON response -------------------------------------------

    #[tokio::test]
    async fn search_html_error_page_returns_parse_error() {
        let server = MockServer::start().await;

        // Given the API returns an HTML error page (e.g. Cloudflare)
        Mock::given(method("POST"))
            .and(path_regex(r"/api/trade2/search/.*"))
            .respond_with(
                ResponseTemplate::new(503).set_body_string("<html>Service Unavailable</html>"),
            )
            .mount(&server)
            .await;

        let client = test_client(&server).await;
        let result = client.search(search_params("Anything")).await;

        assert!(
            matches!(result, Err(TradeError::Parse(_))),
            "expected TradeError::Parse, got: {result:?}"
        );
    }

    // -- Exchange: API error -------------------------------------------------

    #[tokio::test]
    async fn exchange_api_error_returns_trade_error() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path_regex(r"/api/trade2/exchange/.*"))
            .respond_with(
                ResponseTemplate::new(400).set_body_json(
                    serde_json::json!({"error": {"code": 1, "message": "bad request"}}),
                ),
            )
            .mount(&server)
            .await;

        let client = test_client(&server).await;
        let result = client.exchange("chaos", "divine", Some("TestLeague")).await;

        let err = result.unwrap_err();
        assert!(
            matches!(err, TradeError::Api { code: 1, .. }),
            "expected TradeError::Api, got: {err}"
        );
    }

    // -- Rate limiting -------------------------------------------------------

    #[tokio::test]
    async fn rate_limited_response_returns_rate_limit_error() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path_regex(r"/api/trade2/search/.*"))
            .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "30"))
            .mount(&server)
            .await;

        let client = test_client(&server).await;
        let result = client.search(search_params("Anything")).await;

        assert!(
            matches!(result, Err(TradeError::RateLimited(d)) if d == Duration::from_secs(30)),
            "expected TradeError::RateLimited(30s), got: {result:?}"
        );
    }
}