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
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
"""
Pure Python SDK Client for Image Search.

This SDK uses the actual services from app/services/ directly,
providing the same functionality as the API but as a Python library.

Usage:
    from image_search_sdk import ImageSearchClient
    
    # Initialize with your vector store choice
    client = ImageSearchClient(
        data_dir="./my_data",
        model_name="clip-ViT-L-14",
        vector_store_type="pinecone",  # or qdrant, weaviate, chromadb, pgvector
        vector_store_config={
            "api_key": "your_pinecone_key",
            "cloud": "aws",
            "region": "us-east-1"
        }
    )
    
    # Connect your product database
    client.connect_database(
        connection_string="sqlite:///products.db",
        id_column="product_id",
        title_column="name"
    )
    
    # First-time: Index all existing products
    stats = client.initialize()
    
    # Ongoing: Add new products (embeddings generated automatically)
    client.add_product(new_product)
    
    # Search by image
    results = client.search_by_image("query.jpg")
"""

import time
from typing import List, Optional, Union, Dict, Any
from pathlib import Path
from PIL import Image
import io

from .models import Product, SearchResult, SearchOptions
from .exceptions import ImageSearchError, ValidationError
from .schema_mapper import SchemaMapper, SchemaMappingBuilder


class ImageSearchClient:
    """
    Pure Python SDK client that uses services directly.
    
    No API calls - everything runs locally using the actual services
    from app/services/ (CLIP, vector stores, reranking, etc.)
    """
    
    def __init__(
        self,
        data_dir: str = "./sdk_data",
        model_name: str = "clip-ViT-L-14",
        vector_store_type: str = "chromadb",  # pinecone, qdrant, weaviate, chromadb, pgvector
        vector_store_config: Optional[Dict[str, Any]] = None
    ):
        """
        Initialize the Image Search SDK.
        
        Args:
            data_dir: Directory for storing data
            model_name: CLIP model ("clip-ViT-B-32" or "clip-ViT-L-14")
            vector_store_type: Vector store (pinecone, qdrant, weaviate, chromadb, pgvector)
            vector_store_config: Vector store connection parameters
            
        Examples:
            # Pinecone (Managed, Serverless)
            client = ImageSearchClient(
                vector_store_type="pinecone",
                vector_store_config={"api_key": "xxx", "cloud": "aws", "region": "us-east-1"}
            )
            
            # Qdrant (Self-hosted)
            client = ImageSearchClient(
                vector_store_type="qdrant",
                vector_store_config={"mode": "local", "path": "./qdrant_data"}
            )
            
            # ChromaDB (Simple, No setup)
            client = ImageSearchClient(
                vector_store_type="chromadb",
                vector_store_config={"mode": "local", "path": "./chroma_data"}
            )
        """
        import sys
        from pathlib import Path as P
        
        # Add app/services to Python path
        app_services_path = P(__file__).parent.parent.parent.parent / "app"
        if str(app_services_path) not in sys.path:
            sys.path.insert(0, str(app_services_path))
        
        # Import unified services
        from services.ai.clip_service import ClipEmbeddingService
        from services.vector_stores.manager import create_vector_store_manager
        from services.database import create_database_adapter as _create_db_adapter, DatabaseConfig as _DatabaseConfig, DatabaseError
        
        # Store for later use
        self._create_database_adapter = _create_db_adapter
        self._DatabaseConfig = _DatabaseConfig
        self.DatabaseError = DatabaseError
        
        self.data_dir = Path(data_dir)
        self.data_dir.mkdir(exist_ok=True)
        
        # Initialize CLIP service
        self.clip_service = ClipEmbeddingService(model_name=model_name)
        
        # Initialize vector store manager
        self.vector_store_manager = create_vector_store_manager(
            store_type=vector_store_type,
            connection_params=vector_store_config or {},
            clip_service=self.clip_service,
            collection_name="product_embeddings",
            state_file=str(self.data_dir / "init_state.json")
        )
        
        self.database_adapter: Optional[DatabaseAdapter] = None
        self.schema_mapper: Optional[SchemaMapper] = None
        self.product_monitor: Optional[Any] = None  # Auto-monitor for new products
    
    def connect_database(
        self,
        connection_string: str,
        table_name: str = "products",
        schema_mapping: Optional[Dict[str, Any]] = None,
        **column_mappings
    ) -> None:
        """
        Connect to your existing product database with flexible schema mapping.
        
        Args:
            connection_string: Database connection string
            table_name: Name of your products table
            schema_mapping: Complete custom schema mapping dict for complex structures
            **column_mappings: Simple column mappings (id_column, title_column, etc.)
        
        Examples:
            # Simple mapping
            client.connect_database(
                "sqlite:///products.db",
                id_column="product_id",
                title_column="name",
                image_url_column="image",
                category_column="cat",
                price_column="price"
            )
            
            # Complex custom mapping
            client.connect_database(
                "postgresql://user:pass@localhost/db",
                schema_mapping={
                    "table_name": "products",
                    "id_mapping": {"source_column": "sku", "target_field": "id"},
                    "title_mapping": {"source_column": "product_name", "target_field": "title"},
                    ...
                }
            )
        """
        # Build schema mapping
        if schema_mapping:
            schema = SchemaMappingBuilder.from_dict(schema_mapping)
        else:
            # Create simple mapping from keyword arguments
            schema = SchemaMappingBuilder.create_simple_mapping(
                table_name=table_name,
                id_column=column_mappings.get('id_column', 'id'),
                title_column=column_mappings.get('title_column', 'title'),
                image_url_column=column_mappings.get('image_url_column', 'image_url'),
                category_column=column_mappings.get('category_column'),
                brand_column=column_mappings.get('brand_column'),
                price_column=column_mappings.get('price_column'),
                rating_column=column_mappings.get('rating_column'),
                description_column=column_mappings.get('description_column')
            )
        
        self.schema_mapper = SchemaMapper(schema)
        
        # Create database adapter
        config = self._DatabaseConfig(
            connection_string=connection_string,
            table_name=table_name,
            id_column=column_mappings.get('id_column', 'id'),
            title_column=column_mappings.get('title_column', 'title'),
            image_url_column=column_mappings.get('image_url_column', 'image_url')
        )
        
        self.database_adapter = self._create_database_adapter(config)
        self.database_adapter.connect()
    
    def enable_auto_monitor(self, poll_interval: int = 60, enable: bool = True):
        """
        Enable automatic monitoring for new products.
        
        When enabled, the system will automatically detect new products
        added to your database and generate embeddings for them.
        
        Args:
            poll_interval: How often to check for new products (seconds)
            enable: True to enable, False to disable
        """
        if not self.database_adapter:
            raise self.DatabaseError("Connect database first")
        
        if enable:
            # Import monitor
            from services.database.product_monitor import ProductMonitor
            
            # Create and start monitor
            self.product_monitor = ProductMonitor(
                database_adapter=self.database_adapter,
                vector_store_manager=self.vector_store_manager,
                poll_interval=poll_interval,
                batch_size=10
            )
            
            self.product_monitor.start()
        else:
            # Stop monitoring
            if self.product_monitor:
                self.product_monitor.stop()
                self.product_monitor = None
    
    def initialize(self, batch_size: int = 50) -> Dict[str, Any]:
        """
        First-time initialization: Generate embeddings for ALL existing products.
        
        This should be called once after connecting to your database.
        Progress is saved, so you can resume if interrupted.
        
        Args:
            batch_size: Number of products to process in each batch
            
        Returns:
            Dictionary with indexing statistics
        """
        if not self.database_adapter:
            raise self.DatabaseError("No database connected. Call connect_database() first.")
        
        start_time = time.time()
        
        # Use vector store manager for initialization
        stats = self.vector_store_manager.initialize_from_database(
            products_iterator=self.database_adapter.get_all_products(),
            batch_size=batch_size,
            progress_callback=None  # Can add progress callback if needed
        )
        
        duration = time.time() - start_time
        stats['duration_seconds'] = duration
        stats['products_per_second'] = stats['indexed_products'] / duration if duration > 0 else 0
        
        return stats
    
    def add_product(self, product: Product) -> bool:
        """
        Add a new product with automatic embedding generation.
        
        Embeddings are generated automatically when you add products.
        
        Args:
            product: Product to add
            
        Returns:
            True if successful
        """
        return self.vector_store_manager.add_product(product)
    
    def search_by_image(
        self,
        image_path: Union[str, Path],
        options: Optional[SearchOptions] = None
    ) -> List[SearchResult]:
        """
        Search for similar products using an image.
        
        Args:
            image_path: Path to the query image
            options: Search options and filters
            
        Returns:
            List of search results
        """
        if options is None:
            options = SearchOptions()
        
        try:
            # Load and encode image
            image = Image.open(image_path).convert("RGB")
            query_embedding = self.clip_service.encode_image(image)
            
            # Build filters
            filters = {}
            if options.category:
                filters['category'] = options.category
            if options.brand:
                filters['brand'] = options.brand
            
            # Search using vector store manager
            results = self.vector_store_manager.search(
                query_embedding=query_embedding,
                top_k=options.top_k,
                filters=filters if filters else None
            )
            
            # Convert to SearchResult objects
            search_results = []
            for result in results:
                product = Product(
                    id=result['product_id'],
                    title=result['metadata'].get('title', ''),
                    image_url='',
                    category=result['metadata'].get('category'),
                    brand=result['metadata'].get('brand'),
                    price=result['metadata'].get('price'),
                    rating=result['metadata'].get('rating')
                )
                
                search_results.append(SearchResult(
                    product=product,
                    similarity_score=result['score'],
                    rank=len(search_results) + 1,
                    search_time_ms=0
                ))
            
            return search_results
            
        except Exception as e:
            raise ImageSearchError(f"Image search failed: {e}")
    
    def search_by_text(
        self,
        query: str,
        options: Optional[SearchOptions] = None
    ) -> List[SearchResult]:
        """
        Search for products using text query.
        
        Args:
            query: Text search query
            options: Search options and filters
            
        Returns:
            List of search results
        """
        if options is None:
            options = SearchOptions()
        
        try:
            # Generate text embedding
            query_embedding = self.clip_service.encode_text(query)
            
            # Build filters
            filters = {}
            if options.category:
                filters['category'] = options.category
            if options.brand:
                filters['brand'] = options.brand
            
            # Search using vector store manager
            results = self.vector_store_manager.search(
                query_embedding=query_embedding,
                top_k=options.top_k,
                filters=filters if filters else None
            )
            
            # Convert to SearchResult objects
            search_results = []
            for result in results:
                product = Product(
                    id=result['product_id'],
                    title=result['metadata'].get('title', ''),
                    image_url='',
                    category=result['metadata'].get('category'),
                    brand=result['metadata'].get('brand'),
                    price=result['metadata'].get('price'),
                    rating=result['metadata'].get('rating')
                )
                
                search_results.append(SearchResult(
                    product=product,
                    similarity_score=result['score'],
                    rank=len(search_results) + 1,
                    search_time_ms=0
                ))
            
            return search_results
            
        except Exception as e:
            raise ImageSearchError(f"Text search failed: {e}")
    
    def update_product(self, product: Product) -> bool:
        """
        Update an existing product - regenerates embeddings automatically.
        
        Args:
            product: Updated product
            
        Returns:
            True if successful
        """
        return self.vector_store_manager.update_product(product)
    
    def delete_product(self, product_id: str) -> bool:
        """
        Delete a product and its embeddings.
        
        Args:
            product_id: ID of product to delete
            
        Returns:
            True if successful
        """
        return self.vector_store_manager.delete_product(product_id)
    
    def get_stats(self) -> Dict[str, Any]:
        """
        Get system statistics.
        
        Returns:
            Dictionary with system stats
        """
        return self.vector_store_manager.get_stats()
    
    def close(self) -> None:
        """Close all connections and cleanup resources."""
        # Stop monitoring
        if self.product_monitor:
            self.product_monitor.stop()
        
        # Close database
        if self.database_adapter:
            self.database_adapter.disconnect()
        
        # Close vector store
        if self.vector_store_manager:
            self.vector_store_manager.close()