File size: 43,465 Bytes
49b5e1e
 
 
 
 
6848f57
 
49b5e1e
 
 
87f9058
 
 
49b5e1e
 
 
 
 
 
 
87f9058
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49b5e1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0047f3c
49b5e1e
0047f3c
49b5e1e
 
 
 
 
 
 
 
 
 
 
 
 
0183b1e
 
 
 
49b5e1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0183b1e
 
 
 
49b5e1e
 
 
 
 
 
 
 
 
 
 
 
 
a59cff0
49b5e1e
6848f57
 
 
 
 
 
 
 
 
 
 
 
 
 
22f58a9
 
6848f57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22f58a9
6848f57
 
 
 
 
 
 
 
 
22f58a9
6848f57
 
22f58a9
6848f57
 
 
 
 
 
 
 
22f58a9
 
6848f57
 
 
 
 
 
 
 
 
 
 
 
22f58a9
 
 
 
 
6848f57
 
 
 
 
 
 
 
 
 
 
 
 
 
22f58a9
6848f57
 
 
 
 
 
22f58a9
6848f57
0fb9b06
 
6848f57
0fb9b06
 
 
 
 
 
 
 
 
 
22f58a9
0fb9b06
22f58a9
0fb9b06
22f58a9
6848f57
0fb9b06
 
22f58a9
 
 
6848f57
22f58a9
 
49b5e1e
87f9058
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7ddf76
87f9058
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7ddf76
87f9058
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ebd872
87f9058
 
 
 
 
2ebd872
 
 
87f9058
 
2ebd872
 
87f9058
 
2ebd872
87f9058
 
 
 
 
 
2ebd872
 
87f9058
 
 
 
 
 
a7ddf76
87f9058
 
 
 
 
2ebd872
 
 
 
 
87f9058
 
 
 
 
 
 
 
 
 
 
2ebd872
 
 
 
 
 
 
87f9058
2ebd872
87f9058
 
 
 
 
49b5e1e
 
 
 
 
 
 
 
c56d2a1
 
 
 
 
 
 
 
 
 
49b5e1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0183b1e
6848f57
0183b1e
 
 
49b5e1e
0183b1e
49b5e1e
 
 
c675c5a
 
 
 
 
 
 
9a427d9
c675c5a
49b5e1e
 
 
 
0183b1e
 
 
 
 
 
 
 
c675c5a
 
 
9a427d9
c675c5a
0183b1e
 
6848f57
 
0183b1e
 
 
49b5e1e
0183b1e
 
 
c675c5a
0183b1e
 
 
c675c5a
 
6848f57
 
c675c5a
 
 
 
9a427d9
c675c5a
0183b1e
 
6848f57
 
0183b1e
 
 
 
 
6848f57
 
 
 
49b5e1e
 
 
 
 
 
 
87f9058
 
49b5e1e
87f9058
 
 
 
 
49b5e1e
 
 
 
 
87f9058
571cdaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22f58a9
 
571cdaa
22f58a9
 
 
 
 
 
 
 
 
 
 
 
571cdaa
 
22f58a9
 
 
 
 
571cdaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fb9b06
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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
""" 
MongoDB database connection and logging utilities, including admin media click logging. 
""" 
import os 
import logging 
from datetime import datetime, timedelta
from typing import Optional, Dict, Any, Union, List
from bson import ObjectId 
from pymongo import MongoClient 
from pymongo.errors import ConnectionFailure, ServerSelectionTimeoutError 

logger = logging.getLogger(__name__)

# MongoDB connection 
_client: Optional[MongoClient] = None 
_db = None 

# Admin MongoDB connection (media_clicks) 
_admin_client: Optional[MongoClient] = None 
_admin_db = None 

def get_mongodb_client() -> Optional[MongoClient]:
    """Get or create MongoDB client"""
    global _client
    if _client is None:
        mongodb_uri = os.getenv("MONGODB_URI")
        if not mongodb_uri:
            logger.warning("MONGODB_URI environment variable not set. MongoDB features will be disabled.")
            return None
        try:
            _client = MongoClient(
                mongodb_uri,
                serverSelectionTimeoutMS=5000,
                connectTimeoutMS=5000
            )
            # Test connection
            _client.admin.command('ping')
            logger.info("MongoDB connection established successfully")
        except (ConnectionFailure, ServerSelectionTimeoutError) as e:
            logger.error("Failed to connect to MongoDB: %s", str(e))
            _client = None
    return _client

def get_database():
    """Get database instance"""
    global _db
    if _db is None:
        client = get_mongodb_client()
        if client:
            db_name = os.getenv("MONGODB_DB_NAME", "colorization_db")
            _db = client[db_name]
        else:
            logger.warning("MongoDB client not available")
    return _db


def get_admin_client() -> Optional[MongoClient]: 
    """Get or create admin MongoDB client (for media_clicks collection).""" 
    global _admin_client 
    if _admin_client is None: 
        mongodb_uri = os.getenv("MONGODB_ADMIN") 
        if not mongodb_uri: 
            logger.warning("MONGODB_ADMIN environment variable not set. Admin MongoDB features will be disabled.") 
            return None 
        try: 
            _admin_client = MongoClient( 
                mongodb_uri, 
                serverSelectionTimeoutMS=5000, 
                connectTimeoutMS=5000, 
            ) 
            _admin_client.admin.command("ping") 
            logger.info("Admin MongoDB connection established successfully") 
        except (ConnectionFailure, ServerSelectionTimeoutError) as exc: 
            logger.error("Failed to connect to Admin MongoDB: %s", str(exc)) 
            _admin_client = None 
    return _admin_client 


