wf-market 0.2.2

A Rust client library for the warframe.market API
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
//! Item model and specialized views.
//!
//! This module provides the [`Item`] type representing tradable items
//! on warframe.market, along with specialized views for item subtypes
//! like mods ([`ModView`]) and Ayatan sculptures ([`SculptureView`]).
//!
//! # Example
//!
//! ```no_run
//! use wf_market::Client;
//!
//! async fn example() -> wf_market::Result<()> {
//!     let client = Client::builder().build()?;
//!     let items = client.fetch_items().await?;
//!
//!     for item in &items {
//!         // Check if it's a mod
//!         if let Some(mod_view) = item.as_mod() {
//!             println!("{}: max rank {}", item.name(), mod_view.max_rank());
//!         }
//!
//!         // Check if it's a sculpture
//!         if let Some(sculpture) = item.as_sculpture() {
//!             println!("{}: {} endo (full)", item.name(), sculpture.calculate_endo(None, None));
//!         }
//!     }
//!     Ok(())
//! }
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use super::common::Rarity;

/// A tradable item on warframe.market.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Item {
    /// Unique item identifier
    pub id: String,

    /// URL-friendly identifier (used in API endpoints)
    pub slug: String,

    /// Internal game reference path
    #[serde(rename = "gameRef", default)]
    pub game_ref: Option<String>,

    /// Whether the item can be traded
    #[serde(default)]
    pub tradable: Option<bool>,

    /// Item categorization tags
    #[serde(default)]
    pub tags: Vec<String>,

    /// Localized content (keyed by language code)
    #[serde(default)]
    pub i18n: HashMap<String, ItemTranslation>,

    /// Item rarity
    #[serde(default)]
    pub rarity: Option<Rarity>,

    /// Whether the item is vaulted (Prime items)
    #[serde(default)]
    pub vaulted: Option<bool>,

    /// Ducat value when sold to Baro Ki'Teer
    #[serde(default)]
    pub ducats: Option<u32>,

    /// Trading tax in credits
    #[serde(rename = "tradingTax", default)]
    pub trading_tax: Option<u32>,

    /// Required mastery rank to trade
    #[serde(rename = "reqMasteryRank", default)]
    pub mastery_rank: Option<u32>,

    // === Mod-specific fields ===
    /// Maximum mod rank (for rankable mods)
    #[serde(rename = "maxRank", default)]
    pub max_rank: Option<u32>,

    /// Maximum charges (for consumable mods like Requiem)
    #[serde(rename = "maxCharges", default)]
    pub max_charges: Option<u32>,

    // === Ayatan Sculpture fields ===
    /// Maximum amber stars (for Ayatan sculptures)
    #[serde(rename = "maxAmberStars", default)]
    pub max_amber_stars: Option<u32>,

    /// Maximum cyan stars (for Ayatan sculptures)
    #[serde(rename = "maxCyanStars", default)]
    pub max_cyan_stars: Option<u32>,

    /// Base endo value (for Ayatan sculptures)
    #[serde(rename = "baseEndo", default)]
    pub base_endo: Option<u32>,

    /// Endo multiplier per filled socket (for Ayatan sculptures)
    #[serde(rename = "endoMultiplier", default)]
    pub endo_multiplier: Option<f32>,

    // === Set-related fields ===
    /// Whether this item is the root of a set
    #[serde(rename = "setRoot", default)]
    pub set_root: Option<bool>,

    /// Item IDs that are part of this set (if set_root is true)
    #[serde(rename = "setParts", default)]
    pub set_parts: Option<Vec<String>>,

    /// Quantity of this item in its parent set
    #[serde(rename = "quantityInSet", default)]
    pub quantity_in_set: Option<u32>,

    /// Whether multiple items can be traded at once
    #[serde(rename = "bulkTradable", default)]
    pub bulk_tradable: Option<bool>,

    /// Available subtypes (e.g., blueprint, crafted)
    #[serde(default)]
    pub subtypes: Option<Vec<String>>,
}

/// Localized item content.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ItemTranslation {
    /// Localized item name
    pub name: String,

    /// Path to item icon (relative to static assets)
    pub icon: String,

    /// Path to item thumbnail
    #[serde(default)]
    pub thumb: Option<String>,

    /// Path to sub-icon (e.g., blueprint indicator)
    #[serde(rename = "subIcon", default)]
    pub sub_icon: Option<String>,

    /// Localized item description
    #[serde(default)]
    pub description: Option<String>,

    /// Link to the Warframe wiki page
    #[serde(rename = "wikiLink", default)]
    pub wiki_link: Option<String>,
}

