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
 
 
 
 
 
 
 
 
 
 
 
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
#![allow(dead_code)]
//! External image search providers for IntentForge v2
//!
//! Provides concurrent image search from:
//! - **Pixabay** β€” 100 req/60s, free API key, high-quality stock photos
//! - **Pexels** β€” 200 req/hour (20k/month), free API key, curated photos
//!
//! Both providers are queried concurrently with rate limiting and caching.
//! Results are deduplicated and merged with local Meilisearch image results.

use anyhow::{Context, Result};
use futures::future::join_all;
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::time::{sleep, Duration, Instant};

/// Unified image result from any provider
#[derive(Debug, Clone, Serialize)]
pub struct ImageResult {
    pub id: String,
    pub title: String,
    pub url: String,
    pub source: String,
    pub photographer: Option<String>,
    pub thumbnail_url: Option<String>,
    pub width: Option<u32>,
    pub height: Option<u32>,
    pub avg_color: Option<String>,
    pub tags: Vec<String>,
}

/// Configuration for the image search service
#[derive(Debug, Clone)]
pub struct ImageSearchConfig {
    pub pixabay_api_key: Option<String>,
    pub pexels_api_key: Option<String>,
    pub search_limit: usize,
    pub cache_ttl_secs: u64,
}

impl ImageSearchConfig {
    pub fn from_app_config(config: &crate::config::ImageSearchConfig) -> Self {
        let pixabay_key = std::env::var("PIXABAY_API_KEY")
            .ok()
            .or_else(|| config.pixabay_api_key.clone());

        let pexels_key = std::env::var("PEXELS_API_KEY")
            .ok()
            .or_else(|| config.pexels_api_key.clone());

        Self {
            pixabay_api_key: pixabay_key,
            pexels_api_key: pexels_key,
            search_limit: config.search_limit,
            cache_ttl_secs: config.cache_ttl_secs,
        }
    }
}

// ── Rate limiter ──────────────────────────────────────────────────────

/// Token-bucket rate limiter for per-provider request throttling.
#[derive(Debug)]
struct RateLimiter {
    /// Maximum tokens (requests) in the bucket
    max_tokens: u32,
    /// Current available tokens
    tokens: Mutex<f64>,
    /// Refill rate (tokens per second)
    refill_rate: f64,
    /// Last refill timestamp
    last_refill: Mutex<Instant>,
}

impl RateLimiter {
    fn new(max_tokens: u32, refill_interval_secs: f64) -> Self {
        Self {
            max_tokens,
            tokens: Mutex::new(max_tokens as f64),
            refill_rate: max_tokens as f64 / refill_interval_secs,
            last_refill: Mutex::new(Instant::now()),
        }
    }

    /// Acquire a token, waiting if necessary.
    async fn acquire(&self) {
        loop {
            let mut tokens = self.tokens.lock().await;
            let mut last = self.last_refill.lock().await;
            let now = Instant::now();
            let elapsed = now.duration_since(*last).as_secs_f64();
            *tokens = (*tokens + elapsed * self.refill_rate).min(self.max_tokens as f64);
            *last = now;

            if *tokens >= 1.0 {
                *tokens -= 1.0;
                return;
            }

            let deficit = 1.0 - *tokens;
            let wait_secs = deficit / self.refill_rate;
            drop(tokens);
            drop(last);
            sleep(Duration::from_secs_f64(wait_secs.max(0.01))).await;
        }
    }
}

// ── Pixabay ───────────────────────────────────────────────────────────

/// Pixabay API response
#[derive(Debug, Deserialize)]
struct PixabayResponse {
    total: u64,
    #[serde(rename = "totalHits")]
    total_hits: u64,
    hits: Vec<PixabayHit>,
}

#[derive(Debug, Deserialize)]
struct PixabayHit {
    id: u64,
    #[serde(rename = "pageURL")]
    page_url: String,
    tags: String,
    #[serde(rename = "previewURL")]
    preview_url: String,
    #[serde(rename = "previewWidth")]
    preview_width: u32,
    #[serde(rename = "previewHeight")]
    preview_height: u32,
    #[serde(rename = "webformatURL")]
    webformat_url: String,
    #[serde(rename = "webformatWidth")]
    webformat_width: u32,
    #[serde(rename = "webformatHeight")]
    webformat_height: u32,
    user: String,
    #[serde(rename = "userImageURL")]
    user_image_url: String,
}

pub struct PixabayClient {
    client: reqwest::Client,
    api_key: String,
    rate_limiter: RateLimiter,
}

impl PixabayClient {
    pub fn new(client: reqwest::Client, api_key: String) -> Self {
        Self {
            client,
            api_key,
            // Pixabay: 100 requests per 60 seconds
            rate_limiter: RateLimiter::new(100, 60.0),
        }
    }

    pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<ImageResult>> {
        self.rate_limiter.acquire().await;

        let per_page = limit.clamp(3, 200);
        let url = format!(
            "https://pixabay.com/api/?key={}&q={}&image_type=photo&per_page={}&safesearch=true",
            self.api_key,
            urlencoding::encode(query),
            per_page,
        );

        let resp = self
            .client
            .get(&url)
            .timeout(Duration::from_secs(8))
            .send()
            .await
            .with_context(|| "Pixabay API request failed")?;

        if resp.status() == StatusCode::TOO_MANY_REQUESTS {
            tracing::warn!("Pixabay rate limit hit, backing off");
            sleep(Duration::from_secs(5)).await;
            return Ok(Vec::new());
        }

        if !resp.status().is_success() {
            tracing::warn!("Pixabay API returned status {}", resp.status());
            return Ok(Vec::new());
        }

        let data: PixabayResponse = resp
            .json()
            .await
            .with_context(|| "Failed to parse Pixabay response")?;

        let results: Vec<ImageResult> = data
            .hits
            .into_iter()
            .take(limit)
            .map(|h| ImageResult {
                id: format!("pixabay_{}", h.id),
                title: h
                    .tags
                    .split(',')
                    .next()
                    .unwrap_or("Untitled")
                    .trim()
                    .to_string(),
                url: h.page_url,
                source: "pixabay".to_string(),
                photographer: Some(h.user),
                thumbnail_url: Some(h.preview_url),
                width: Some(h.webformat_width),
                height: Some(h.webformat_height),
                avg_color: None,
                tags: h.tags.split(',').map(|t| t.trim().to_string()).collect(),
            })
            .collect();

        Ok(results)
    }
}

// ── Pexels ────────────────────────────────────────────────────────────

/// Pexels API response
#[derive(Debug, Deserialize)]
struct PexelsResponse {
    total_results: u64,
    photos: Vec<PexelsPhoto>,
}

#[derive(Debug, Deserialize)]
struct PexelsPhoto {
    id: u64,
    width: u32,
    height: u32,
    url: String,
    photographer: String,
    #[serde(rename = "avg_color")]
    avg_color: Option<String>,
    src: PexelsSrc,
    alt: Option<String>,
}

#[derive(Debug, Deserialize)]
struct PexelsSrc {
    original: String,
    large: String,
    medium: String,
    small: String,
    portrait: String,
    landscape: String,
    tiny: String,
}

pub struct PexelsClient {
    client: reqwest::Client,
    api_key: String,
    rate_limiter: RateLimiter,
}

impl PexelsClient {
    pub fn new(client: reqwest::Client, api_key: String) -> Self {
        Self {
            client,
            api_key,
            // Pexels: 200 requests per hour = ~0.055 req/s refill
            rate_limiter: RateLimiter::new(200, 3600.0),
        }
    }

    pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<ImageResult>> {
        self.rate_limiter.acquire().await;

        let per_page = limit.clamp(1, 80);
        let url = format!(
            "https://api.pexels.com/v1/search?query={}&per_page={}",
            urlencoding::encode(query),
            per_page,
        );

        let resp = self
            .client
            .get(&url)
            .header("Authorization", &self.api_key)
            .timeout(Duration::from_secs(8))
            .send()
            .await
            .with_context(|| "Pexels API request failed")?;

        if resp.status() == StatusCode::TOO_MANY_REQUESTS {
            tracing::warn!("Pexels rate limit hit, backing off");
            sleep(Duration::from_secs(10)).await;
            return Ok(Vec::new());
        }

        if resp.status() == StatusCode::FORBIDDEN {
            tracing::warn!("Pexels API key invalid or unauthorized");
            return Ok(Vec::new());
        }

        if !resp.status().is_success() {
            tracing::warn!("Pexels API returned status {}", resp.status());
            return Ok(Vec::new());
        }

        let data: PexelsResponse = resp
            .json()
            .await
            .with_context(|| "Failed to parse Pexels response")?;

        let results: Vec<ImageResult> = data
            .photos
            .into_iter()
            .take(limit)
            .map(|p| ImageResult {
                id: format!("pexels_{}", p.id),
                title: p.alt.unwrap_or_else(|| p.photographer.clone()),
                url: p.url,
                source: "pexels".to_string(),
                photographer: Some(p.photographer),
                thumbnail_url: Some(p.src.tiny),
                width: Some(p.width),
                height: Some(p.height),
                avg_color: p.avg_color,
                tags: Vec::new(),
            })
            .collect();

        Ok(results)
    }
}

// ── Service ───────────────────────────────────────────────────────────

/// Aggregated image search service that fans out to all configured providers.
pub struct ImageSearchService {
    pixabay: Option<PixabayClient>,
    pexels: Option<PexelsClient>,
    cache: Arc<Mutex<ImageCache>>,
    cache_ttl: Duration,
}

#[derive(Debug)]
struct CacheEntry {
    results: Vec<ImageResult>,
    expires: Instant,
}

