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
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
#![allow(clippy::too_many_arguments)]
//! Indexer module for IntentForge v2
//!
//! Handles document indexing with Qdrant Cloud, including binary quantization
//! and hybrid search capabilities.

use anyhow::{Context, Result};
use qdrant_client::prelude::*;
use qdrant_client::qdrant::{
    quantization_config, vectors_config::Config as VectorConfigEnum, BinaryQuantization, Condition,
    CreateCollection, Distance, FieldType, Filter, PointId, PointStruct, PointsSelector,
    QuantizationConfig, SearchPoints, Value, VectorParams, VectorsConfig,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use uuid::Uuid;

/// Document schema for IntentForge
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IntentDocument {
    pub id: String,
    pub title: String,
    pub content: String,
    pub description: Option<String>,
    pub url: String,
    pub source: String,
    pub category: String,
    pub tags: Vec<String>,
    pub published_at: Option<i64>,

    // Media
    #[serde(default = "default_media_type")]
    pub media_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thumbnail_url: Option<String>,

    // Image-specific fields
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_hash: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_thumbhash: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_dimensions: Option<(u32, u32)>,

    // Scores
    #[serde(rename = "intent_score")]
    pub intent_score: f32,
    #[serde(rename = "relevance_score")]
    pub relevance_score: f32,
    #[serde(rename = "commercial_score")]
    #[serde(default)]
    pub commercial_score: f32,
    #[serde(rename = "spam_score")]
    #[serde(default)]
    pub spam_score: f32,

    // Vector embeddings (Stored in Qdrant named vectors)
    #[serde(skip)]
    pub vector: Option<Vec<f32>>,
}

fn default_media_type() -> String {
    "text".to_string()
}

impl IntentDocument {
    /// Create a new document with vector
    pub fn new(
        id: String,
        title: String,
        content: String,
        url: String,
        source: String,
        category: String,
        intent_score: f32,
        relevance_score: f32,
        vector: Vec<f32>,
    ) -> Self {
        Self {
            id,
            title,
            content,
            description: None,
            url,
            source,
            category,
            tags: Vec::new(),
            published_at: None,
            media_type: default_media_type(),
            thumbnail_url: None,
            image_hash: None,
            image_thumbhash: None,
            image_dimensions: None,
            intent_score,
            relevance_score,
            commercial_score: 0.0,
            spam_score: 0.0,
            vector: Some(vector),
        }
    }

    /// Convert to Qdrant PointStruct
    pub fn to_point(&self, _collection_name: &str) -> Result<PointStruct> {
        let mut payload_map: HashMap<&str, Value> = HashMap::new();

        payload_map.insert("id", self.id.clone().into());
        payload_map.insert("title", self.title.clone().into());
        payload_map.insert("content", self.content.clone().into());
        if let Some(desc) = &self.description {
            payload_map.insert("description", desc.clone().into());
        }
        payload_map.insert("url", self.url.clone().into());
        payload_map.insert("source", self.source.clone().into());
        payload_map.insert("category", self.category.clone().into());
        payload_map.insert("tags", self.tags.clone().into());
        if let Some(pub_at) = self.published_at {
            payload_map.insert("published_at", pub_at.into());
        }
        payload_map.insert("media_type", self.media_type.clone().into());
        if let Some(thumb) = &self.thumbnail_url {
            payload_map.insert("thumbnail_url", thumb.clone().into());
        }
        if let Some(hash) = &self.image_hash {
            payload_map.insert("image_hash", hash.clone().into());
        }
        if let Some(thash) = &self.image_thumbhash {
            payload_map.insert("image_thumbhash", thash.clone().into());
        }
        if let Some(dims) = self.image_dimensions {
            payload_map.insert("image_width", (dims.0 as i64).into());
            payload_map.insert("image_height", (dims.1 as i64).into());
        }
        payload_map.insert("intent_score", (self.intent_score as f64).into());
        payload_map.insert("relevance_score", (self.relevance_score as f64).into());
        payload_map.insert("commercial_score", (self.commercial_score as f64).into());
        payload_map.insert("spam_score", (self.spam_score as f64).into());

        let payload = Payload::from(payload_map);
        let point_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, self.id.as_bytes()).to_string();
        let vector = self.vector.clone().context("Document missing vector")?;

        Ok(PointStruct::new(point_id, vector, payload))
    }

    /// Set extra scores
    pub fn with_extra_scores(mut self, commercial: f32, spam: f32) -> Self {
        self.commercial_score = commercial;
        self.spam_score = spam;
        self
    }

    /// Set description
    pub fn with_description(mut self, description: String) -> Self {
        self.description = Some(description);
        self
    }

    /// Set tags
    pub fn with_tags(mut self, tags: Vec<String>) -> Self {
        self.tags = tags;
        self
    }

    /// Set published timestamp
    pub fn with_published_at(mut self, timestamp: i64) -> Self {
        self.published_at = Some(timestamp);
        self
    }

    /// Set image metadata (hash, thumbhash, dimensions)
    pub fn with_image_metadata(
        mut self,
        hash: Option<String>,
        thumbhash: Option<String>,
        dimensions: Option<(u32, u32)>,
    ) -> Self {
        self.media_type = "image".to_string();
        self.image_hash = hash;
        self.image_thumbhash = thumbhash;
        self.image_dimensions = dimensions;
        self
    }

    /// Set media type
    pub fn with_media_type(mut self, media_type: String) -> Self {
        self.media_type = media_type;
        self
    }

    /// Truncate content to a snippet if not already short
    pub fn with_snippet(mut self, max_length: usize) -> Self {
        if self.content.len() > max_length {
            let mut snippet = self.content.chars().take(max_length).collect::<String>();
            snippet.push_str("...");
            self.content = snippet;
        }
        self
    }
}