impl Item {
    /// Get the English name of the item.
    ///
    /// Returns an empty string if no English translation is available.
    pub fn name(&self) -> &str {
        self.i18n.get("en").map(|t| t.name.as_str()).unwrap_or("")
    }

    /// Get the localized name for a specific language.
    ///
    /// Falls back to English if the requested language is not available.
    pub fn name_localized(&self, lang: &str) -> &str {
        self.i18n
            .get(lang)
            .or_else(|| self.i18n.get("en"))
            .map(|t| t.name.as_str())
            .unwrap_or("")
    }

    /// Get the English translation data.
    pub fn translation(&self) -> Option<&ItemTranslation> {
        self.i18n.get("en")
    }

    /// Get the icon URL (relative to static assets base).
    pub fn icon(&self) -> Option<&str> {
        self.i18n.get("en").map(|t| t.icon.as_str())
    }

    /// Get the wiki link if available.
    pub fn wiki_link(&self) -> Option<&str> {
        self.i18n.get("en").and_then(|t| t.wiki_link.as_deref())
    }

    /// Check if this item is a mod (has max_rank).
    pub fn is_mod(&self) -> bool {
        self.max_rank.is_some()
    }

    /// Check if this item is an Ayatan sculpture.
    pub fn is_sculpture(&self) -> bool {
        self.base_endo.is_some() && self.endo_multiplier.is_some()
    }

    /// Check if this item is a set (contains multiple parts).
    pub fn is_set(&self) -> bool {
        self.set_root.unwrap_or(false)
    }

    /// Check if this item is vaulted.
    pub fn is_vaulted(&self) -> bool {
        self.vaulted.unwrap_or(false)
    }

    /// Check if this item has charges (like Requiem mods).
    pub fn has_charges(&self) -> bool {
        self.max_charges.is_some()
    }

    /// Get a mod-specific view of this item.
    ///
    /// Returns `Some(ModView)` if this item is a mod, `None` otherwise.
    /// The view provides type-safe access to mod-specific data.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use wf_market::models::Item;
    /// # fn example(item: &Item) {
    /// if let Some(mod_view) = item.as_mod() {
    ///     println!("Max rank: {}", mod_view.max_rank());
    ///     if let Some(charges) = mod_view.max_charges() {
    ///         println!("Max charges: {}", charges);
    ///     }
    /// }
    /// # }
    /// ```
    pub fn as_mod(&self) -> Option<ModView<'_>> {
        if self.max_rank.is_some() {
            Some(ModView(self))
        } else {
            None
        }
    }

    /// Get a sculpture-specific view of this item.
    ///
    /// Returns `Some(SculptureView)` if this item is an Ayatan sculpture,
    /// `None` otherwise. The view provides type-safe access to sculpture
    /// data and endo calculation.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use wf_market::models::Item;
    /// # fn example(item: &Item) {
    /// if let Some(sculpture) = item.as_sculpture() {
    ///     let endo = sculpture.calculate_endo(None, None);
    ///     println!("Endo value (full): {}", endo);
    /// }
    /// # }
    /// ```
    pub fn as_sculpture(&self) -> Option<SculptureView<'_>> {
        if self.base_endo.is_some() && self.endo_multiplier.is_some() {
            Some(SculptureView(self))
        } else {
            None
        }
    }
}

/// A zero-cost view into mod-specific item data.
///
/// This type can only be constructed from an [`Item`] that is actually
/// a mod, providing compile-time guarantees that mod-specific methods
/// are only called on appropriate items.
#[derive(Debug, Clone, Copy)]
pub struct ModView<'a>(&'a Item);

impl<'a> ModView<'a> {
    /// Get the underlying item.
    pub fn item(&self) -> &Item {
        self.0
    }

    /// Get the maximum rank of this mod.
    ///
    /// This is guaranteed to return a value since `ModView` can only
    /// be constructed from items that have `max_rank`.
    pub fn max_rank(&self) -> u32 {
        self.0.max_rank.unwrap() // Safe: guaranteed by construction
    }

