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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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
"""
πŸ—„οΈ DATABASE MODULE - PostgreSQL Support
Extended version of database.py with PostgreSQL support for production deployment
"""

import os
import uuid
from datetime import datetime
from typing import Dict, List, Optional, Tuple
import json

# =============================================================================
# DATABASE CONFIGURATION
# =============================================================================

# Get database URL from environment
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///carpet_analysis.db")

# Determine database type
if DATABASE_URL.startswith("postgresql"):
    DATABASE_TYPE = "postgresql"
    import psycopg2
    from psycopg2.extras import RealDictCursor
    print(f"πŸ—„οΈ  Using PostgreSQL database")
    SCHEMA_PATH = "database_schema_postgres.sql"  # Use PostgreSQL schema
elif DATABASE_URL.startswith("sqlite"):
    DATABASE_TYPE = "sqlite"
    import sqlite3
    DATABASE_PATH = DATABASE_URL.replace("sqlite:///", "")
    print(f"πŸ—„οΈ  Using SQLite database: {DATABASE_PATH}")
    SCHEMA_PATH = "database_schema.sql"  # Use SQLite schema
else:
    # Default to SQLite
    DATABASE_TYPE = "sqlite"
    import sqlite3
    DATABASE_PATH = "carpet_analysis.db"
    print(f"πŸ—„οΈ  Using SQLite database (default): {DATABASE_PATH}")
    SCHEMA_PATH = "database_schema.sql"  # Use SQLite schema

# =============================================================================
# CONNECTION HELPERS
# =============================================================================

def get_connection():
    """Get database connection based on type"""
    if DATABASE_TYPE == "postgresql":
        return psycopg2.connect(DATABASE_URL)
    else:
        return sqlite3.connect(DATABASE_PATH)

def get_cursor(conn):
    """Get cursor with appropriate row factory"""
    if DATABASE_TYPE == "postgresql":
        return conn.cursor(cursor_factory=RealDictCursor)
    else:
        conn.row_factory = sqlite3.Row
        return conn.cursor()

# =============================================================================
# DATABASE INITIALIZATION
# =============================================================================

def init_database():
    """Initialize database dengan schema dari SQL file"""
    print("πŸ—„οΈ  Initializing database...")
    
    conn = get_connection()
    cursor = get_cursor(conn)
    
    # Load dan execute schema
    if os.path.exists(SCHEMA_PATH):
        with open(SCHEMA_PATH, 'r', encoding='utf-8') as f:
            schema = f.read()
            
            if DATABASE_TYPE == "postgresql":
                cursor.execute(schema)
            else:
                cursor.executescript(schema)
        
        print(f"βœ… Database schema loaded from {SCHEMA_PATH}")
    else:
        print(f"⚠️  Schema file not found: {SCHEMA_PATH}")
        print("   Creating basic schema...")
        create_basic_schema(cursor)
    
    conn.commit()
    conn.close()
    print(f"βœ… Database initialized: {DATABASE_TYPE}")


def create_basic_schema(cursor):
    """Create basic schema jika SQL file tidak ada"""
    if DATABASE_TYPE == "postgresql":
        # PostgreSQL version
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS analysis_history (
                id SERIAL PRIMARY KEY,
                analysis_id TEXT UNIQUE NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                material TEXT NOT NULL,
                material_confidence REAL NOT NULL,
                carpet_type TEXT NOT NULL,
                type_confidence REAL NOT NULL,
                carpet_coverage REAL NOT NULL,
                is_authentic BOOLEAN NOT NULL,
                confidence_level TEXT,
                price_min INTEGER,
                price_max INTEGER,
                total_processing_time REAL NOT NULL
            )
        """)
        
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS carpet_products (
                id SERIAL PRIMARY KEY,
                product_name TEXT UNIQUE NOT NULL,
                carpet_type TEXT NOT NULL,
                material TEXT NOT NULL,
                price_min INTEGER NOT NULL,
                price_max INTEGER NOT NULL,
                stock_status TEXT DEFAULT 'available'
            )
        """)
    else:
        # SQLite version (original)
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS analysis_history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                analysis_id TEXT UNIQUE NOT NULL,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                material TEXT NOT NULL,
                material_confidence REAL NOT NULL,
                carpet_type TEXT NOT NULL,
                type_confidence REAL NOT NULL,
                carpet_coverage REAL NOT NULL,
                is_authentic BOOLEAN NOT NULL,
                confidence_level TEXT,
                price_min INTEGER,
                price_max INTEGER,
                total_processing_time REAL NOT NULL
            )
        """)
        
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS carpet_products (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                product_name TEXT UNIQUE NOT NULL,
                carpet_type TEXT NOT NULL,
                material TEXT NOT NULL,
                price_min INTEGER NOT NULL,
                price_max INTEGER NOT NULL,
                stock_status TEXT DEFAULT 'available'
            )
        """)