/// Indexer wrapper for Qdrant operations
#[derive(Clone)]
pub struct Indexer {
    pub client: Arc<QdrantClient>,
    pub collection_name: String,
    pub redis: Option<Arc<crate::redis_store::RedisStore>>,
}

impl Indexer {
    /// Create a new indexer instance
    pub fn new(url: &str, api_key: Option<&str>, collection_name: &str) -> Result<Self> {
        let mut config = QdrantClientConfig::from_url(url);
        if let Some(key) = api_key {
            config.api_key = Some(key.to_string());
        }

        let client = QdrantClient::new(Some(config))?;

        Ok(Self {
            client: Arc::new(client),
            collection_name: collection_name.to_string(),
            redis: None,
        })
    }

    pub fn with_redis(mut self, redis: Arc<crate::redis_store::RedisStore>) -> Self {
        self.redis = Some(redis);
        self
    }

    pub fn get_redis(&self) -> Arc<crate::redis_store::RedisStore> {
        self.redis
            .as_ref()
            .expect("RedisStore not initialized in Indexer")
            .clone()
    }

    /// Ensure collection exists with correct settings
    pub async fn ensure_settings(&self) -> Result<()> {
        if self.client.collection_exists(&self.collection_name).await? {
            tracing::info!("Collection {} already exists", self.collection_name);
            return Ok(());
        }

        tracing::info!(
            "Creating collection {} with Binary Quantization",
            self.collection_name
        );

        self.client
            .create_collection(&CreateCollection {
                collection_name: self.collection_name.clone(),
                vectors_config: Some(VectorsConfig {
                    config: Some(VectorConfigEnum::Params(VectorParams {
                        size: 384,
                        distance: Distance::Cosine.into(),
                        ..Default::default()
                    })),
                }),
                quantization_config: Some(QuantizationConfig {
                    quantization: Some(quantization_config::Quantization::Binary(
                        BinaryQuantization {
                            always_ram: Some(true),
                        },
                    )),
                }),
                ..Default::default()
            })
            .await?;

        // Create field indexes for title and content
        self.client
            .create_field_index(&self.collection_name, "title", FieldType::Text, None, None)
            .await?;
        self.client
            .create_field_index(
                &self.collection_name,
                "content",
                FieldType::Text,
                None,
                None,
            )
            .await?;

        // Create standard keyword indexes for filtering
        self.client
            .create_field_index(
                &self.collection_name,
                "category",
                FieldType::Keyword,
                None,
                None,
            )
            .await?;
        self.client
            .create_field_index(
                &self.collection_name,
                "media_type",
                FieldType::Keyword,
                None,
                None,
            )
            .await?;
        self.client
            .create_field_index(
                &self.collection_name,
                "source",
                FieldType::Keyword,
                None,
                None,
            )
            .await?;

        Ok(())
    }