    /// Get the maximum charges (for consumable mods like Requiem).
    pub fn max_charges(&self) -> Option<u32> {
        self.0.max_charges
    }

    /// Check if this mod has charges.
    pub fn has_charges(&self) -> bool {
        self.0.max_charges.is_some()
    }
}

/// A zero-cost view into Ayatan sculpture-specific item data.
///
/// This type can only be constructed from an [`Item`] that is actually
/// an Ayatan sculpture, providing compile-time guarantees that sculpture
/// methods are only called on appropriate items.
#[derive(Debug, Clone, Copy)]
pub struct SculptureView<'a>(&'a Item);

impl<'a> SculptureView<'a> {
    /// Get the underlying item.
    pub fn item(&self) -> &Item {
        self.0
    }

    /// Get the base endo value before star multipliers.
    pub fn base_endo(&self) -> u32 {
        self.0.base_endo.unwrap() // Safe: guaranteed by construction
    }

    /// Get the endo multiplier per filled socket.
    pub fn endo_multiplier(&self) -> f32 {
        self.0.endo_multiplier.unwrap() // Safe: guaranteed by construction
    }

    /// Get the maximum amber star slots.
    pub fn max_amber_stars(&self) -> u32 {
        self.0.max_amber_stars.unwrap_or(0)
    }

    /// Get the maximum cyan star slots.
    pub fn max_cyan_stars(&self) -> u32 {
        self.0.max_cyan_stars.unwrap_or(0)
    }

    /// Get the total number of star slots.
    pub fn total_slots(&self) -> u32 {
        self.max_amber_stars() + self.max_cyan_stars()
    }