def get_admin_database(): 
    """Get admin database instance.""" 
    global _admin_db 
    if _admin_db is None: 
        client = get_admin_client() 
        if client: 
            db_name = os.getenv("MONGODB_ADMIN_DB_NAME", "adminPanel") 
            _admin_db = client[db_name] 
            logger.info("Using admin database: %s", db_name)
        else: 
            logger.warning("Admin MongoDB client not available") 
    return _admin_db 


def _normalize_object_id(raw_value: Optional[Union[str, int, ObjectId]]) -> ObjectId: 
    """Normalize user id inputs into a deterministic ObjectId.""" 
    if isinstance(raw_value, ObjectId): 
        return raw_value 

    if raw_value is None: 
        return ObjectId() 

    # Handle empty strings as None
    if isinstance(raw_value, str) and not raw_value.strip():
        return ObjectId()

    try: 
        if isinstance(raw_value, int) or (isinstance(raw_value, str) and raw_value.strip().lstrip("-").isdigit()): 
            int_value = int(str(raw_value).strip()) 
            hex_str = format(abs(int_value), "x").zfill(24)[-24:] 
            if ObjectId.is_valid(hex_str): 
                return ObjectId(hex_str) 
    except Exception as exc:  # pragma: no cover - defensive 
        logger.debug("Numeric user id normalization failed: %s", str(exc)) 

    if isinstance(raw_value, str): 
        candidate = raw_value.strip() 
        if ObjectId.is_valid(candidate): 
            return ObjectId(candidate) 

    return ObjectId() 


def _objectid_from_any(value: str) -> ObjectId: 
    """Convert arbitrary string into an ObjectId deterministically when possible.""" 
    if ObjectId.is_valid(value): 
        return ObjectId(value) 
    try: 
        hex_str = value.encode("utf-8").hex().zfill(24)[-24:] 
        if ObjectId.is_valid(hex_str): 
            return ObjectId(hex_str) 
    except Exception as exc:  # pragma: no cover - defensive 
        logger.debug("Category id normalization failed: %s", str(exc)) 
    return ObjectId() 


def _resolve_category_id( 
    category_id: Optional[str], 
    endpoint_path: Optional[str], 
    default_category_id: Optional[str], 
) -> ObjectId: 
    """Pick category id from explicit value, endpoint default, or fallback.""" 
    # Handle empty strings as None
    if isinstance(category_id, str) and not category_id.strip():
        category_id = None
        
    endpoint_map = { 
        "colorization": os.getenv("DEFAULT_CATEGORY_COLORIZATION"), 
        "upload": os.getenv("DEFAULT_CATEGORY_COLORIZATION"), 
        "colorize": os.getenv("DEFAULT_CATEGORY_COLORIZATION"), 
    } 
    normalized_endpoint = None 
    if endpoint_path: 
        normalized_endpoint = endpoint_path.strip("/").split("/")[0].lower() or None 

    chosen = category_id 
    if not chosen and normalized_endpoint and endpoint_map.get(normalized_endpoint): 
        chosen = endpoint_map[normalized_endpoint] 
    if not chosen: 
        chosen = default_category_id or os.getenv("DEFAULT_CATEGORY_FALLBACK", "69368fcd2e46bd68ae1889b2") 

    return _objectid_from_any(chosen)


def _get_today_midnight_utc() -> datetime:
    """Get today's date at midnight UTC (timezone-naive for MongoDB compatibility)."""
    now = datetime.utcnow()
    return datetime(now.year, now.month, now.day)