#[derive(Debug, Default)]
struct ImageCache {
    entries: std::collections::HashMap<String, CacheEntry>,
}

impl ImageSearchService {
    pub fn new(client: reqwest::Client, config: ImageSearchConfig) -> Self {
        let pixabay = config.pixabay_api_key.map(|key| {
            tracing::info!("Pixabay image search enabled");
            PixabayClient::new(client.clone(), key)
        });

        let pexels = config.pexels_api_key.map(|key| {
            tracing::info!("Pexels image search enabled");
            PexelsClient::new(client.clone(), key)
        });

        if pixabay.is_none() && pexels.is_none() {
            tracing::info!("No external image search API keys configured (set PIXABAY_API_KEY and/or PEXELS_API_KEY)");
        }

        Self {
            pixabay,
            pexels,
            cache: Arc::new(Mutex::new(ImageCache::default())),
            cache_ttl: Duration::from_secs(config.cache_ttl_secs),
        }
    }

    /// Search all configured providers concurrently and merge results.
    /// Results are cached per query for `cache_ttl`.
    pub async fn search(&self, query: &str, limit: usize) -> Result<Vec<ImageResult>> {
        let cache_key = format!("{}:{}", query.to_lowercase(), limit);

        // Check cache
        {
            let cache = self.cache.lock().await;
            if let Some(entry) = cache.entries.get(&cache_key) {
                if Instant::now() < entry.expires {
                    return Ok(entry.results.clone());
                }
            }
        }

        #[allow(clippy::type_complexity)]
        let mut futures: Vec<
            std::pin::Pin<Box<dyn std::future::Future<Output = Result<Vec<ImageResult>>> + Send>>,
        > = Vec::new();

        if let Some(ref pixabay) = self.pixabay {
            let q = query.to_string();
            let lim = limit;
            futures.push(Box::pin(async move { pixabay.search(&q, lim).await }));
        }

        if let Some(ref pexels) = self.pexels {
            let q = query.to_string();
            let lim = limit;
            futures.push(Box::pin(async move { pexels.search(&q, lim).await }));
        }

        let results = join_all(futures).await;

        let mut merged: Vec<ImageResult> = Vec::new();
        let mut seen_urls = HashSet::new();

        for result in results {
            match result {
                Ok(images) => {
                    for img in images {
                        if seen_urls.insert(img.url.clone()) {
                            merged.push(img);
                        }
                    }
                }
                Err(e) => {
                    tracing::warn!("Image search provider error: {}", e);
                }
            }
        }

        let final_results: Vec<ImageResult> = merged.into_iter().take(limit).collect();

        // Update cache
        {
            let mut cache = self.cache.lock().await;
            cache.entries.insert(
                cache_key,
                CacheEntry {
                    results: final_results.clone(),
                    expires: Instant::now() + self.cache_ttl,
                },
            );
            // Evict expired entries lazily
            cache.entries.retain(|_, v| Instant::now() < v.expires);
        }

        Ok(final_results)
    }
}

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

    #[test]
    fn test_image_result_structure() {
        let img = ImageResult {
            id: "test_1".to_string(),
            title: "Test".to_string(),
            url: "https://example.com".to_string(),
            source: "pixabay".to_string(),
            photographer: Some("User".to_string()),
            thumbnail_url: Some("https://example.com/thumb.jpg".to_string()),
            width: Some(800),
            height: Some(600),
            avg_color: None,
            tags: vec!["test".to_string()],
        };
        assert_eq!(img.source, "pixabay");
        assert_eq!(img.width, Some(800));
    }

    #[test]
    fn test_config_from_env_fallback() {
        // Ensure no panic when env vars are not set
        std::env::remove_var("PIXABAY_API_KEY");
        std::env::remove_var("PEXELS_API_KEY");

        let app_config = crate::config::ImageSearchConfig::default();
        let config = ImageSearchConfig::from_app_config(&app_config);
        assert!(config.pixabay_api_key.is_none());
        assert!(config.pexels_api_key.is_none());
        assert_eq!(config.search_limit, 20);
        assert_eq!(config.cache_ttl_secs, 86400);
    }

    #[tokio::test]
    async fn test_rate_limiter() {
        // 2 tokens per second, burst of 2
        let limiter = RateLimiter::new(2, 1.0);
        let start = Instant::now();

        // First 2 should be near-instant (burst)
        for _ in 0..2 {
            limiter.acquire().await;
        }
        let elapsed = start.elapsed();
        assert!(
            elapsed.as_millis() < 200,
            "First 2 burst tokens should be fast, got {}ms",
            elapsed.as_millis()
        );

        // 3rd should require waiting ~500ms
        limiter.acquire().await;
        let elapsed = start.elapsed();
        assert!(
            elapsed.as_millis() >= 300,
            "3rd token should require wait, got {}ms",
            elapsed.as_millis()
        );
    }
}