    /// Calculate the endo value of this sculpture with given stars.
    ///
    /// # Arguments
    ///
    /// * `cyan_stars` - Number of cyan stars installed. If `None`, uses max.
    /// * `amber_stars` - Number of amber stars installed. If `None`, uses max.
    ///
    /// # Formula
    ///
    /// The endo value is calculated as:
    /// ```text
    /// (base + 50*cyan + 100*amber) * (1 + multiplier * filled_slots / total_slots)
    /// ```
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use wf_market::models::Item;
    /// # fn example(item: &Item) {
    /// if let Some(sculpture) = item.as_sculpture() {
    ///     // Full value (all slots filled)
    ///     let full = sculpture.calculate_endo(None, None);
    ///
    ///     // Empty value (no stars)
    ///     let empty = sculpture.calculate_endo(Some(0), Some(0));
    ///
    ///     // Partial (2 cyan, 1 amber)
    ///     let partial = sculpture.calculate_endo(Some(2), Some(1));
    /// }
    /// # }
    /// ```
    pub fn calculate_endo(&self, cyan_stars: Option<u32>, amber_stars: Option<u32>) -> u32 {
        let base = self.base_endo() as f32;
        let multiplier = self.endo_multiplier();
        let total_slots = self.total_slots();

        if total_slots == 0 {
            return base as u32;
        }

        let cyan = cyan_stars.unwrap_or_else(|| self.max_cyan_stars());
        let amber = amber_stars.unwrap_or_else(|| self.max_amber_stars());

        let filled_slots = (cyan + amber) as f32;
        let base_value = base + 50.0 * (cyan as f32) + 100.0 * (amber as f32);
        let socket_factor = 1.0 + multiplier * filled_slots / (total_slots as f32);

        (base_value * socket_factor) as u32
    }
}

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

    fn make_test_item() -> Item {
        Item {
            id: "test-id".to_string(),
            slug: "test-slug".to_string(),
            game_ref: None,
            tradable: Some(true),
            tags: vec!["mod".to_string()],
            i18n: HashMap::from([(
                "en".to_string(),
                ItemTranslation {
                    name: "Test Item".to_string(),
                    icon: "/icons/test.png".to_string(),
                    thumb: None,
                    sub_icon: None,
                    description: None,
                    wiki_link: None,
                },
            )]),
            rarity: Some(Rarity::Rare),
            vaulted: None,
            ducats: None,
            trading_tax: None,
            mastery_rank: None,
            max_rank: Some(10),
            max_charges: None,
            max_amber_stars: None,
            max_cyan_stars: None,
            base_endo: None,
            endo_multiplier: None,
            set_root: None,
            set_parts: None,
            quantity_in_set: None,
            bulk_tradable: None,
            subtypes: None,
        }
    }

    fn make_sculpture() -> Item {
        Item {
            id: "sculpture-id".to_string(),
            slug: "ayatan-anasa".to_string(),
            game_ref: None,
            tradable: Some(true),
            tags: vec!["ayatan".to_string()],
            i18n: HashMap::from([(
                "en".to_string(),
                ItemTranslation {
                    name: "Ayatan Anasa Sculpture".to_string(),
                    icon: "/icons/anasa.png".to_string(),
                    thumb: None,
                    sub_icon: None,
                    description: None,
                    wiki_link: None,
                },
            )]),
            rarity: None,
            vaulted: None,
            ducats: None,
            trading_tax: None,
            mastery_rank: None,
            max_rank: None,
            max_charges: None,
            max_amber_stars: Some(2),
            max_cyan_stars: Some(4),
            base_endo: Some(450),
            endo_multiplier: Some(0.9),
            set_root: None,
            set_parts: None,
            quantity_in_set: None,
            bulk_tradable: None,
            subtypes: None,
        }
    }

    #[test]
    fn test_item_name() {
        let item = make_test_item();
        assert_eq!(item.name(), "Test Item");
    }

    #[test]
    fn test_item_is_mod() {
        let item = make_test_item();
        assert!(item.is_mod());
        assert!(!item.is_sculpture());
    }

    #[test]
    fn test_mod_view() {
        let item = make_test_item();
        let mod_view = item.as_mod().expect("Should be a mod");
        assert_eq!(mod_view.max_rank(), 10);
    }

    #[test]
    fn test_sculpture_view() {
        let item = make_sculpture();
        assert!(item.is_sculpture());
        assert!(!item.is_mod());

        let sculpture = item.as_sculpture().expect("Should be a sculpture");
        assert_eq!(sculpture.base_endo(), 450);
        assert_eq!(sculpture.max_amber_stars(), 2);
        assert_eq!(sculpture.max_cyan_stars(), 4);
        assert_eq!(sculpture.total_slots(), 6);
    }

    #[test]
    fn test_sculpture_endo_calculation() {
        let item = make_sculpture();
        let sculpture = item.as_sculpture().unwrap();

        // Full value
        let full = sculpture.calculate_endo(None, None);
        assert!(full > sculpture.base_endo());

        // Empty value
        let empty = sculpture.calculate_endo(Some(0), Some(0));
        assert_eq!(empty, sculpture.base_endo());

        // Partial should be between empty and full
        let partial = sculpture.calculate_endo(Some(2), Some(1));
        assert!(partial > empty);
        assert!(partial < full);
    }

    #[test]
    fn test_non_mod_returns_none() {
        let item = make_sculpture();
        assert!(item.as_mod().is_none());
    }

    #[test]
    fn test_non_sculpture_returns_none() {
        let item = make_test_item();
        assert!(item.as_sculpture().is_none());
    }
}

/// Response for item set endpoint.
///
/// Contains the requested item's ID and all items in the set.
/// If the item is not part of a set, the items array contains only that item.
///
/// # Example
///
/// ```ignore
/// use wf_market::Client;
///
/// async fn example() -> wf_market::Result<()> {
///     let client = Client::builder().build()?;
///     let set = client.get_item_set("nikana_prime_set").await?;
///
///     println!("Set {} contains {} items:", set.id, set.items.len());
///     for item in &set.items {
///         println!("  - {}", item.name());
///     }
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone, Deserialize)]
pub struct ItemSet {
    /// ID of the requested item
    pub id: String,

    /// All items in the set (or just the single item if not part of a set)
    pub items: Vec<Item>,
}

impl ItemSet {
    /// Check if this is actually a set (more than one item).
    pub fn is_set(&self) -> bool {
        self.items.len() > 1
    }

    /// Get the number of items in the set.
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Check if the set is empty (should never happen with valid API data).
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Get the set root item (the main set item like "Nikana Prime Set").
    pub fn root(&self) -> Option<&Item> {
        self.items.iter().find(|item| item.is_set())
    }

    /// Get all parts excluding the set root.
    pub fn parts(&self) -> impl Iterator<Item = &Item> {
        self.items.iter().filter(|item| !item.is_set())
    }
}