mudra-cli 0.1.0

A robust, high-performance currency converter with caching and CLI interface
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
//! Enhanced exchange rate service with caching and historical data support

use crate::{
    CurrencyError, Result,
    api::{
        client::CurrencyClient,
        types::{
            ApiErrorResponse, ConversionResponse, ExchangeRateResponse,
            HistoricalConversionRequest, HistoricalRateResponse, SupportedCurrenciesResponse,
            is_valid_currency_code, is_valid_date_format,
        },
    },
    cache::{CacheKey, ExchangeRateCache},
};

/// Enhanced service for exchange rate operations with caching
#[derive(Debug, Clone)]
pub struct ExchangeRateService {
    client: CurrencyClient,
    cache: ExchangeRateCache,
}

impl ExchangeRateService {
    /// Create a new exchange rate service with caching
    pub fn new(client: CurrencyClient) -> Self {
        Self {
            client,
            cache: ExchangeRateCache::new(),
        }
    }

    /// Create a service from environment variables
    pub fn from_env() -> Result<Self> {
        let client = CurrencyClient::from_env()?;
        Ok(Self::new(client))
    }

    /// Create a service with custom cache configuration
    pub fn with_cache_config(
        client: CurrencyClient,
        cache_config: crate::cache::CacheConfig,
    ) -> Self {
        Self {
            client,
            cache: ExchangeRateCache::with_config(cache_config),
        }
    }

    /// Fetch latest exchange rates for a base currency (with caching)
    pub async fn get_latest_rates(&self, base_currency: &str) -> Result<ExchangeRateResponse> {
        // Validate currency code format
        self.validate_currency_code(base_currency)?;

        let cache_key = CacheKey::latest(base_currency);

        // Try cache first
        if let Some(cached_rates) = self.cache.get(&cache_key).await {
            return Ok(cached_rates);
        }

        // Cache miss - fetch from API

        // Get API key for the request
        let api_key = self.get_api_key()?;

        // Build endpoint URL
        let endpoint = format!("{}/latest/{}", api_key, base_currency.to_uppercase());

        // Make the API request
        match self.client.get::<ExchangeRateResponse>(&endpoint).await {
            Ok(response) => {
                if response.is_success() {
                    // Cache the response
                    self.cache.put(cache_key, response.clone()).await;
                    Ok(response)
                } else {
                    Err(CurrencyError::api(format!(
                        "API returned unsuccessful result: {}",
                        response.result
                    )))
                }
            }
            Err(e) => {
                // Try to parse as an error response for better error messages
                if let Ok(error_response) = self.try_parse_error_response(&endpoint).await {
                    return Err(CurrencyError::api(format!(
                        "API error: {} - {}",
                        error_response.error_type,
                        error_response.extra_info.unwrap_or_default()
                    )));
                }
                Err(e)
            }
        }
    }

    /// Fetch historical exchange rates for a specific date
    pub async fn get_historical_rates(
        &self,
        base_currency: &str,
        date: &str,
    ) -> Result<HistoricalRateResponse> {
        // Validate inputs
        self.validate_currency_code(base_currency)?;
        self.validate_date_format(date)?;

        let cache_key = CacheKey::historical(base_currency, date);

        // Try cache first - convert standard response to historical if cached
        if let Some(cached_rates) = self.cache.get(&cache_key).await {
            println!(
                "๐Ÿ“‹ Using cached historical rates for {} on {}",
                base_currency.to_uppercase(),
                date
            );
            return Ok(cached_rates.to_historical(date));
        }

        // Cache miss - fetch from API
        println!(
            "๐Ÿ“Š Fetching historical rates for {} on {}",
            base_currency.to_uppercase(),
            date
        );

        let api_key = self.get_api_key()?;
        let endpoint = format!(
            "history/{}/{}/{}",
            api_key,
            base_currency.to_uppercase(),
            date
        );

        // Try to fetch as historical response, fallback to standard response
        match self.client.get::<HistoricalRateResponse>(&endpoint).await {
            Ok(response) => {
                if response.is_success() {
                    println!("โœ… Successfully fetched historical rates for {}", date);

                    // Cache as standard response
                    let standard_response = response.to_standard();
                    self.cache.put(cache_key, standard_response).await;

                    Ok(response)
                } else {
                    Err(CurrencyError::api(format!(
                        "Historical data request failed: {}",
                        response.result
                    )))
                }
            }
            Err(_) => {
                // Fallback: try to get current rates and convert to historical format
                match self.get_latest_rates(base_currency).await {
                    Ok(current_rates) => {
                        println!("โš ๏ธ Using current rates as historical fallback for {}", date);
                        Ok(current_rates.to_historical(date))
                    }
                    Err(e) => Err(e),
                }
            }
        }
    }