def _update_daily_count(collection, user_object_id: ObjectId, today: datetime) -> None:
    """Update ai_edit_daily_count array: add today with count 1 if missing, fill gaps with count 0."""
    # Ensure today is at midnight
    today_start = today.replace(hour=0, minute=0, second=0, microsecond=0)
    
    logger.info("Updating daily count for user %s, today: %s", str(user_object_id), today_start.isoformat())
    
    # Check if today's date already exists
    user_doc = collection.find_one({"userId": user_object_id})
    
    if not user_doc:
        # User document doesn't exist yet - this shouldn't happen as we create it first
        # But handle it gracefully by initializing the field
        logger.warning("User document not found when updating daily count, initializing")
        collection.update_one(
            {"userId": user_object_id},
            {
                "$setOnInsert": {
                    "ai_edit_daily_count": [{
                        "date": today_start,
                        "count": 1
                    }]
                }
            },
            upsert=False
        )
        return
    
    # Get existing daily counts
    existing_counts = user_doc.get("ai_edit_daily_count", [])
    logger.debug("Existing daily counts: %d entries", len(existing_counts))
    
    # Check if today's date already exists
    today_exists = False
    for entry in existing_counts:
        entry_date = entry.get("date")
        if entry_date:
            # Normalize to midnight for comparison
            if isinstance(entry_date, datetime):
                normalized_date = entry_date.replace(hour=0, minute=0, second=0, microsecond=0)
                logger.debug("Comparing entry date %s with today %s", normalized_date.isoformat(), today_start.isoformat())
                if normalized_date == today_start:
                    today_exists = True
                    logger.info("Today's date already exists in daily count, leaving unchanged: %s", today_start.isoformat())
                    break
    
    # If today exists, do nothing (leave it as is)
    if today_exists:
        logger.debug("Today's date already exists in daily count, leaving unchanged: %s", today_start.isoformat())
        return
    
    # Today doesn't exist - need to add it and fill missing dates
    logger.info("Today's date does not exist in daily count, adding new entry")
    
    # Find the latest date in existing counts
    last_date = None
    if existing_counts:
        dates = []
        for entry in existing_counts:
            entry_date = entry.get("date")
            if entry_date:
                # Normalize to midnight for comparison
                if isinstance(entry_date, datetime):
                    dates.append(entry_date.replace(hour=0, minute=0, second=0, microsecond=0))
        if dates:
            last_date = max(dates)
            logger.debug("Last date found: %s", last_date.isoformat())
        else:
            logger.debug("No valid dates found in existing counts")
    else:
        logger.debug("No existing counts, will add today as first entry")
    
    # Generate missing dates between last_date and today
    dates_to_add = []
    if last_date:
        # Normalize last_date to midnight
        last_date = last_date.replace(hour=0, minute=0, second=0, microsecond=0)
        current_date = last_date + timedelta(days=1)
        # Fill missing dates with count 0
        while current_date < today_start:
            dates_to_add.append({
                "date": current_date,
                "count": 0
            })
            current_date += timedelta(days=1)
        logger.debug("Filled %d gap dates between %s and %s", len(dates_to_add), last_date.isoformat(), today_start.isoformat())
    
    # Add today's entry with count 1
    dates_to_add.append({
        "date": today_start,
        "count": 1
    })
    logger.info("Adding %d new date entries (including today with count 1)", len(dates_to_add))
    
    # Merge existing entries with the new ones, sort by date (oldest first),
    # and keep only the most recent 32 dates (drop the oldest beyond 32).
    if dates_to_add:
        all_entries = list(existing_counts) + dates_to_add

        def _entry_sort_key(entry: Dict[str, Any]) -> datetime:
            dt = entry.get("date")
            if isinstance(dt, datetime):
                return dt.replace(hour=0, minute=0, second=0, microsecond=0)
            return datetime.min

        all_entries.sort(key=_entry_sort_key)
        if len(all_entries) > 32:
            removed = len(all_entries) - 32
            all_entries = all_entries[-32:]
            logger.debug("Removed %d oldest entries to maintain 32-entry limit", removed)

        result = collection.update_one(
            {"userId": user_object_id},
            {"$set": {"ai_edit_daily_count": all_entries}},
        )
        logger.info(
            "Updated ai_edit_daily_count with %d entries (oldest first, max 32). Matched: %d, Modified: %d",
            len(all_entries), result.matched_count, result.modified_count,
        )
    else:
        logger.warning("No dates to add - this should not happen!")

def log_api_call(
    endpoint: str,
    method: str,
    status_code: int = 200,
    request_data: Optional[Dict[str, Any]] = None,
    response_data: Optional[Dict[str, Any]] = None,
    error: Optional[str] = None,
    user_id: Optional[str] = None,
    ip_address: Optional[str] = None
) -> bool:
    """
    Log API call to MongoDB
    
    Args:
        endpoint: API endpoint path
        method: HTTP method (GET, POST, etc.)
        status_code: HTTP status code
        request_data: Request data/parameters
        response_data: Response data
        error: Error message if any
        user_id: User ID if authenticated
        ip_address: Client IP address
    
    Returns:
        True if logged successfully, False otherwise
    """
    try:
        db = get_database()
        if db is None:
            logger.warning("MongoDB not available, skipping API log")
            return False
        
        collection = db["api_calls"]
        
        log_entry = {
            "endpoint": endpoint,
            "method": method,
            "status_code": status_code,
            "timestamp": datetime.utcnow(),
            "request_data": request_data or {},
            "response_data": response_data or {},
            "error": error,
            "user_id": user_id,
            "ip_address": ip_address
        }
        
        result = collection.insert_one(log_entry)
        logger.info("API call logged to MongoDB: %s", result.inserted_id)
        return True
    except Exception as e:
        logger.error("Failed to log API call to MongoDB: %s", str(e))
        return False

def log_image_upload(
    image_id: str,
    filename: str,
    file_size: int,
    content_type: str,
    user_id: Optional[str] = None,
    ip_address: Optional[str] = None
) -> bool:
    """
    Log image upload to MongoDB
    
    Args:
        image_id: Unique image identifier
        filename: Original filename
        file_size: File size in bytes
        content_type: MIME type
        user_id: User ID if authenticated
        ip_address: Client IP address
    
    Returns:
        True if logged successfully, False otherwise
    """
    try:
        db = get_database()
        if db is None:
            logger.warning("MongoDB not available, skipping upload log")
            return False
        
        collection = db["image_uploads"]
        
        log_entry = {
            "image_id": image_id,
            "filename": filename,
            "file_size": file_size,
            "content_type": content_type,
            "uploaded_at": datetime.utcnow(),
            "user_id": user_id,
            "ip_address": ip_address
        }
        
        result = collection.insert_one(log_entry)
        logger.info("Image upload logged to MongoDB: %s", result.inserted_id)
        return True
    except Exception as e:
        logger.error("Failed to log image upload to MongoDB: %s", str(e))
        return False