# =============================================================================
# PRODUCT OPERATIONS
# =============================================================================

def get_all_products() -> List[Dict]:
    """Get semua produk karpet dari database"""
    conn = get_connection()
    cursor = get_cursor(conn)
    
    cursor.execute("""
        SELECT * FROM carpet_products 
        WHERE stock_status = 'available'
        ORDER BY carpet_type
    """)
    
    products = [dict(row) for row in cursor.fetchall()]
    conn.close()
    return products


def get_product_by_combination(material: str, carpet_type: str) -> Optional[Dict]:
    """Get produk berdasarkan kombinasi material + type"""
    conn = get_connection()
    cursor = get_cursor(conn)
    
    if DATABASE_TYPE == "postgresql":
        cursor.execute("""
            SELECT * FROM carpet_products 
            WHERE material = %s AND carpet_type = %s
            AND stock_status = 'available'
        """, (material, carpet_type))
    else:
        cursor.execute("""
            SELECT * FROM carpet_products 
            WHERE material = ? AND carpet_type = ?
            AND stock_status = 'available'
        """, (material, carpet_type))
    
    row = cursor.fetchone()
    conn.close()
    return dict(row) if row else None


def get_price_range(material: str, carpet_type: str) -> Optional[Tuple[int, int]]:
    """Get price range untuk kombinasi material + type"""
    product = get_product_by_combination(material, carpet_type)
    if product:
        return (product['price_min'], product['price_max'])
    return None

# =============================================================================
# ANALYSIS HISTORY OPERATIONS
# =============================================================================

def save_analysis_result(result: Dict) -> str:
    """
    Simpan hasil analisis ke database
    
    Returns:
        analysis_id: UUID untuk tracking
    """
    conn = get_connection()
    cursor = get_cursor(conn)
    
    analysis_id = str(uuid.uuid4())
    
    # Prepare query based on database type
    if DATABASE_TYPE == "postgresql":
        cursor.execute("""
            INSERT INTO analysis_history (
                analysis_id,
                mikro_image_path,
                makro_image_path,
                material,
                material_confidence,
                material_processing_time,
                carpet_coverage,
                segmentation_processing_time,
                carpet_type,
                type_confidence,
                type_processing_time,
                is_authentic,
                confidence_level,
                warning,
                reason,
                price_min,
                price_max,
                price_note,
                total_processing_time
            ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
        """, (
            analysis_id,
            result.get('mikro_image_path'),
            result.get('makro_image_path'),
            result['material'],
            result['material_confidence'],
            result.get('material_processing_time'),
            result['carpet_coverage'],
            result.get('segmentation_processing_time'),
            result['carpet_type'],
            result['type_confidence'],
            result.get('type_processing_time'),
            result['is_authentic'],
            result.get('confidence_level'),
            result.get('warning'),
            result.get('reason'),
            result.get('price_min'),
            result.get('price_max'),
            result.get('price_note'),
            result['total_processing_time']
        ))
    else:
        cursor.execute("""
            INSERT INTO analysis_history (
                analysis_id,
                mikro_image_path,
                makro_image_path,
                material,
                material_confidence,
                material_processing_time,
                carpet_coverage,
                segmentation_processing_time,
                carpet_type,
                type_confidence,
                type_processing_time,
                is_authentic,
                confidence_level,
                warning,
                reason,
                price_min,
                price_max,
                price_note,
                total_processing_time
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        """, (
            analysis_id,
            result.get('mikro_image_path'),
            result.get('makro_image_path'),
            result['material'],
            result['material_confidence'],
            result.get('material_processing_time'),
            result['carpet_coverage'],
            result.get('segmentation_processing_time'),
            result['carpet_type'],
            result['type_confidence'],
            result.get('type_processing_time'),
            result['is_authentic'],
            result.get('confidence_level'),
            result.get('warning'),
            result.get('reason'),
            result.get('price_min'),
            result.get('price_max'),
            result.get('price_note'),
            result['total_processing_time']
        ))
    
    conn.commit()
    conn.close()
    
    print(f"πŸ’Ύ Analysis saved to database: {analysis_id}")
    return analysis_id