    /// Convert currency with historical data support
    pub async fn convert_historical(
        &self,
        request: HistoricalConversionRequest,
    ) -> Result<ConversionResponse> {
        // Validate inputs
        self.validate_currency_code(&request.from)?;
        self.validate_currency_code(&request.to)?;
        self.validate_amount(request.amount)?;
        self.validate_date_format(&request.date)?;

        println!(
            "๐Ÿ’ฑ Historical conversion: {} {} to {} on {}",
            request.amount,
            request.from.to_uppercase(),
            request.to.to_uppercase(),
            request.date
        );

        // Get historical rates for the base currency
        let rates = self
            .get_historical_rates(&request.from, &request.date)
            .await?;

        // Find the target currency rate
        let rate = rates.get_rate(&request.to.to_uppercase()).ok_or_else(|| {
            CurrencyError::api(format!(
                "Historical rate not available for {} on {}",
                request.to.to_uppercase(),
                request.date
            ))
        })?;

        let converted_amount = request.amount * rate;

        println!(
            "โœ… Historical conversion: {} {} = {:.6} {} (rate: {:.6})",
            request.amount,
            request.from.to_uppercase(),
            converted_amount,
            request.to.to_uppercase(),
            rate
        );

        Ok(ConversionResponse {
            result: "success".to_string(),
            base_code: request.from.to_uppercase(),
            target_code: request.to.to_uppercase(),
            conversion_rate: rate,
            conversion_result: converted_amount,
        })
    }

    /// Convert a specific amount between two currencies (current rates)
    pub async fn convert_currency(
        &self,
        from: &str,
        to: &str,
        amount: f64,
    ) -> Result<ConversionResponse> {
        // Validate inputs
        self.validate_currency_code(from)?;
        self.validate_currency_code(to)?;
        self.validate_amount(amount)?;

        let api_key = self.get_api_key()?;

        // Build endpoint URL for pair conversion
        let endpoint = format!(
            "pair/{}/{}/{}/{}",
            api_key,
            from.to_uppercase(),
            to.to_uppercase(),
            amount
        );

        println!(
            "๐Ÿ’ฑ Converting {} {} to {}",
            amount,
            from.to_uppercase(),
            to.to_uppercase()
        );

        // Make the API request
        match self.client.get::<ConversionResponse>(&endpoint).await {
            Ok(response) => {
                if response.is_success() {
                    println!(
                        "โœ… Conversion successful: {} {} = {} {}",
                        amount,
                        from.to_uppercase(),
                        response.conversion_result,
                        to.to_uppercase()
                    );
                    Ok(response)
                } else {
                    Err(CurrencyError::api(format!(
                        "Conversion failed: {}",
                        response.result
                    )))
                }
            }
            Err(e) => {
                if let Ok(error_response) = self.try_parse_error_response(&endpoint).await {
                    return Err(CurrencyError::api(format!(
                        "Conversion error: {} - {}",
                        error_response.error_type,
                        error_response.extra_info.unwrap_or_default()
                    )));
                }
                Err(e)
            }
        }
    }

    /// Get list of supported currencies (cached)
    pub async fn get_supported_currencies(&self) -> Result<SupportedCurrenciesResponse> {
        let api_key = self.get_api_key()?;
        let endpoint = format!("codes/{}", api_key);

        println!("๐Ÿ“‹ Fetching supported currencies");

        let response = self
            .client
            .get::<SupportedCurrenciesResponse>(&endpoint)
            .await?;

        if response.result == "success" {
            println!(
                "โœ… Found {} supported currencies",
                response.supported_codes.len()
            );
            Ok(response)
        } else {
            Err(CurrencyError::api(format!(
                "Failed to fetch supported currencies: {}",
                response.result
            )))
        }
    }