def log_colorization(
    result_id: Optional[str] = None,
    image_id: Optional[str] = None,
    prompt: Optional[str] = None,
    model_type: Optional[str] = None,
    processing_time: Optional[float] = None,
    user_id: Optional[str] = None,
    ip_address: Optional[str] = None,
    status: str = "success",
    error: Optional[str] = None
) -> bool:
    """
    Log colorization request to MongoDB (colorization_db -> colorizations collection)
    Logs both successful and failed API calls.
    
    Args:
        result_id: Unique result identifier (None for failed requests)
        image_id: Original image identifier
        prompt: Text prompt used (if any)
        model_type: Model type used (fastai, pytorch, sdxl, etc.)
        processing_time: Time taken to process in seconds
        user_id: User ID if authenticated
        ip_address: Client IP address
        status: Status of the request ("success" or "failed")
        error: Error message if status is "failed"
    
    Returns:
        True if logged successfully, False otherwise
    """
    try:
        db = get_database()
        if db is None:
            logger.warning("MongoDB not available, skipping colorization log")
            return False
        
        collection = db["colorizations"]
        
        # Generate result_id if not provided (for failed requests)
        if not result_id:
            import uuid
            result_id = str(uuid.uuid4())
        
        log_entry = {
            "result_id": result_id,
            "image_id": image_id,
            "prompt": prompt,
            "model_type": model_type,
            "processing_time": processing_time,
            "created_at": datetime.utcnow(),
            "user_id": user_id,
            "ip_address": ip_address
        }
        
        # Add status and error fields only if provided (for new documents)
        # Existing documents won't have these fields, which is fine
        if status:
            log_entry["status"] = status
        if error:
            log_entry["error"] = error
        
        result = collection.insert_one(log_entry)
        logger.info("Colorization logged to MongoDB (status: %s): %s", status, result.inserted_id)
        return True
    except Exception as e:
        logger.error("Failed to log colorization to MongoDB: %s", str(e))
        return False


def log_media_click( 
    user_id: Optional[Union[str, int, ObjectId]], 
    category_id: Optional[str], 
    *, 
    endpoint_path: Optional[str] = None, 
    default_category_id: Optional[str] = None, 
) -> bool: 
    """Log media clicks into the admin MongoDB (media_clicks collection).
    
    Only logs if user_id is provided. If user_id is None or empty, returns False without logging.
    Regular MongoDB logging (api_calls, image_uploads, colorizations) always happens regardless.
    """
    # Only log to media_clicks if user_id is provided
    if not user_id or (isinstance(user_id, str) and not user_id.strip()):
        logger.debug("Skipping media click log - user_id not provided")
        return False
        
    try: 
        db = get_admin_database() 
        if db is None: 
            logger.warning("Admin MongoDB not available, skipping media click log") 
            return False 

        collection = db["media_clicks"] 

        # Drop legacy index to avoid duplicate key errors (best effort) 
        try: 
            collection.drop_index("user_id_1_header_1_media_id_1") 
        except Exception as exc: 
            logger.debug("Legacy index drop skipped: %s", str(exc)) 

        user_object_id = _normalize_object_id(user_id) 
        category_object_id = _resolve_category_id(category_id, endpoint_path, default_category_id) 
        now = datetime.utcnow()
        today = _get_today_midnight_utc()
        
        logger.info("Media click - user_id input: %s, normalized: %s, category_id input: %s, normalized: %s", 
                   user_id, str(user_object_id), category_id, str(category_object_id)) 

        # Try to update existing category in new schema (categories.categoryId)
        update_existing = collection.update_one( 
            {"userId": user_object_id, "categories.categoryId": category_object_id}, 
            { 
                "$inc": {
                    "categories.$.click_count": 1,
                    "ai_edit_complete": 1  # Increment usage count
                }, 
                "$set": {
                    "categories.$.lastClickedAt": now,
                    "updatedAt": now,
                    "ai_edit_last_date": now  # Update last used date (MongoDB Date object)
                }, 
            }, 
        ) 

        if update_existing.matched_count == 0: 
            # Category not found in new schema, check if user exists
            user_exists = collection.find_one({"userId": user_object_id})
            
            if user_exists:
                # User exists but category doesn't in new schema - add to categories array
                collection.update_one( 
                    {"userId": user_object_id}, 
                    { 
                        "$inc": {"ai_edit_complete": 1},  # Increment usage count
                        "$set": {
                            "updatedAt": now,
                            "ai_edit_last_date": now  # Update last used date (MongoDB Date object)
                        }, 
                        "$push": { 
                            "categories": { 
                                "categoryId": category_object_id,
                                "click_count": 1,
                                "lastClickedAt": now, 
                            } 
                        }, 
                    }, 
                )
            else:
                # User doesn't exist - create new document with categories array
                # Default ai_edit_complete = 0, then increment to 1 on first use
                collection.update_one( 
                    {"userId": user_object_id}, 
                    { 
                        "$setOnInsert": {
                            "createdAt": now,
                            "ai_edit_complete": 0,  # Default 0 for new users
                            "ai_edit_daily_count": []  # Initialize empty array
                        }, 
                        "$inc": {"ai_edit_complete": 1},  # Increment to 1 on first use
                        "$set": {
                            "updatedAt": now,
                            "ai_edit_last_date": now  # Set last used date (MongoDB Date object)
                        }, 
                        "$push": { 
                            "categories": { 
                                "categoryId": category_object_id,
                                "click_count": 1,
                                "lastClickedAt": now, 
                            } 
                        }, 
                    }, 
                    upsert=True, 
                )
        
        # Update daily count (after document is created/updated)
        _update_daily_count(collection, user_object_id, today)

        logger.info("Media click logged for user %s", str(user_object_id)) 
        return True 
    except Exception as exc: 
        logger.error("Failed to log media click to admin MongoDB: %s", str(exc)) 
        return False 