def get_analysis_by_id(analysis_id: str) -> Optional[Dict]:
    """Get hasil analisis berdasarkan ID"""
    conn = get_connection()
    cursor = get_cursor(conn)
    
    if DATABASE_TYPE == "postgresql":
        cursor.execute("""
            SELECT * FROM analysis_history 
            WHERE analysis_id = %s
        """, (analysis_id,))
    else:
        cursor.execute("""
            SELECT * FROM analysis_history 
            WHERE analysis_id = ?
        """, (analysis_id,))
    
    row = cursor.fetchone()
    conn.close()
    return dict(row) if row else None


def get_recent_analyses(limit: int = 20) -> List[Dict]:
    """Get analisis terbaru"""
    conn = get_connection()
    cursor = get_cursor(conn)
    
    # Try to use view first, fallback to direct query
    try:
        if DATABASE_TYPE == "postgresql":
            cursor.execute("""
                SELECT * FROM recent_analyses
                LIMIT %s
            """, (limit,))
        else:
            cursor.execute("""
                SELECT * FROM recent_analyses
                LIMIT ?
            """, (limit,))
    except:
        # Fallback if view doesn't exist
        if DATABASE_TYPE == "postgresql":
            cursor.execute("""
                SELECT * FROM analysis_history
                ORDER BY created_at DESC
                LIMIT %s
            """, (limit,))
        else:
            cursor.execute("""
                SELECT * FROM analysis_history
                ORDER BY created_at DESC
                LIMIT ?
            """, (limit,))
    
    analyses = [dict(row) for row in cursor.fetchall()]
    conn.close()
    return analyses

# =============================================================================
# STATISTICS & REPORTING
# =============================================================================

def get_material_statistics() -> List[Dict]:
    """Get statistik per material"""
    conn = get_connection()
    cursor = get_cursor(conn)
    
    try:
        cursor.execute("SELECT * FROM material_statistics")
        stats = [dict(row) for row in cursor.fetchall()]
    except:
        # Fallback if view doesn't exist
        cursor.execute("""
            SELECT 
                material,
                COUNT(*) as total_analyses,
                SUM(CASE WHEN is_authentic THEN 1 ELSE 0 END) as authentic_count,
                SUM(CASE WHEN NOT is_authentic THEN 1 ELSE 0 END) as fake_count,
                ROUND(AVG(material_confidence) * 100, 2) as avg_confidence_pct,
                ROUND(AVG(total_processing_time), 3) as avg_processing_time
            FROM analysis_history
            GROUP BY material
        """)
        stats = [dict(row) for row in cursor.fetchall()]
    
    conn.close()
    return stats


def get_carpet_type_statistics() -> List[Dict]:
    """Get statistik per jenis karpet"""
    conn = get_connection()
    cursor = get_cursor(conn)
    
    try:
        cursor.execute("SELECT * FROM carpet_type_statistics")
        stats = [dict(row) for row in cursor.fetchall()]
    except:
        # Fallback if view doesn't exist
        cursor.execute("""
            SELECT 
                carpet_type,
                COUNT(*) as total_analyses,
                SUM(CASE WHEN is_authentic THEN 1 ELSE 0 END) as authentic_count,
                SUM(CASE WHEN NOT is_authentic THEN 1 ELSE 0 END) as fake_count,
                ROUND(AVG(type_confidence) * 100, 2) as avg_confidence_pct,
                ROUND(AVG(total_processing_time), 3) as avg_processing_time
            FROM analysis_history
            GROUP BY carpet_type
        """)
        stats = [dict(row) for row in cursor.fetchall()]
    
    conn.close()
    return stats