    /// Check if a currency is supported by fetching a small set of rates
    pub async fn is_currency_supported(&self, currency: &str) -> Result<bool> {
        match self.get_latest_rates(currency).await {
            Ok(_) => Ok(true),
            Err(CurrencyError::Api { message }) if message.contains("unsupported-code") => {
                Ok(false)
            }
            Err(e) => Err(e),
        }
    }

    /// Batch convert multiple currency pairs efficiently
    pub async fn batch_convert(
        &self,
        base_currency: &str,
        target_currencies: &[String],
        amount: f64,
    ) -> Result<Vec<Result<ConversionResponse>>> {
        // Get rates for the base currency once
        let rates = self.get_latest_rates(base_currency).await?;

        println!(
            "๐Ÿ”„ Batch converting {} {} to {} currencies",
            amount,
            base_currency.to_uppercase(),
            target_currencies.len()
        );

        let mut results = Vec::new();

        for target in target_currencies {
            let result = if let Some(rate) = rates.get_rate(&target.to_uppercase()) {
                let converted_amount = amount * rate;
                Ok(ConversionResponse {
                    result: "success".to_string(),
                    base_code: base_currency.to_uppercase(),
                    target_code: target.to_uppercase(),
                    conversion_rate: rate,
                    conversion_result: converted_amount,
                })
            } else {
                Err(CurrencyError::api(format!(
                    "Exchange rate not available for {}",
                    target.to_uppercase()
                )))
            };
            results.push(result);
        }

        println!("โœ… Completed batch conversion");
        Ok(results)
    }

    /// Get cache statistics
    pub fn get_cache_stats(&self) -> crate::cache::CacheStats {
        self.cache.get_stats()
    }

    /// Clear cache manually
    pub async fn clear_cache(&self) {
        self.cache.clear().await;
        println!("๐Ÿ—‘๏ธ Cache cleared");
    }

    /// Force cache cleanup of expired entries
    pub async fn cleanup_cache(&self) {
        self.cache.cleanup_expired().await;
        println!("๐Ÿงน Cache cleanup completed");
    }

    /// Validate currency code format
    fn validate_currency_code(&self, code: &str) -> Result<()> {
        if !is_valid_currency_code(code) {
            return Err(CurrencyError::invalid_currency(format!(
                "{} (must be 3 uppercase letters, e.g., USD, EUR, GBP)",
                code
            )));
        }
        Ok(())
    }

    /// Validate date format (YYYY-MM-DD)
    fn validate_date_format(&self, date: &str) -> Result<()> {
        if !is_valid_date_format(date) {
            return Err(CurrencyError::conversion(format!(
                "Invalid date format: '{}'. Use YYYY-MM-DD format (e.g., 2024-01-15)",
                date
            )));
        }
        Ok(())
    }

    /// Validate amount for conversion
    fn validate_amount(&self, amount: f64) -> Result<()> {
        if amount <= 0.0 {
            return Err(CurrencyError::invalid_amount(amount));
        }
        if amount.is_nan() || amount.is_infinite() {
            return Err(CurrencyError::invalid_amount(amount));
        }
        // Reasonable upper limit to prevent abuse
        if amount > 1_000_000_000.0 {
            return Err(CurrencyError::invalid_amount(amount));
        }
        Ok(())
    }

    /// Get API key from client configuration
    fn get_api_key(&self) -> Result<String> {
        if !self.client.has_api_key() {
            return Err(CurrencyError::configuration(
                "API key required. Set EXCHANGE_API_KEY environment variable",
            ));
        }
        // For now, we'll assume the API key is available
        // In a real implementation, you'd extract it from the client
        std::env::var("EXCHANGE_API_KEY")
            .map_err(|_| CurrencyError::configuration("EXCHANGE_API_KEY not found"))
    }

    /// Try to parse an error response for better error messages
    async fn try_parse_error_response(&self, endpoint: &str) -> Result<ApiErrorResponse> {
        // This is a simplified approach - in practice you might want to
        // capture the original response body in the error
        self.client.get::<ApiErrorResponse>(endpoint).await
    }
}