def close_connection():
    """Close MongoDB connection"""
    global _client, _db, _admin_client, _admin_db 
    if _client:
        _client.close()
        _client = None
        _db = None
        logger.info("MongoDB connection closed")
    if _admin_client: 
        _admin_client.close() 
        _admin_client = None 
        _admin_db = None 
        logger.info("Admin MongoDB connection closed") 



# """ 
# MongoDB database connection and logging utilities, including admin media click logging. 
# """ 
# import os 
# import logging 
# from datetime import datetime, timedelta
# from typing import Optional, Dict, Any, Union, List
# from bson import ObjectId 
# from pymongo import MongoClient 
# from pymongo.errors import ConnectionFailure, ServerSelectionTimeoutError 

# logger = logging.getLogger(__name__)

# # MongoDB connection 
# _client: Optional[MongoClient] = None 
# _db = None 

# # Admin MongoDB connection (media_clicks) 
# _admin_client: Optional[MongoClient] = None 
# _admin_db = None 

# def get_mongodb_client() -> Optional[MongoClient]:
#     """Get or create MongoDB client"""
#     global _client
#     if _client is None:
#         mongodb_uri = os.getenv("MONGODB_URI")
#         if not mongodb_uri:
#             logger.warning("MONGODB_URI environment variable not set. MongoDB features will be disabled.")
#             return None
#         try:
#             _client = MongoClient(
#                 mongodb_uri,
#                 serverSelectionTimeoutMS=5000,
#                 connectTimeoutMS=5000
#             )
#             # Test connection
#             _client.admin.command('ping')
#             logger.info("MongoDB connection established successfully")
#         except (ConnectionFailure, ServerSelectionTimeoutError) as e:
#             logger.error("Failed to connect to MongoDB: %s", str(e))
#             _client = None
#     return _client

# def get_database():
#     """Get database instance"""
#     global _db
#     if _db is None:
#         client = get_mongodb_client()
#         if client:
#             db_name = os.getenv("MONGODB_DB_NAME", "colorization_db")
#             _db = client[db_name]
#         else:
#             logger.warning("MongoDB client not available")
#     return _db


# def get_admin_client() -> Optional[MongoClient]: 
#     """Get or create admin MongoDB client (for media_clicks collection).""" 
#     global _admin_client 
#     if _admin_client is None: 
#         mongodb_uri = os.getenv("MONGODB_ADMIN") 
#         if not mongodb_uri: 
#             logger.warning("MONGODB_ADMIN environment variable not set. Admin MongoDB features will be disabled.") 
#             return None 
#         try: 
#             _admin_client = MongoClient( 
#                 mongodb_uri, 
#                 serverSelectionTimeoutMS=5000, 
#                 connectTimeoutMS=5000, 
#             ) 
#             _admin_client.admin.command("ping") 
#             logger.info("Admin MongoDB connection established successfully") 
#         except (ConnectionFailure, ServerSelectionTimeoutError) as exc: 
#             logger.error("Failed to connect to Admin MongoDB: %s", str(exc)) 
#             _admin_client = None 
#     return _admin_client 


# def get_admin_database(): 
#     """Get admin database instance.""" 
#     global _admin_db 
#     if _admin_db is None: 
#         client = get_admin_client() 
#         if client: 
#             db_name = os.getenv("MONGODB_ADMIN_DB_NAME", "adminPanel") 
#             _admin_db = client[db_name] 
#             logger.info("Using admin database: %s", db_name)
#         else: 
#             logger.warning("Admin MongoDB client not available") 
#     return _admin_db 


# def _normalize_object_id(raw_value: Optional[Union[str, int, ObjectId]]) -> ObjectId: 
#     """Normalize user id inputs into a deterministic ObjectId.""" 
#     if isinstance(raw_value, ObjectId): 
#         return raw_value 

#     if raw_value is None: 
#         return ObjectId() 

#     # Handle empty strings as None
#     if isinstance(raw_value, str) and not raw_value.strip():
#         return ObjectId()

