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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
"""
database.py - SQLite Database Manager for Dressa App

Handles:
- User session management
- Upload tracking
- Rating storage
- Corpus growth tracking
"""

import sqlite3
import uuid
import json
from datetime import datetime
from pathlib import Path
import os
from typing import List, Optional, Dict, Any
from contextlib import contextmanager
import logging

logger = logging.getLogger(__name__)

# Default database path
APP_DIR = Path(__file__).parent.resolve()
DEFAULT_DB_PATH = Path(
    os.getenv("DRESSA_DB_PATH", str(APP_DIR / "user_study.db"))
)


class Database:
    """SQLite database manager for user study data."""

    def __init__(self, db_path: Optional[Path] = None):
        """
        Initialize database connection.

        Args:
            db_path: Path to SQLite database file
        """
        self.db_path = Path(db_path) if db_path else DEFAULT_DB_PATH
        self.db_path.parent.mkdir(parents=True, exist_ok=True)
        self._init_db()

    def _init_db(self):
        """Create tables if they don't exist."""
        with self._get_connection() as conn:
            cursor = conn.cursor()

            # Users table
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS users (
                    user_id TEXT PRIMARY KEY,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            """)

            # Uploads table (user's query images)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS uploads (
                    upload_id TEXT PRIMARY KEY,
                    user_id TEXT,
                    filepath TEXT,
                    uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    added_to_corpus INTEGER DEFAULT 0,
                    num_ratings INTEGER DEFAULT 0,
                    FOREIGN KEY (user_id) REFERENCES users(user_id)
                )
            """)

            # Ratings table (legacy, kept for backward compatibility)
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS ratings (
                    rating_id INTEGER PRIMARY KEY AUTOINCREMENT,
                    user_id TEXT,
                    upload_id TEXT,
                    result_image_path TEXT,
                    model TEXT,
                    rating TEXT,
                    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (user_id) REFERENCES users(user_id),
                    FOREIGN KEY (upload_id) REFERENCES uploads(upload_id)
                )
            """)

            # New evaluation_ratings table with provenance
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS evaluation_ratings (
                    rating_id INTEGER PRIMARY KEY AUTOINCREMENT,
                    user_id TEXT NOT NULL,
                    upload_id TEXT NOT NULL,
                    result_image_id TEXT NOT NULL,
                    rating TEXT NOT NULL,
                    provenance TEXT NOT NULL,
                    display_position INTEGER,
                    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            """)

            conn.commit()
            logger.info(f"Database initialized at {self.db_path}")

    @contextmanager
    def _get_connection(self):
        """Context manager for database connections."""
        conn = sqlite3.connect(self.db_path)
        conn.row_factory = sqlite3.Row
        try:
            yield conn
        finally:
            conn.close()

    # ==================== User Methods ====================

    def create_user(self) -> str:
        """
        Create a new user with a unique ID.

        Returns:
            user_id: UUID string for the new user
        """
        user_id = str(uuid.uuid4())

        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO users (user_id) VALUES (?)",
                (user_id,)
            )
            conn.commit()

        logger.info(f"Created new user: {user_id}")
        return user_id

    def get_user(self, user_id: str) -> Optional[Dict]:
        """Get user by ID."""
        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute(
                "SELECT * FROM users WHERE user_id = ?",
                (user_id,)
            )
            row = cursor.fetchone()
            return dict(row) if row else None

    def user_exists(self, user_id: str) -> bool:
        """Check if a user exists."""
        return self.get_user(user_id) is not None

    # ==================== Upload Methods ====================

    def create_upload(self, user_id: str, filepath: str) -> str:
        """
        Record a new image upload.

        Args:
            user_id: ID of the user who uploaded
            filepath: Path where the uploaded image is stored

        Returns:
            upload_id: UUID string for the new upload
        """
        upload_id = str(uuid.uuid4())

        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute(
                """INSERT INTO uploads (upload_id, user_id, filepath)
                   VALUES (?, ?, ?)""",
                (upload_id, user_id, filepath)
            )
            conn.commit()

        logger.info(f"Created upload {upload_id} for user {user_id}")
        return upload_id

    def get_upload(self, upload_id: str) -> Optional[Dict]:
        """Get upload by ID."""
        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute(
                "SELECT * FROM uploads WHERE upload_id = ?",
                (upload_id,)
            )
            row = cursor.fetchone()
            return dict(row) if row else None

    def get_user_uploads(self, user_id: str) -> List[Dict]:
        """Get all uploads for a user."""
        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute(
                """SELECT * FROM uploads
                   WHERE user_id = ?
                   ORDER BY uploaded_at DESC""",
                (user_id,)
            )
            return [dict(row) for row in cursor.fetchall()]

    def mark_added_to_corpus(self, upload_id: str):
        """Mark an upload as added to the corpus."""
        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute(
                """UPDATE uploads
                   SET added_to_corpus = 1
                   WHERE upload_id = ?""",
                (upload_id,)
            )
            conn.commit()

        logger.info(f"Marked upload {upload_id} as added to corpus")

    def increment_upload_ratings(self, upload_id: str) -> int:
        """
        Increment the rating count for an upload.

        Returns:
            New rating count
        """
        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute(
                """UPDATE uploads
                   SET num_ratings = num_ratings + 1
                   WHERE upload_id = ?""",
                (upload_id,)
            )
            cursor.execute(
                "SELECT num_ratings FROM uploads WHERE upload_id = ?",
                (upload_id,)
            )
            conn.commit()
            result = cursor.fetchone()
            return result['num_ratings'] if result else 0

    # ==================== Rating Methods ====================

    def save_rating(
        self,
        user_id: str,
        upload_id: str,
        result_image_path: str,
        model: str,
        rating: str
    ) -> int:
        """
        Save a user's rating for a result image.

        Args:
            user_id: ID of the user
            upload_id: ID of the query image upload
            result_image_path: Path to the result image being rated
            model: Which model returned this result
            rating: 'similar' or 'not_similar'

        Returns:
            rating_id: ID of the new rating
        """
        if rating not in ('similar', 'not_similar'):
            raise ValueError(f"Invalid rating: {rating}. "
                           f"Must be 'similar' or 'not_similar'")

        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute(
                """INSERT INTO ratings
                   (user_id, upload_id, result_image_path, model, rating)
                   VALUES (?, ?, ?, ?, ?)""",
                (user_id, upload_id, result_image_path, model, rating)
            )
            conn.commit()
            rating_id = cursor.lastrowid

        # Increment upload's rating count
        self.increment_upload_ratings(upload_id)

        logger.info(f"Saved rating {rating_id}: {rating} for {model}")
        return rating_id

    def get_upload_ratings(self, upload_id: str) -> List[Dict]:
        """Get all ratings for an upload."""
        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute(
                """SELECT * FROM ratings
                   WHERE upload_id = ?
                   ORDER BY timestamp""",
                (upload_id,)
            )
            return [dict(row) for row in cursor.fetchall()]

    def get_user_ratings(self, user_id: str) -> List[Dict]:
        """Get all ratings by a user."""
        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute(
                """SELECT * FROM ratings
                   WHERE user_id = ?
                   ORDER BY timestamp""",
                (user_id,)
            )
            return [dict(row) for row in cursor.fetchall()]

    def has_rated(self, upload_id: str, result_image_path: str) -> bool:
        """Check if a result image has already been rated for this upload."""
        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute(
                """SELECT COUNT(*) as count FROM ratings
                   WHERE upload_id = ? AND result_image_path = ?""",
                (upload_id, result_image_path)
            )
            result = cursor.fetchone()
            return result['count'] > 0

    # ==================== Evaluation Rating Methods ====================

    def save_evaluation_rating(
        self,
        user_id: str,
        upload_id: str,
        result_image_id: str,
        rating: str,
        provenance: dict,
        display_position: int
    ):
        """
        Save a user's evaluation rating with provenance information.

        Args:
            user_id: ID of the user
            upload_id: ID of the query image upload
            result_image_id: Path/ID of the result image being rated
            rating: 'similar' or 'not_similar'
            provenance: Dict mapping model_name -> rank (1-indexed)
            display_position: Position in the shuffled display order
        """
        if rating not in ('similar', 'not_similar'):
            raise ValueError(f"Invalid rating: {rating}. "
                           f"Must be 'similar' or 'not_similar'")

        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("""
                INSERT INTO evaluation_ratings
                (user_id, upload_id, result_image_id, rating, provenance, display_position)
                VALUES (?, ?, ?, ?, ?, ?)
            """, (user_id, upload_id, result_image_id, rating,
                  json.dumps(provenance), display_position))
            conn.commit()

        # Increment upload's rating count
        self.increment_upload_ratings(upload_id)

        logger.info(f"Saved evaluation rating: {rating} for {result_image_id} "
                   f"(position {display_position}, provenance: {provenance})")

    def get_evaluation_ratings(self, upload_id: str) -> List[Dict]:
        """Get all evaluation ratings for an upload."""
        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute(
                """SELECT * FROM evaluation_ratings
                   WHERE upload_id = ?
                   ORDER BY timestamp""",
                (upload_id,)
            )
            rows = [dict(row) for row in cursor.fetchall()]
            # Parse provenance JSON
            for row in rows:
                row['provenance'] = json.loads(row['provenance'])
            return rows

    # ==================== Analytics Methods ====================

    def get_stats(self) -> Dict[str, Any]:
        """Get overall statistics."""
        with self._get_connection() as conn:
            cursor = conn.cursor()

            stats = {}

            # Total users
            cursor.execute("SELECT COUNT(*) as count FROM users")
            stats['total_users'] = cursor.fetchone()['count']

            # Total uploads
            cursor.execute("SELECT COUNT(*) as count FROM uploads")
            stats['total_uploads'] = cursor.fetchone()['count']

            # Uploads added to corpus
            cursor.execute(
                "SELECT COUNT(*) as count FROM uploads WHERE added_to_corpus = 1"
            )
            stats['corpus_additions'] = cursor.fetchone()['count']

            # Total ratings
            cursor.execute("SELECT COUNT(*) as count FROM ratings")
            stats['total_ratings'] = cursor.fetchone()['count']

            # Ratings by model
            cursor.execute(
                """SELECT model, COUNT(*) as count
                   FROM ratings GROUP BY model"""
            )
            stats['ratings_by_model'] = {
                row['model']: row['count']
                for row in cursor.fetchall()
            }

            # Similar vs not similar
            cursor.execute(
                """SELECT rating, COUNT(*) as count
                   FROM ratings GROUP BY rating"""
            )
            stats['ratings_breakdown'] = {
                row['rating']: row['count']
                for row in cursor.fetchall()
            }

            return stats

    def export_ratings_csv(self, output_path: str):
        """Export all ratings to CSV for analysis."""
        import csv

        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute("""
                SELECT r.*, u.filepath as query_image_path
                FROM ratings r
                JOIN uploads u ON r.upload_id = u.upload_id
                ORDER BY r.timestamp
            """)
            rows = cursor.fetchall()

        with open(output_path, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerow([
                'rating_id', 'user_id', 'upload_id', 'query_image_path',
                'result_image_path', 'model', 'rating', 'timestamp'
            ])
            for row in rows:
                writer.writerow([
                    row['rating_id'], row['user_id'], row['upload_id'],
                    row['query_image_path'], row['result_image_path'],
                    row['model'], row['rating'], row['timestamp']
                ])

        logger.info(f"Exported {len(rows)} ratings to {output_path}")


# Convenience function for testing
def test_database():
    """Test database operations."""
    import tempfile
    import os

    # Use temp database for testing
    test_db = Path(tempfile.gettempdir()) / "dressa_test.db"
    if test_db.exists():
        os.remove(test_db)

    db = Database(test_db)

    print("Testing database.py...")

    # Test user creation
    user_id = db.create_user()
    print(f"  Created user: {user_id[:8]}...")

    # Test upload creation
    upload_id = db.create_upload(user_id, "/path/to/test.jpg")
    print(f"  Created upload: {upload_id[:8]}...")

    # Test rating
    rating_id = db.save_rating(
        user_id, upload_id, "/path/to/result.jpg",
        "openai_clip", "similar"
    )
    print(f"  Saved rating: {rating_id}")

    # Test stats
    stats = db.get_stats()
    print(f"  Stats: {stats}")

    # Cleanup
    os.remove(test_db)
    print("\nDatabase tests complete!")


if __name__ == "__main__":
    test_database()