def get_overall_statistics() -> Dict:
    """Get statistik keseluruhan"""
    conn = get_connection()
    cursor = get_cursor(conn)
    
    # Total analyses
    cursor.execute("SELECT COUNT(*) as total FROM analysis_history")
    result = cursor.fetchone()
    total = result['total'] if DATABASE_TYPE == "postgresql" else result[0]
    
    # Authentic vs fake
    cursor.execute("""
        SELECT 
            COALESCE(SUM(CASE WHEN is_authentic THEN 1 ELSE 0 END), 0) as authentic,
            COALESCE(SUM(CASE WHEN NOT is_authentic THEN 1 ELSE 0 END), 0) as fake
        FROM analysis_history
    """)
    result = cursor.fetchone()
    auth_fake = (result['authentic'], result['fake']) if DATABASE_TYPE == "postgresql" else (result[0], result[1])
    
    # Average processing time
    cursor.execute("SELECT AVG(total_processing_time) as avg_time FROM analysis_history")
    result = cursor.fetchone()
    avg_time = result['avg_time'] if DATABASE_TYPE == "postgresql" else result[0]
    avg_time = avg_time or 0
    
    # Today's analyses
    if DATABASE_TYPE == "postgresql":
        cursor.execute("""
            SELECT COUNT(*) as today FROM analysis_history 
            WHERE DATE(created_at) = CURRENT_DATE
        """)
    else:
        cursor.execute("""
            SELECT COUNT(*) as today FROM analysis_history 
            WHERE DATE(created_at) = DATE('now')
        """)
    result = cursor.fetchone()
    today = result['today'] if DATABASE_TYPE == "postgresql" else result[0]
    
    conn.close()
    
    return {
        'total_analyses': total,
        'authentic_count': auth_fake[0] or 0,
        'fake_count': auth_fake[1] or 0,
        'avg_processing_time': round(avg_time, 3),
        'today_count': today
    }


def log_suspicious_pattern(analysis_id: str, pattern_type: str, 
                          severity: str, details: str):
    """Log pola mencurigakan untuk fraud detection"""
    conn = get_connection()
    cursor = get_cursor(conn)
    
    if DATABASE_TYPE == "postgresql":
        cursor.execute("""
            INSERT INTO suspicious_patterns (
                analysis_id, pattern_type, severity, details
            ) VALUES (%s, %s, %s, %s)
        """, (analysis_id, pattern_type, severity, details))
    else:
        cursor.execute("""
            INSERT INTO suspicious_patterns (
                analysis_id, pattern_type, severity, details
            ) VALUES (?, ?, ?, ?)
        """, (analysis_id, pattern_type, severity, details))
    
    conn.commit()
    conn.close()
    
    print(f"⚠️  Suspicious pattern logged: {pattern_type} ({severity})")

# =============================================================================
# EXPORT FUNCTIONS
# =============================================================================

def export_to_json(analysis_id: str, output_path: str):
    """Export hasil analisis ke JSON file"""
    result = get_analysis_by_id(analysis_id)
    if result:
        # Convert datetime to string
        if 'created_at' in result:
            result['created_at'] = str(result['created_at'])
        
        with open(output_path, 'w', encoding='utf-8') as f:
            json.dump(result, f, indent=2, ensure_ascii=False)
        print(f"πŸ“„ Exported to {output_path}")
    else:
        print(f"❌ Analysis not found: {analysis_id}")

# =============================================================================
# MAIN - TEST DATABASE
# =============================================================================

if __name__ == "__main__":
    print()
    print("="*70)
    print("πŸ—„οΈ  TESTING DATABASE MODULE (PostgreSQL Support)")
    print("="*70)
    print(f"Database Type: {DATABASE_TYPE}")
    print(f"Database URL: {DATABASE_URL[:50]}...")
    print("="*70)
    print()
    
    # Initialize database
    init_database()
    print()
    
    # Test: Get all products
    print("πŸ“¦ Products in database:")
    products = get_all_products()
    for p in products:
        print(f"   β€’ {p['product_name']}: Rp {p['price_min']:,} - Rp {p['price_max']:,}")
    print()
    
    # Test: Get price for specific combination
    print("πŸ’° Price check:")
    price = get_price_range('Polypropylene', 'Asia')
    if price:
        print(f"   Asia + Polypropylene: Rp {price[0]:,} - Rp {price[1]:,}")
    print()
    
    # Test: Get statistics
    print("πŸ“Š Overall Statistics:")
    stats = get_overall_statistics()
    print(f"   Total: {stats['total_analyses']}")
    print(f"   Authentic: {stats['authentic_count']}")
    print(f"   Fake: {stats['fake_count']}")
    print(f"   Avg time: {stats['avg_processing_time']}s")
    print()
    
    print("="*70)
    print("βœ… Database test complete!")
    print("="*70)
    print()