#     try: 
#         if isinstance(raw_value, int) or (isinstance(raw_value, str) and raw_value.strip().lstrip("-").isdigit()): 
#             int_value = int(str(raw_value).strip()) 
#             hex_str = format(abs(int_value), "x").zfill(24)[-24:] 
#             if ObjectId.is_valid(hex_str): 
#                 return ObjectId(hex_str) 
#     except Exception as exc:  # pragma: no cover - defensive 
#         logger.debug("Numeric user id normalization failed: %s", str(exc)) 

#     if isinstance(raw_value, str): 
#         candidate = raw_value.strip() 
#         if ObjectId.is_valid(candidate): 
#             return ObjectId(candidate) 

#     return ObjectId() 


# def _objectid_from_any(value: str) -> ObjectId: 
#     """Convert arbitrary string into an ObjectId deterministically when possible.""" 
#     if ObjectId.is_valid(value): 
#         return ObjectId(value) 
#     try: 
#         hex_str = value.encode("utf-8").hex().zfill(24)[-24:] 
#         if ObjectId.is_valid(hex_str): 
#             return ObjectId(hex_str) 
#     except Exception as exc:  # pragma: no cover - defensive 
#         logger.debug("Category id normalization failed: %s", str(exc)) 
#     return ObjectId() 


# def _resolve_category_id( 
#     category_id: Optional[str], 
#     endpoint_path: Optional[str], 
#     default_category_id: Optional[str], 
# ) -> ObjectId: 
#     """Pick category id from explicit value, endpoint default, or fallback.""" 
#     # Handle empty strings as None
#     if isinstance(category_id, str) and not category_id.strip():
#         category_id = None
        
#     endpoint_map = { 
#         "colorization": os.getenv("DEFAULT_CATEGORY_COLORIZATION"), 
#         "upload": os.getenv("DEFAULT_CATEGORY_COLORIZATION"), 
#         "colorize": os.getenv("DEFAULT_CATEGORY_COLORIZATION"), 
#     } 
#     normalized_endpoint = None 
#     if endpoint_path: 
#         normalized_endpoint = endpoint_path.strip("/").split("/")[0].lower() or None 

#     chosen = category_id 
#     if not chosen and normalized_endpoint and endpoint_map.get(normalized_endpoint): 
#         chosen = endpoint_map[normalized_endpoint] 
#     if not chosen: 
#         chosen = default_category_id or os.getenv("DEFAULT_CATEGORY_FALLBACK", "69368fcd2e46bd68ae1889b2") 

#     return _objectid_from_any(chosen)


# def _get_today_midnight_utc() -> datetime:
#     """Get today's date at midnight UTC (timezone-naive for MongoDB compatibility)."""
#     now = datetime.utcnow()
#     return datetime(now.year, now.month, now.day)


# def _update_daily_count(collection, user_object_id: ObjectId, today: datetime) -> None:
#     """Update ai_edit_daily_count array: add today with count 1 if missing, fill gaps with count 0."""
#     # Ensure today is at midnight
#     today_start = today.replace(hour=0, minute=0, second=0, microsecond=0)
    
#     # Check if today's date already exists
#     user_doc = collection.find_one({"userId": user_object_id})
    
#     if not user_doc:
#         # User document doesn't exist yet - this shouldn't happen as we create it first
#         # But handle it gracefully by initializing the field
#         logger.warning("User document not found when updating daily count, initializing")
#         collection.update_one(
#             {"userId": user_object_id},
#             {
#                 "$setOnInsert": {
#                     "ai_edit_daily_count": [{
#                         "date": today_start,
#                         "count": 1
#                     }]
#                 }
#             },
#             upsert=False
#         )
#         return
    
#     # Get existing daily counts
#     existing_counts = user_doc.get("ai_edit_daily_count", [])
    
#     # Check if today's date already exists
#     today_exists = False
#     for entry in existing_counts:
#         entry_date = entry.get("date")
#         if entry_date:
#             # Normalize to midnight for comparison
#             if isinstance(entry_date, datetime):
#                 normalized_date = entry_date.replace(hour=0, minute=0, second=0, microsecond=0)
#                 if normalized_date == today_start:
#                     today_exists = True
#                     break
    
#     # If today exists, do nothing (leave it as is)
#     if today_exists:
#         logger.debug("Today's date already exists in daily count, leaving unchanged: %s", today_start.isoformat())
#         return
    
#     # Today doesn't exist - need to add it and fill missing dates
#     # Find the latest date in existing counts
#     last_date = None
#     if existing_counts:
#         dates = []
#         for entry in existing_counts:
#             entry_date = entry.get("date")
#             if entry_date:
#                 # Normalize to midnight for comparison
#                 if isinstance(entry_date, datetime):
#                     dates.append(entry_date.replace(hour=0, minute=0, second=0, microsecond=0))
#         if dates:
#             last_date = max(dates)
    
#     # Generate missing dates between last_date and today
#     dates_to_add = []
#     if last_date:
#         # Normalize last_date to midnight
#         last_date = last_date.replace(hour=0, minute=0, second=0, microsecond=0)
#         current_date = last_date + timedelta(days=1)
#         # Fill missing dates with count 0
#         while current_date < today_start:
#             dates_to_add.append({
#                 "date": current_date,
#                 "count": 0
#             })
#             current_date += timedelta(days=1)
    