    /// Index a single document
    pub async fn index_document(&self, doc: &IntentDocument) -> Result<()> {
        let point = doc.to_point(&self.collection_name)?;
        self.client
            .upsert_points(&self.collection_name, None, vec![point], None)
            .await?;
        Ok(())
    }

    /// Index multiple documents in batch
    pub async fn index_documents(&self, docs: &[IntentDocument]) -> Result<()> {
        if docs.is_empty() {
            return Ok(());
        }

        let mut points = Vec::new();
        for doc in docs {
            points.push(doc.to_point(&self.collection_name)?);
        }

        self.client
            .upsert_points(&self.collection_name, None, points, None)
            .await?;
        Ok(())
    }

    /// Delete a document by ID
    pub async fn delete_document(&self, id: &str) -> Result<()> {
        let point_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, id.as_bytes()).to_string();
        let selector: PointsSelector = vec![PointId::from(point_id)].into();
        self.client
            .delete_points(&self.collection_name, None, &selector, None)
            .await?;
        Ok(())
    }

    /// Search (Full-text fallback for legacy Rust callers)
    pub async fn search(
        &self,
        query_text: &str,
        _filter_str: Option<&str>,
        limit: Option<usize>,
    ) -> Result<Vec<IntentDocument>> {
        let mut filter = None;

        if !query_text.is_empty() {
            // Full-text match on title
            filter = Some(Filter::all(vec![Condition::matches(
                "title",
                query_text.to_string(),
            )]));
        }

        let result = self
            .client
            .search_points(&SearchPoints {
                collection_name: self.collection_name.clone(),
                vector: vec![0.0; 384], // Dummy vector for payload-only search
                filter,
                limit: limit.unwrap_or(30) as u64,
                with_payload: Some(true.into()),
                ..Default::default()
            })
            .await?;

        let mut docs = Vec::new();
        for point in result.result {
            let doc_json = serde_json::to_value(point.payload)?;
            let doc: IntentDocument = serde_json::from_value(doc_json)?;
            docs.push(doc);
        }

        Ok(docs)
    }

    /// Vector Search (Primary method for Python Query Layer)
    pub async fn search_vector(
        &self,
        query_vector: Vec<f32>,
        filter: Option<Filter>,
        limit: usize,
    ) -> Result<Vec<IntentDocument>> {
        let result = self
            .client
            .search_points(&SearchPoints {
                collection_name: self.collection_name.clone(),
                vector: query_vector,
                filter,
                limit: limit as u64,
                with_payload: Some(true.into()),
                ..Default::default()
            })
            .await?;

        let mut docs = Vec::new();
        for point in result.result {
            let doc_json = serde_json::to_value(point.payload)?;
            let doc: IntentDocument = serde_json::from_value(doc_json)?;
            docs.push(doc);
        }

        Ok(docs)
    }

    /// Batch update documents
    pub async fn batch_update_documents(&self, docs: &[IntentDocument]) -> Result<()> {
        self.index_documents(docs).await
    }
}

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

    #[test]
    fn test_document_creation() {
        let vector = vec![0.1; 384];
        let doc = IntentDocument::new(
            "test-1".to_string(),
            "Test Title".to_string(),
            "Test content".to_string(),
            "https://example.com".to_string(),
            "test-source".to_string(),
            "tech".to_string(),
            0.8,
            0.9,
            vector,
        );

        assert_eq!(doc.id, "test-1");
        assert!(doc.vector.is_some());
    }
}