#     # Add today's entry with count 1
#     dates_to_add.append({
#         "date": today_start,
#         "count": 1
#     })
    
#     # Merge existing entries with the new ones, sort by date (oldest first),
#     # and keep only the most recent 32 dates (drop the oldest beyond 32).
#     if dates_to_add:
#         all_entries = list(existing_counts) + dates_to_add

#         def _entry_sort_key(entry: Dict[str, Any]) -> datetime:
#             dt = entry.get("date")
#             if isinstance(dt, datetime):
#                 return dt.replace(hour=0, minute=0, second=0, microsecond=0)
#             return datetime.min

#         all_entries.sort(key=_entry_sort_key)
#         if len(all_entries) > 32:
#             all_entries = all_entries[-32:]

#         collection.update_one(
#             {"userId": user_object_id},
#             {"$set": {"ai_edit_daily_count": all_entries}},
#         )
#         logger.debug(
#             "Updated ai_edit_daily_count with %d entries (oldest first, max 32)",
#             len(all_entries),
#         )

# def log_api_call(
#     endpoint: str,
#     method: str,
#     status_code: int = 200,
#     request_data: Optional[Dict[str, Any]] = None,
#     response_data: Optional[Dict[str, Any]] = None,
#     error: Optional[str] = None,
#     user_id: Optional[str] = None,
#     ip_address: Optional[str] = None
# ) -> bool:
#     """
#     Log API call to MongoDB
    
#     Args:
#         endpoint: API endpoint path
#         method: HTTP method (GET, POST, etc.)
#         status_code: HTTP status code
#         request_data: Request data/parameters
#         response_data: Response data
#         error: Error message if any
#         user_id: User ID if authenticated
#         ip_address: Client IP address
    
#     Returns:
#         True if logged successfully, False otherwise
#     """
#     try:
#         db = get_database()
#         if db is None:
#             logger.warning("MongoDB not available, skipping API log")
#             return False
        
#         collection = db["api_calls"]
        
#         log_entry = {
#             "endpoint": endpoint,
#             "method": method,
#             "status_code": status_code,
#             "timestamp": datetime.utcnow(),
#             "request_data": request_data or {},
#             "response_data": response_data or {},
#             "error": error,
#             "user_id": user_id,
#             "ip_address": ip_address
#         }
        
#         result = collection.insert_one(log_entry)
#         logger.info("API call logged to MongoDB: %s", result.inserted_id)
#         return True
#     except Exception as e:
#         logger.error("Failed to log API call to MongoDB: %s", str(e))
#         return False

# def log_image_upload(
#     image_id: str,
#     filename: str,
#     file_size: int,
#     content_type: str,
#     user_id: Optional[str] = None,
#     ip_address: Optional[str] = None
# ) -> bool:
#     """
#     Log image upload to MongoDB
    
#     Args:
#         image_id: Unique image identifier
#         filename: Original filename
#         file_size: File size in bytes
#         content_type: MIME type
#         user_id: User ID if authenticated
#         ip_address: Client IP address
    
#     Returns:
#         True if logged successfully, False otherwise
#     """
#     try:
#         db = get_database()
#         if db is None:
#             logger.warning("MongoDB not available, skipping upload log")
#             return False
        
#         collection = db["image_uploads"]
        
#         log_entry = {
#             "image_id": image_id,
#             "filename": filename,
#             "file_size": file_size,
#             "content_type": content_type,
#             "uploaded_at": datetime.utcnow(),
#             "user_id": user_id,
#             "ip_address": ip_address
#         }
        
#         result = collection.insert_one(log_entry)
#         logger.info("Image upload logged to MongoDB: %s", result.inserted_id)
#         return True
#     except Exception as e:
#         logger.error("Failed to log image upload to MongoDB: %s", str(e))
#         return False

# def log_colorization(
#     result_id: Optional[str] = None,
#     image_id: Optional[str] = None,
#     prompt: Optional[str] = None,
#     model_type: Optional[str] = None,
#     processing_time: Optional[float] = None,
#     user_id: Optional[str] = None,
#     ip_address: Optional[str] = None,
#     status: str = "success",
#     error: Optional[str] = None
# ) -> bool:
#     """
#     Log colorization request to MongoDB (colorization_db -> colorizations collection)
#     Logs both successful and failed API calls.
    
#     Args:
#         result_id: Unique result identifier (None for failed requests)
#         image_id: Original image identifier
#         prompt: Text prompt used (if any)
#         model_type: Model type used (fastai, pytorch, sdxl, etc.)
#         processing_time: Time taken to process in seconds
#         user_id: User ID if authenticated
#         ip_address: Client IP address
#         status: Status of the request ("success" or "failed")
#         error: Error message if status is "failed"
    
#     Returns:
#         True if logged successfully, False otherwise
#     """
#     try:
#         db = get_database()
#         if db is None:
#             logger.warning("MongoDB not available, skipping colorization log")
#             return False
        
#         collection = db["colorizations"]
        
#         # Generate result_id if not provided (for failed requests)
#         if not result_id:
#             import uuid
#             result_id = str(uuid.uuid4())
        
#         log_entry = {
#             "result_id": result_id,
#             "image_id": image_id,
#             "prompt": prompt,
#             "model_type": model_type,
#             "processing_time": processing_time,
#             "created_at": datetime.utcnow(),
#             "user_id": user_id,
#             "ip_address": ip_address
#         }
        
#         # Add status and error fields only if provided (for new documents)
#         # Existing documents won't have these fields, which is fine
#         if status:
#             log_entry["status"] = status
#         if error:
#             log_entry["error"] = error
        
#         result = collection.insert_one(log_entry)
#         logger.info("Colorization logged to MongoDB (status: %s): %s", status, result.inserted_id)
#         return True
#     except Exception as e:
#         logger.error("Failed to log colorization to MongoDB: %s", str(e))
#         return False


# def log_media_click( 
#     user_id: Optional[Union[str, int, ObjectId]], 
#     category_id: Optional[str], 
#     *, 
#     endpoint_path: Optional[str] = None, 
#     default_category_id: Optional[str] = None, 
# ) -> bool: 
#     """Log media clicks into the admin MongoDB (media_clicks collection).
    
#     Only logs if user_id is provided. If user_id is None or empty, returns False without logging.
#     Regular MongoDB logging (api_calls, image_uploads, colorizations) always happens regardless.
#     """
#     # Only log to media_clicks if user_id is provided
#     if not user_id or (isinstance(user_id, str) and not user_id.strip()):
#         logger.debug("Skipping media click log - user_id not provided")
#         return False
        
#     try: 
#         db = get_admin_database() 
#         if db is None: 
#             logger.warning("Admin MongoDB not available, skipping media click log") 
#             return False 

#         collection = db["media_clicks"] 

#         # Drop legacy index to avoid duplicate key errors (best effort) 
#         try: 
#             collection.drop_index("user_id_1_header_1_media_id_1") 
#         except Exception as exc: 
#             logger.debug("Legacy index drop skipped: %s", str(exc)) 

#         user_object_id = _normalize_object_id(user_id) 
#         category_object_id = _resolve_category_id(category_id, endpoint_path, default_category_id) 
#         now = datetime.utcnow()
#         today = _get_today_midnight_utc()
        
#         logger.info("Media click - user_id input: %s, normalized: %s, category_id input: %s, normalized: %s", 
#                    user_id, str(user_object_id), category_id, str(category_object_id)) 

#         # Try to update existing category in new schema (categories.categoryId)
#         update_existing = collection.update_one( 
#             {"userId": user_object_id, "categories.categoryId": category_object_id}, 
#             { 
#                 "$inc": {
#                     "categories.$.click_count": 1,
#                     "ai_edit_complete": 1  # Increment usage count
#                 }, 
#                 "$set": {
#                     "categories.$.lastClickedAt": now,
#                     "updatedAt": now,
#                     "ai_edit_last_date": now  # Update last used date (MongoDB Date object)
#                 }, 
#             }, 
#         ) 

#         if update_existing.matched_count == 0: 
#             # Category not found in new schema, check if user exists
#             user_exists = collection.find_one({"userId": user_object_id})
            
#             if user_exists:
#                 # User exists but category doesn't in new schema - add to categories array
#                 collection.update_one( 
#                     {"userId": user_object_id}, 
#                     { 
#                         "$inc": {"ai_edit_complete": 1},  # Increment usage count
#                         "$set": {
#                             "updatedAt": now,
#                             "ai_edit_last_date": now  # Update last used date (MongoDB Date object)
#                         }, 
#                         "$push": { 
#                             "categories": { 
#                                 "categoryId": category_object_id,
#                                 "click_count": 1,
#                                 "lastClickedAt": now, 
#                             } 
#                         }, 
#                     }, 
#                 )
#             else:
#                 # User doesn't exist - create new document with categories array
#                 # Default ai_edit_complete = 0, then increment to 1 on first use
#                 collection.update_one( 
#                     {"userId": user_object_id}, 
#                     { 
#                         "$setOnInsert": {
#                             "createdAt": now,
#                             "ai_edit_complete": 0,  # Default 0 for new users
#                             "ai_edit_daily_count": []  # Initialize empty array
#                         }, 
#                         "$inc": {"ai_edit_complete": 1},  # Increment to 1 on first use
#                         "$set": {
#                             "updatedAt": now,
#                             "ai_edit_last_date": now  # Set last used date (MongoDB Date object)
#                         }, 
#                         "$push": { 
#                             "categories": { 
#                                 "categoryId": category_object_id,
#                                 "click_count": 1,
#                                 "lastClickedAt": now, 
#                             } 
#                         }, 
#                     }, 
#                     upsert=True, 
#                 )
        
#         # Update daily count (after document is created/updated)
#         _update_daily_count(collection, user_object_id, today)

#         logger.info("Media click logged for user %s", str(user_object_id)) 
#         return True 
#     except Exception as exc: 
#         logger.error("Failed to log media click to admin MongoDB: %s", str(exc)) 
#         return False 

# def close_connection():
#     """Close MongoDB connection"""
#     global _client, _db, _admin_client, _admin_db 
#     if _client:
#         _client.close()
#         _client = None
#         _db = None
#         logger.info("MongoDB connection closed")
#     if _admin_client: 
#         _admin_client.close() 
#         _admin_client = None 
#         _admin_db = None 
#         logger.info("Admin MongoDB connection closed")