File size: 79,045 Bytes
b19e5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623a0a4
b19e5b5
 
 
 
 
623a0a4
b19e5b5
 
 
 
 
 
 
 
 
 
 
 
 
623a0a4
 
b19e5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623a0a4
 
b19e5b5
 
 
 
 
 
 
 
 
 
 
 
623a0a4
 
b19e5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623a0a4
 
b19e5b5
623a0a4
 
 
 
 
 
b19e5b5
623a0a4
 
 
 
 
 
 
 
 
b19e5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623a0a4
 
b19e5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623a0a4
 
 
 
b19e5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623a0a4
 
 
 
 
 
 
 
 
 
 
 
 
b19e5b5
 
 
623a0a4
 
b19e5b5
623a0a4
 
 
 
 
 
 
 
 
 
 
b19e5b5
623a0a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b19e5b5
623a0a4
 
 
 
 
 
 
 
 
b19e5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623a0a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b19e5b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
623a0a4
b19e5b5
 
623a0a4
b19e5b5
 
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
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
"""
FastAPI Server for Audit Checklist Application
=============================================

This server provides a REST API for managing audit checklists with MongoDB integration.
It supports CRUD operations for checklist data and user management.

Features:
- MongoDB Atlas integration with async Motor driver
- CORS support for React frontend
- Comprehensive error handling
- Health check endpoint
- Environment-based configuration

Author: Audit Checklist Team
Version: 1.0.0
"""

import os
import sys
import base64
from datetime import datetime
from typing import Optional, List, Dict, Any, Union
import logging

# FastAPI imports
from fastapi import FastAPI, HTTPException, status, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

# Pydantic for data validation
from pydantic import BaseModel, Field

# MongoDB async driver
import motor.motor_asyncio
from bson import ObjectId

# Environment variables
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv('mongodb.env')

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# =============================================================================
# CONFIGURATION AND INITIALIZATION
# =============================================================================

# Environment variables with fallback defaults
MONGODB_URI = os.getenv('MONGODB_URI', 'mongodb://localhost:27017/audit_checklist')
PORT = int(os.getenv('PORT', 8000))  # Hugging Face Spaces uses port 8000
CORS_ORIGIN = os.getenv('CORS_ORIGIN', '*')  # Allow all origins by default for mobile apps

# Initialize FastAPI application
app = FastAPI(
    title="Audit Checklist API",
    description="REST API for managing audit checklists with MongoDB integration",
    version="1.0.0",
    docs_url="/docs",  # Swagger UI documentation
    redoc_url="/redoc"  # ReDoc documentation
)

# Configure CORS middleware
# Allow all origins for Hugging Face Spaces deployment
cors_origins = [CORS_ORIGIN] if CORS_ORIGIN != "*" else ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=cors_origins,
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
    allow_headers=["*"],
)

# MongoDB connection setup
client = None
db = None

async def connect_to_mongodb():
    """
    Establish connection to MongoDB Atlas
    
    This function creates an async connection to MongoDB using the Motor driver.
    It handles connection errors gracefully and logs the status.
    """
    global client, db
    try:
        client = motor.motor_asyncio.AsyncIOMotorClient(MONGODB_URI)
        db = client.audit_checklist
        
        # Test the connection
        await client.admin.command('ping')
        logger.info("Successfully connected to MongoDB Atlas")
        
        # Create indexes for better performance
        await create_database_indexes()
        
    except Exception as e:
        logger.error(f"Failed to connect to MongoDB: {e}")
        raise e

async def create_database_indexes():
    """
    Create database indexes for optimal query performance
    
    This function creates indexes on frequently queried fields to improve
    database performance and query speed.
    """
    try:
        # Index on userId for faster user-specific queries
        await db.checklists.create_index("userId", unique=False)
        
        # Index on createdAt for time-based queries
        await db.checklists.create_index("createdAt", unique=False)
        
        logger.info("Database indexes created successfully")
        
    except Exception as e:
        logger.warning(f"Could not create indexes: {e}")

async def close_mongodb_connection():
    """Close MongoDB connection gracefully"""
    global client
    if client:
        client.close()
        logger.info("MongoDB connection closed")

# =============================================================================
# PYDANTIC MODELS FOR DATA VALIDATION
# =============================================================================

class ChecklistItem(BaseModel):
    """
    Model for individual checklist items
    
    Attributes:
        id: Unique identifier for the item
        requirement: Description of the requirement to be checked
        compliance: Compliance status (N/A, Compliant, Non-Compliant)
        deviation: Description of any deviation found
        action: Action taken to address the issue
        checkedAt: Timestamp when the item was checked
        checkedBy: Name of the person who checked the item
    """
    id: str = Field(..., description="Unique identifier for the checklist item")
    requirement: str = Field(..., description="Description of the requirement")
    compliance: str = Field(default="N/A", description="Compliance status: N/A, Compliant, or Non-Compliant")
    deviation: str = Field(default="", description="Description of any deviation found")
    action: str = Field(default="", description="Action taken to address the issue")
    checkedAt: Optional[datetime] = Field(default=None, description="Timestamp when item was checked")
    checkedBy: str = Field(default="", description="Name of the person who checked the item")

class ChecklistSection(BaseModel):
    """
    Model for checklist sections containing multiple items
    
    Attributes:
        id: Unique identifier for the section
        title: Display title of the section
        icon: Icon identifier for UI display
        items: List of checklist items in this section
    """
    id: str = Field(..., description="Unique identifier for the section")
    title: str = Field(..., description="Display title of the section")
    icon: str = Field(..., description="Icon identifier for UI display")
    items: List[ChecklistItem] = Field(default=[], description="List of checklist items")

class Metadata(BaseModel):
    """
    Metadata model for checklist information
    """
    userName: Optional[str] = Field(default=None, description="Name of the user who saved the checklist")
    savedAt: Optional[str] = Field(default=None, description="ISO timestamp when saved")
    savedAtFormatted: Optional[str] = Field(default=None, description="Formatted timestamp when saved")
    userId: Optional[str] = Field(default=None, description="User ID")
    version: Optional[str] = Field(default="1.0", description="Version of the checklist")

class ChecklistData(BaseModel):
    """
    Complete checklist data model
    
    Attributes:
        userId: Unique identifier for the user
        title: Title of the checklist
        sections: List of sections in the checklist
        totalItems: Total number of items across all sections
        completedItems: Number of completed items
        nonCompliantItems: Number of non-compliant items
        complianceScore: Calculated compliance percentage
        verificationDate: Date when the checklist was verified
        createdAt: Timestamp when the checklist was created
        updatedAt: Timestamp when the checklist was last updated
        imageData: Base64 encoded image data (stored when compliance < 100%)
        imageType: MIME type of the image (e.g., image/jpeg, image/png)
    """
    userId: str = Field(..., description="Unique identifier for the user")
    title: str = Field(..., description="Title of the checklist")
    sections: List[ChecklistSection] = Field(default=[], description="List of checklist sections")
    totalItems: Optional[int] = Field(default=0, description="Total number of items")
    completedItems: Optional[int] = Field(default=0, description="Number of completed items")
    nonCompliantItems: Optional[int] = Field(default=0, description="Number of non-compliant items")
    complianceScore: Optional[float] = Field(default=0.0, description="Compliance percentage score")
    verificationDate: Optional[datetime] = Field(default=None, description="Date of verification")
    createdAt: Optional[datetime] = Field(default=None, description="Creation timestamp")
    updatedAt: Optional[datetime] = Field(default=None, description="Last update timestamp")
    metadata: Optional[Metadata] = Field(default=None, description="Additional metadata including user information")
    imageData: Optional[str] = Field(default=None, description="Base64 encoded image data for non-compliant checklists")
    imageType: Optional[str] = Field(default=None, description="MIME type of the image")
    
    class Config:
        # Allow extra fields that might be sent from frontend
        extra = "allow"

class ChecklistResponse(BaseModel):
    """
    Standard API response model for checklist operations
    
    Attributes:
        success: Boolean indicating if the operation was successful
        data: The checklist data (if successful)
        message: Optional message describing the result
        error: Error message (if unsuccessful)
    """
    success: bool = Field(..., description="Whether the operation was successful")
    data: Optional[Union[ChecklistData, Dict[str, Any]]] = Field(default=None, description="Checklist data")
    message: Optional[str] = Field(default=None, description="Success message")
    error: Optional[str] = Field(default=None, description="Error message")

class HealthResponse(BaseModel):
    """Health check response model"""
    status: str = Field(..., description="Health status")
    timestamp: datetime = Field(..., description="Current timestamp")
    database: str = Field(..., description="Database connection status")
    version: str = Field(default="1.0.0", description="API version")

# =============================================================================
# UTILITY FUNCTIONS
# =============================================================================

def calculate_checklist_metrics(checklist_data: Dict[str, Any]) -> Dict[str, Any]:
    """
    Calculate compliance metrics for a checklist
    
    Args:
        checklist_data: Dictionary containing checklist data
        
    Returns:
        Dictionary with calculated metrics (totalItems, completedItems, nonCompliantItems, complianceScore)
    """
    total_items = 0
    completed_items = 0
    non_compliant_items = 0
    
    # Iterate through all sections and items
    for section in checklist_data.get('sections', []):
        for item in section.get('items', []):
            total_items += 1
            
            # Count completed items (those that are not N/A)
            if item.get('compliance') != 'N/A':
                completed_items += 1
                
                # Count non-compliant items
                if item.get('compliance') == 'Non-Compliant':
                    non_compliant_items += 1
    
    # Calculate compliance score
    compliance_score = (completed_items / total_items * 100) if total_items > 0 else 0
    
    return {
        'totalItems': total_items,
        'completedItems': completed_items,
        'nonCompliantItems': non_compliant_items,
        'complianceScore': round(compliance_score, 2)
    }

def serialize_checklist(checklist_doc: Dict[str, Any]) -> Dict[str, Any]:
    """
    Serialize MongoDB document to JSON-serializable format
    
    Args:
        checklist_doc: MongoDB document
        
    Returns:
        Dictionary with ObjectId converted to string
    """
    if checklist_doc and '_id' in checklist_doc:
        checklist_doc['_id'] = str(checklist_doc['_id'])
    
    # Convert datetime objects to ISO strings
    for field in ['createdAt', 'updatedAt', 'verificationDate']:
        if field in checklist_doc and checklist_doc[field]:
            # Only convert if it's a datetime object, not a string
            if hasattr(checklist_doc[field], 'isoformat'):
                checklist_doc[field] = checklist_doc[field].isoformat()
    
    # Convert datetime objects in items
    for section in checklist_doc.get('sections', []):
        for item in section.get('items', []):
            if 'checkedAt' in item and item['checkedAt']:
                # Only convert if it's a datetime object, not a string
                if hasattr(item['checkedAt'], 'isoformat'):
                    item['checkedAt'] = item['checkedAt'].isoformat()
    
    return checklist_doc

# =============================================================================
# API ENDPOINTS
# =============================================================================

@app.on_event("startup")
async def startup_event():
    """
    Application startup event handler
    
    This function is called when the FastAPI application starts up.
    It initializes the MongoDB connection and sets up the database.
    """
    logger.info("Starting Audit Checklist API server...")
    await connect_to_mongodb()
    logger.info(f"Server ready on port {PORT}")

@app.on_event("shutdown")
async def shutdown_event():
    """
    Application shutdown event handler
    
    This function is called when the FastAPI application shuts down.
    It gracefully closes the MongoDB connection.
    """
    logger.info("Shutting down Audit Checklist API server...")
    await close_mongodb_connection()

@app.get("/", response_model=Dict[str, str])
async def root():
    """
    Root endpoint providing basic API information
    
    Returns:
        Dictionary with API name and version
    """
    return {
        "message": "Audit Checklist API",
        "version": "1.0.0",
        "docs": "/docs",
        "health": "/health"
    }

@app.get("/health", response_model=HealthResponse)
async def health_check():
    """
    Health check endpoint for monitoring and load balancers
    
    This endpoint checks the status of the API server and database connection.
    It's useful for health monitoring, load balancers, and DevOps automation.
    
    Returns:
        HealthResponse with current status information
    """
    try:
        # Test database connection
        await client.admin.command('ping')
        db_status = "connected"
    except Exception as e:
        logger.error(f"Database health check failed: {e}")
        db_status = "disconnected"
    
    return HealthResponse(
        status="healthy" if db_status == "connected" else "unhealthy",
        timestamp=datetime.utcnow(),
        database=db_status,
        version="1.0.0"
    )

@app.get("/api/checklist/{user_id}", response_model=ChecklistResponse)
async def get_checklist(user_id: str):
    """
    Retrieve checklist data for a specific user
    
    This endpoint fetches the checklist data for a given user ID. If no checklist
    exists for the user, it creates a new one with the default structure.
    
    Args:
        user_id: Unique identifier for the user
        
    Returns:
        ChecklistResponse containing the checklist data
        
    Raises:
        HTTPException: If database operation fails
    """
    try:
        logger.info(f"Fetching checklist for user: {user_id}")
        
        # Query the database for the user's checklist
        # Find the most recent checklist for the user
        checklist_doc = await db.checklists.find_one(
            {"userId": user_id},
            sort=[("createdAt", -1)]  # Get the most recent one
        )
        
        if not checklist_doc:
            # Create new checklist if none exists
            logger.info(f"No checklist found for user {user_id}, creating new one")
            
            # Default checklist structure - Complete 38-item audit checklist
            default_checklist = {
                "userId": user_id,
                "title": "Checklist di Audit Operativo (38 Controlli)",
                "sections": [
                    {
                        "id": "S1",
                        "title": "1. PERSONALE E IGIENE (6 Controlli)",
                        "icon": "Users",
                        "items": [
                            {"id": "I1.1", "requirement": "Indumenti da lavoro puliti (divisa, grembiule).", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I1.2", "requirement": "Scarpe antinfortunistiche / Calzature pulite.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I1.3", "requirement": "Cuffie e/o Retine per capelli indossate correttamente.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I1.4", "requirement": "Assenza di gioielli, piercing visibili, unghie lunghe.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I1.5", "requirement": "Lavaggio mani documentato all'ingresso/reingresso.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I1.6", "requirement": "Assenza di cibo/bevande non autorizzate nelle aree produttive.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""}
                        ]
                    },
                    {
                        "id": "S2",
                        "title": "2. STRUTTURE E IMPIANTI (6 Controlli)",
                        "icon": "Building",
                        "items": [
                            {"id": "I2.1", "requirement": "Illuminazione adeguata e funzionante in tutte le aree.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I2.2", "requirement": "Porte esterne/interne in buone condizioni e chiuse correttamente (sigillatura).", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I2.3", "requirement": "Integrità di pavimenti, pareti e soffitti (assenza di crepe/danni).", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I2.4", "requirement": "Controllo vetri / lampade protette o anti-frantumazione.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I2.5", "requirement": "Condizioni igieniche dei servizi igienici e spogliatoi (pulizia e dotazioni).", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I2.6", "requirement": "Ventilazione e aspirazione funzionanti, pulite e non ostruite.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""}
                        ]
                    },
                    {
                        "id": "S3",
                        "title": "3. GESTIONE E IGIENE AMBIENTALE (4 Controlli)",
                        "icon": "Package",
                        "items": [
                            {"id": "I3.1", "requirement": "Contenitori dei rifiuti puliti, chiusi e identificati.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I3.2", "requirement": "Separazione corretta dei rifiuti (es. umido, secco, plastica).", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I3.3", "requirement": "Area di stoccaggio rifiuti (interna ed esterna) ordinata e sanificata.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I3.4", "requirement": "Frequenza di rimozione dei rifiuti adeguata a prevenire accumuli.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""}
                        ]
                    },
                    {
                        "id": "S4",
                        "title": "4. CONTROLLO PROCESSO E QUALITÀ (6 Controlli)",
                        "icon": "Settings",
                        "items": [
                            {"id": "I4.1", "requirement": "Monitoraggio e registrazione dei Punti Critici di Controllo (CCP).", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I4.2", "requirement": "Procedure di Buona Fabbricazione (GMP) rispettate (es. pulizia prima dell'avvio).", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I4.3", "requirement": "Verifica e calibrazione del Metal Detector eseguita e registrata.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I4.4", "requirement": "Corretta identificazione dei lotti di materie prime e semilavorati.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I4.5", "requirement": "Rispettate le temperature di stoccaggio dei prodotti finiti e intermedi.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I4.6", "requirement": "Corretta gestione, etichettatura e isolamento dei prodotti non conformi.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""}
                        ]
                    },
                    {
                        "id": "S5",
                        "title": "5. CONTROLLO INFESTANTI (5 Controlli)",
                        "icon": "Shield",
                        "items": [
                            {"id": "I5.1", "requirement": "Assenza di tracce visibili di roditori, insetti o uccelli.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I5.2", "requirement": "Stazioni di monitoraggio/trappole numerate, integre e registrate.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I5.3", "requirement": "Mappe e registri delle trappole aggiornati e disponibili.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I5.4", "requirement": "Barriere fisiche (es. reti, spazzole) anti-intrusione in buone condizioni.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I5.5", "requirement": "Prodotti chimici di controllo infestanti stoccati in modo sicuro e separato.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""}
                        ]
                    },
                    {
                        "id": "S6",
                        "title": "6. MANUTENZIONE E VETRI (6 Controlli)",
                        "icon": "Settings",
                        "items": [
                            {"id": "I6.1", "requirement": "Piano di manutenzione preventiva e correttiva rispettato e registrato.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I6.2", "requirement": "Lubrificanti e oli utilizzati autorizzati per uso alimentare (se richiesto).", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I6.3", "requirement": "Registri di calibrazione/verifica degli strumenti di misura critici aggiornati.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I6.4", "requirement": "Gestione dei vetri rotti (registri rotture) aggiornata e conforme alla procedura.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I6.5", "requirement": "Assenza di perdite, gocciolamenti o cavi scoperti da impianti/macchinari.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I6.6", "requirement": "Area di deposito utensili e pezzi di ricambio ordinata e pulita.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""}
                        ]
                    },
                    {
                        "id": "S7",
                        "title": "7. DOCUMENTAZIONE E FORMAZIONE (5 Controlli)",
                        "icon": "FileText",
                        "items": [
                            {"id": "I7.1", "requirement": "Documentazione di processo (procedure, istruzioni) aggiornata e disponibile.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I7.2", "requirement": "Registri di formazione del personale aggiornati e verificabili.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I7.3", "requirement": "Certificazioni e attestati del personale validi e aggiornati.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I7.4", "requirement": "Controllo documenti (versioni, distribuzione, obsolescenza) conforme.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""},
                            {"id": "I7.5", "requirement": "Archiviazione e conservazione documenti secondo i requisiti normativi.", "compliance": "N/A", "deviation": "", "action": "", "checkedAt": None, "checkedBy": ""}
                        ]
                    }
                ],
                "totalItems": 38,
                "completedItems": 0,
                "nonCompliantItems": 0,
                "complianceScore": 0.0,
                "verificationDate": None,
                "createdAt": datetime.utcnow(),
                "updatedAt": datetime.utcnow()
            }
            
            # Insert the new checklist
            result = await db.checklists.insert_one(default_checklist)
            checklist_doc = await db.checklists.find_one({"_id": result.inserted_id})
            logger.info(f"Created new checklist for user {user_id}")
        
        # Serialize the document
        serialized_checklist = serialize_checklist(checklist_doc)
        
        return ChecklistResponse(
            success=True,
            data=ChecklistData(**serialized_checklist),
            message="Checklist retrieved successfully"
        )
        
    except Exception as e:
        logger.error(f"Error retrieving checklist for user {user_id}: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to retrieve checklist: {str(e)}"
        )

@app.put("/api/checklist/{user_id}", response_model=ChecklistResponse)
async def save_checklist(user_id: str, checklist_data: dict):
    """
    Save or update checklist data for a specific user
    
    This endpoint saves the checklist data to the database. It calculates
    compliance metrics and updates the timestamp.
    
    Args:
        user_id: Unique identifier for the user
        checklist_data: The checklist data to save
        
    Returns:
        ChecklistResponse confirming the save operation
        
    Raises:
        HTTPException: If database operation fails
    """
    try:
        logger.info(f"Saving checklist for user: {user_id}")
        
        # Use the dictionary directly (already converted from JSON)
        checklist_dict = checklist_data.copy()
        
        # Calculate compliance metrics
        metrics = calculate_checklist_metrics(checklist_dict)
        checklist_dict.update(metrics)
        
        # Handle image data for non-compliant checklists
        compliance_score = metrics.get('complianceScore', 0.0)
        if compliance_score < 100.0 and 'collectedImages' in checklist_dict and checklist_dict['collectedImages']:
            # Process collected images from individual items
            collected_images = checklist_dict['collectedImages']
            logger.info(f"Storing {len(collected_images)} images for non-compliant checklist (score: {compliance_score}%)")
            
            # Store the collected images in the checklist data
            checklist_dict['imageData'] = collected_images
            checklist_dict['imageType'] = 'multiple_items'
        elif compliance_score < 100.0:
            logger.info(f"No image data provided for non-compliant checklist (score: {compliance_score}%)")
        
        # Update timestamps
        checklist_dict['updatedAt'] = datetime.utcnow()
        
        # Check if this is an update to existing checklist or new save
        existing_checklist = await db.checklists.find_one({"userId": user_id})
        
        if existing_checklist:
            # Update existing checklist
            checklist_dict['createdAt'] = existing_checklist.get('createdAt', datetime.utcnow())
            
            # Remove _id if it exists to prevent immutable field error
            if '_id' in checklist_dict:
                del checklist_dict['_id']
            
            result = await db.checklists.update_one(
                {"userId": user_id},
                {"$set": checklist_dict}
            )
            
            if result.modified_count > 0:
                logger.info(f"Updated existing checklist for user {user_id}")
                message = "Checklist updated successfully"
            else:
                logger.error(f"Failed to update checklist for user {user_id}")
                raise HTTPException(
                    status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                    detail="Failed to update checklist"
                )
        else:
            # Create new checklist
            checklist_dict['createdAt'] = datetime.utcnow()
            
            # Remove _id if it exists to let MongoDB generate a new one
            if '_id' in checklist_dict:
                del checklist_dict['_id']
            
            result = await db.checklists.insert_one(checklist_dict)
            
            if result.inserted_id:
                logger.info(f"Created new checklist for user {user_id}")
                message = "Checklist created successfully"
            else:
                logger.error(f"Failed to create checklist for user {user_id}")
                raise HTTPException(
                    status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                    detail="Failed to save checklist"
                )
        
        # Retrieve the updated/created checklist
        if existing_checklist:
            # For updates, get the updated document
            updated_checklist = await db.checklists.find_one({"userId": user_id})
            serialized_checklist = serialize_checklist(updated_checklist)
        else:
            # For new checklists, get the newly created document
            created_checklist = await db.checklists.find_one({"_id": result.inserted_id})
            serialized_checklist = serialize_checklist(created_checklist)
        
        return ChecklistResponse(
            success=True,
            data=serialized_checklist,  # Return as dict instead of Pydantic model
            message=message
        )
        
    except Exception as e:
        logger.error(f"Error saving checklist for user {user_id}: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to save checklist: {str(e)}"
        )

@app.get("/api/checklists/by-user/{user_name}", response_model=Dict[str, Any])
async def get_checklists_by_user_name(user_name: str):
    """
    Retrieve all checklists for a specific user name
    
    Args:
        user_name: The name of the user to retrieve checklists for
        
    Returns:
        Dictionary containing list of checklists for the user
        
    Raises:
        HTTPException: If database operation fails
    """
    try:
        logger.info(f"Retrieving checklists for user: {user_name}")
        
        # Find all checklists where metadata.userName matches
        cursor = db.checklists.find({"metadata.userName": user_name})
        checklists = []
        
        async for checklist_doc in cursor:
            serialized_checklist = serialize_checklist(checklist_doc)
            checklists.append(serialized_checklist)
        
        return {
            "success": True,
            "data": checklists,
            "count": len(checklists),
            "user_name": user_name
        }
        
    except Exception as e:
        logger.error(f"Error retrieving checklists for user {user_name}: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to retrieve checklists for user: {str(e)}"
        )

@app.post("/api/checklist/{user_id}/image")
async def upload_checklist_image(user_id: str, image: UploadFile = File(...)):
    """
    Upload an image for a checklist (for non-compliant cases)
    
    Args:
        user_id: Unique identifier for the user
        image: The image file to upload
        
    Returns:
        Dictionary containing the base64 encoded image data and metadata
    """
    try:
        logger.info(f"Uploading image for user: {user_id}")
        
        # Validate image file type
        allowed_types = ["image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp"]
        if image.content_type not in allowed_types:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"Invalid image type. Allowed types: {', '.join(allowed_types)}"
            )
        
        # Read image data
        image_data = await image.read()
        
        # Encode to base64
        base64_data = base64.b64encode(image_data).decode('utf-8')
        
        # Create data URL
        data_url = f"data:{image.content_type};base64,{base64_data}"
        
        logger.info(f"Image uploaded successfully for user {user_id}, size: {len(image_data)} bytes")
        
        return {
            "success": True,
            "data": {
                "imageData": base64_data,
                "imageType": image.content_type,
                "dataUrl": data_url,
                "size": len(image_data),
                "filename": image.filename
            },
            "message": "Image uploaded successfully"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error uploading image for user {user_id}: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to upload image: {str(e)}"
        )

async def ensure_default_template_exists():
    """
    Ensure the default template exists in the database.
    Creates it if it doesn't exist.
    """
    try:
        logger.info("Checking if default template exists...")
        # Check if template exists (check both old and new IDs)
        template = await db.checklist_templates.find_one({
            "$or": [
                {"templateId": "default"},
                {"templateId": "default-audit-checklist"}
            ]
        })
        
        if not template:
            logger.info("Default template not found, creating it now...")
            
            # Create the default template
            default_template = {
                "templateId": "default",
                "title": "Checklist di Audit Operativo",
                "sections": [
                    {
                        "id": "S1",
                        "title": "1. PERSONALE E IGIENE",
                        "icon": "Users",
                        "items": [
                            {"id": "I1.1", "requirement": "Indumenti da lavoro puliti (divisa, grembiule)."},
                            {"id": "I1.2", "requirement": "Scarpe antinfortunistiche / Calzature pulite."},
                            {"id": "I1.3", "requirement": "Cuffie e/o Retine per capelli indossate correttamente."},
                            {"id": "I1.4", "requirement": "Assenza di gioielli, piercing visibili, unghie lunghe."},
                            {"id": "I1.5", "requirement": "Lavaggio mani documentato all'ingresso/reingresso."},
                            {"id": "I1.6", "requirement": "Assenza di cibo/bevande non autorizzate nelle aree produttive."},
                        ],
                    },
                    {
                        "id": "S2",
                        "title": "2. STRUTTURE E IMPIANTI",
                        "icon": "Building",
                        "items": [
                            {"id": "I2.1", "requirement": "Illuminazione adeguata e funzionante in tutte le aree."},
                            {"id": "I2.2", "requirement": "Porte esterne/interne in buone condizioni e chiuse correttamente (sigillatura)."},
                            {"id": "I2.3", "requirement": "Integrità di pavimenti, pareti e soffitti (assenza di crepe/danni)."},
                            {"id": "I2.4", "requirement": "Controllo vetri / lampade protette o anti-frantumazione."},
                            {"id": "I2.5", "requirement": "Condizioni igieniche dei servizi igienici e spogliatoi (pulizia e dotazioni)."},
                            {"id": "I2.6", "requirement": "Ventilazione e aspirazione funzionanti, pulite e non ostruite."},
                        ],
                    },
                    {
                        "id": "S3",
                        "title": "3. GESTIONE E IGIENE AMBIENTALE",
                        "icon": "Package",
                        "items": [
                            {"id": "I3.1", "requirement": "Contenitori dei rifiuti puliti, chiusi e identificati."},
                            {"id": "I3.2", "requirement": "Separazione corretta dei rifiuti (es. umido, secco, plastica)."},
                            {"id": "I3.3", "requirement": "Area di stoccaggio rifiuti (interna ed esterna) ordinata e sanificata."},
                            {"id": "I3.4", "requirement": "Frequenza di rimozione dei rifiuti adeguata a prevenire accumuli."},
                        ],
                    },
                    {
                        "id": "S4",
                        "title": "4. CONTROLLO PROCESSO E QUALITÀ",
                        "icon": "Settings",
                        "items": [
                            {"id": "I4.1", "requirement": "Monitoraggio e registrazione dei Punti Critici di Controllo (CCP)."},
                            {"id": "I4.2", "requirement": "Procedure di Buona Fabbricazione (GMP) rispettate (es. pulizia prima dell'avvio)."},
                            {"id": "I4.3", "requirement": "Verifica e calibrazione del Metal Detector eseguita e registrata."},
                            {"id": "I4.4", "requirement": "Corretta identificazione dei lotti di materie prime e semilavorati."},
                            {"id": "I4.5", "requirement": "Rispettate le temperature di stoccaggio dei prodotti finiti e intermedi."},
                            {"id": "I4.6", "requirement": "Corretta gestione, etichettatura e isolamento dei prodotti non conformi."},
                        ],
                    },
                    {
                        "id": "S5",
                        "title": "5. CONTROLLO INFESTANTI",
                        "icon": "Shield",
                        "items": [
                            {"id": "I5.1", "requirement": "Assenza di tracce visibili di roditori, insetti o uccelli."},
                            {"id": "I5.2", "requirement": "Stazioni di monitoraggio/trappole numerate, integre e registrate."},
                            {"id": "I5.3", "requirement": "Mappe e registri delle trappole aggiornati e disponibili."},
                            {"id": "I5.4", "requirement": "Barriere fisiche (es. reti, spazzole) anti-intrusione in buone condizioni."},
                            {"id": "I5.5", "requirement": "Prodotti chimici di controllo infestanti stoccati in modo sicuro e separato."},
                        ],
                    },
                    {
                        "id": "S6",
                        "title": "6. MANUTENZIONE E VETRI",
                        "icon": "Settings",
                        "items": [
                            {"id": "I6.1", "requirement": "Piano di manutenzione preventiva e correttiva rispettato e registrato."},
                            {"id": "I6.2", "requirement": "Lubrificanti e oli utilizzati autorizzati per uso alimentare (se richiesto)."},
                            {"id": "I6.3", "requirement": "Registri di calibrazione/verifica degli strumenti di misura critici aggiornati."},
                            {"id": "I6.4", "requirement": "Gestione dei vetri rotti (registri rotture) aggiornata e conforme alla procedura."},
                            {"id": "I6.5", "requirement": "Assenza di perdite, gocciolamenti o cavi scoperti da impianti/macchinari."},
                            {"id": "I6.6", "requirement": "Area di deposito utensili e pezzi di ricambio ordinata e pulita."},
                        ],
                    },
                    {
                        "id": "S7",
                        "title": "7. DOCUMENTAZIONE E FORMAZIONE",
                        "icon": "FileText",
                        "items": [
                            {"id": "I7.1", "requirement": "Documentazione di processo (procedure, istruzioni) aggiornata e disponibile."},
                            {"id": "I7.2", "requirement": "Registri di formazione del personale aggiornati e verificabili."},
                            {"id": "I7.3", "requirement": "Certificazioni e attestati del personale validi e aggiornati."},
                            {"id": "I7.4", "requirement": "Controllo documenti (versioni, distribuzione, obsolescenza) conforme."},
                            {"id": "I7.5", "requirement": "Archiviazione e conservazione documenti secondo i requisiti normativi."},
                        ],
                    },
                ],
                "metadata": {
                    "createdAt": datetime.utcnow().isoformat(),
                    "updatedAt": datetime.utcnow().isoformat(),
                }
            }
            
            result = await db.checklist_templates.insert_one(default_template)
            logger.info(f"✅ Successfully created default template with ID: {result.inserted_id}")
            # Fetch the newly created template to return with _id
            template = await db.checklist_templates.find_one({"templateId": "default"})
            return template
        else:
            logger.info("✅ Default template already exists in database")
            return template
            
    except Exception as e:
        logger.error(f"❌ Error ensuring default template exists: {e}", exc_info=True)
        return None

@app.get("/api/checklist-template/default", response_model=Dict[str, Any])
async def get_default_checklist_template():
    """
    Get the default checklist template
    
    Returns:
        Dictionary containing the default checklist template structure
        
    Raises:
        HTTPException: If template not found or database operation fails
    """
    try:
        logger.info("📋 GET /api/checklist-template/default - Retrieving default checklist template")
        
        # Ensure template exists (creates if not found)
        template_doc = await ensure_default_template_exists()
        logger.info(f"Template check result: {'Found' if template_doc else 'Not Found'}")
        
        if not template_doc:
            # Fallback to looking for old template ID
            logger.info("Checking for old template ID: default-audit-checklist")
            template_doc = await db.checklist_templates.find_one({"templateId": "default-audit-checklist"})
        
        if not template_doc:
            # If template doesn't exist, create it from the hardcoded structure
            logger.info("Default template not found, creating from hardcoded structure")
            
            # Use the same structure as in get_checklist but mark as template
            default_template = {
                "templateId": "default-audit-checklist",
                "title": "Checklist di Audit Operativo (38 Controlli)",
                "description": "Template per audit operativo in ambiente di produzione alimentare",
                "version": "1.0",
                "isTemplate": True,
                "createdAt": datetime.utcnow(),
                "updatedAt": datetime.utcnow(),
                "sections": [
                    {
                        "id": "S1",
                        "title": "1. PERSONALE E IGIENE",
                        "icon": "Users",
                        "items": [
                            {"id": "I1.1", "requirement": "Indumenti da lavoro puliti (divisa, grembiule).", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I1.2", "requirement": "Scarpe antinfortunistiche / Calzature pulite.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I1.3", "requirement": "Cuffie e/o Retine per capelli indossate correttamente.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I1.4", "requirement": "Assenza di gioielli, piercing visibili, unghie lunghe.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I1.5", "requirement": "Lavaggio mani documentato all'ingresso/reingresso.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I1.6", "requirement": "Assenza di cibo/bevande non autorizzate nelle aree produttive.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None}
                        ]
                    },
                    {
                        "id": "S2",
                        "title": "2. STRUTTURE E IMPIANTI",
                        "icon": "Building",
                        "items": [
                            {"id": "I2.1", "requirement": "Illuminazione adeguata e funzionante in tutte le aree.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I2.2", "requirement": "Porte esterne/interne in buone condizioni e chiuse correttamente (sigillatura).", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I2.3", "requirement": "Integrità di pavimenti, pareti e soffitti (assenza di crepe/danni).", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I2.4", "requirement": "Controllo vetri / lampade protette o anti-frantumazione.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I2.5", "requirement": "Condizioni igieniche dei servizi igienici e spogliatoi (pulizia e dotazioni).", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I2.6", "requirement": "Ventilazione e aspirazione funzionanti, pulite e non ostruite.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None}
                        ]
                    },
                    {
                        "id": "S3",
                        "title": "3. GESTIONE E IGIENE AMBIENTALE",
                        "icon": "Package",
                        "items": [
                            {"id": "I3.1", "requirement": "Contenitori dei rifiuti puliti, chiusi e identificati.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I3.2", "requirement": "Separazione corretta dei rifiuti (es. umido, secco, plastica).", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I3.3", "requirement": "Area di stoccaggio rifiuti (interna ed esterna) ordinata e sanificata.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I3.4", "requirement": "Frequenza di rimozione dei rifiuti adeguata a prevenire accumuli.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None}
                        ]
                    },
                    {
                        "id": "S4",
                        "title": "4. CONTROLLO PROCESSO E QUALITÀ",
                        "icon": "Settings",
                        "items": [
                            {"id": "I4.1", "requirement": "Monitoraggio e registrazione dei Punti Critici di Controllo (CCP).", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I4.2", "requirement": "Procedure di Buona Fabbricazione (GMP) rispettate (es. pulizia prima dell'avvio).", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I4.3", "requirement": "Verifica e calibrazione del Metal Detector eseguita e registrata.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I4.4", "requirement": "Corretta identificazione dei lotti di materie prime e semilavorati.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I4.5", "requirement": "Rispettate le temperature di stoccaggio dei prodotti finiti e intermedi.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I4.6", "requirement": "Corretta gestione, etichettatura e isolamento dei prodotti non conformi.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None}
                        ]
                    },
                    {
                        "id": "S5",
                        "title": "5. CONTROLLO INFESTANTI",
                        "icon": "Shield",
                        "items": [
                            {"id": "I5.1", "requirement": "Assenza di tracce visibili di roditori, insetti o uccelli.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I5.2", "requirement": "Stazioni di monitoraggio/trappole numerate, integre e registrate.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I5.3", "requirement": "Mappe e registri delle trappole aggiornati e disponibili.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I5.4", "requirement": "Barriere fisiche (es. reti, spazzole) anti-intrusione in buone condizioni.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I5.5", "requirement": "Prodotti chimici di controllo infestanti stoccati in modo sicuro e separato.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None}
                        ]
                    },
                    {
                        "id": "S6",
                        "title": "6. MANUTENZIONE E VETRI",
                        "icon": "Settings",
                        "items": [
                            {"id": "I6.1", "requirement": "Piano di manutenzione preventiva e correttiva rispettato e registrato.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I6.2", "requirement": "Lubrificanti e oli utilizzati autorizzati per uso alimentare (se richiesto).", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I6.3", "requirement": "Registri di calibrazione/verifica degli strumenti di misura critici aggiornati.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I6.4", "requirement": "Gestione dei vetri rotti (registri rotture) aggiornata e conforme alla procedura.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I6.5", "requirement": "Assenza di perdite, gocciolamenti o cavi scoperti da impianti/macchinari.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I6.6", "requirement": "Area di deposito utensili e pezzi di ricambio ordinata e pulita.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None}
                        ]
                    },
                    {
                        "id": "S7",
                        "title": "7. DOCUMENTAZIONE E FORMAZIONE",
                        "icon": "FileText",
                        "items": [
                            {"id": "I7.1", "requirement": "Documentazione di processo (procedure, istruzioni) aggiornata e disponibile.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I7.2", "requirement": "Registri di formazione del personale aggiornati e verificabili.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I7.3", "requirement": "Certificazioni e attestati del personale validi e aggiornati.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I7.4", "requirement": "Controllo documenti (versioni, distribuzione, obsolescenza) conforme.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None},
                            {"id": "I7.5", "requirement": "Archiviazione e conservazione documenti secondo i requisiti normativi.", "compliance": "N/A", "deviation": "", "action": "", "imageData": None}
                        ]
                    }
                ],
                "totalItems": 38,
                "completedItems": 0,
                "nonCompliantItems": 0,
                "complianceScore": 0.0
            }
            
            # Insert the template
            await db.checklist_templates.insert_one(default_template)
            template_doc = default_template
        
        # Serialize the document
        serialized_template = serialize_checklist(template_doc)
        
        return {
            "success": True,
            "data": serialized_template,
            "message": "Default checklist template retrieved successfully"
        }
        
    except Exception as e:
        logger.error(f"Error retrieving default checklist template: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to retrieve checklist template: {str(e)}"
        )

@app.post("/api/checklist-template/item", response_model=Dict[str, Any])
async def add_template_item(item_data: dict):
    """
    Add a new item to the shared checklist template
    
    Args:
        item_data: Dictionary containing item information (sectionId, requirement, etc.)
        
    Returns:
        Dictionary confirming the item was added
        
    Raises:
        HTTPException: If database operation fails
    """
    try:
        logger.info(f"Adding new item to shared template")
        
        # Ensure template exists first and get it
        template = await ensure_default_template_exists()
        
        if not template:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Template not found"
            )
        
        template_id = template.get("templateId", "default")
        
        # Find the section and add the new item
        section_id = item_data.get('sectionId')
        section_index = next((i for i, s in enumerate(template['sections']) if s['id'] == section_id), None)
        
        if section_index is None:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Section {section_id} not found"
            )
        
        new_item = {
            "id": item_data.get('id', f"I{section_id[-1]}.{len(template['sections'][section_index]['items'])+1}"),
            "requirement": item_data.get('requirement', ''),
        }
        
        # Update the template
        result = await db.checklist_templates.update_one(
            {"templateId": template_id, "sections.id": section_id},
            {"$push": {"sections.$.items": new_item}}
        )
        
        if result.modified_count > 0:
            logger.info(f"Successfully added item to template")
            return {
                "success": True,
                "message": "Item added successfully",
                "data": new_item
            }
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Failed to add item"
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error adding item to template: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to add item: {str(e)}"
        )

@app.put("/api/checklist-template/item/{item_id}", response_model=Dict[str, Any])
async def update_template_item(item_id: str, item_data: dict):
    """
    Update an existing item in the shared checklist template
    
    Args:
        item_id: ID of the item to update
        item_data: Dictionary containing updated item information
        
    Returns:
        Dictionary confirming the item was updated
        
    Raises:
        HTTPException: If database operation fails
    """
    try:
        logger.info(f"Updating item {item_id} in shared template")
        
        # Ensure template exists first and get it
        template = await ensure_default_template_exists()
        template_id = template.get("templateId") if template else "default"
        
        # Prepare update fields
        update_fields = {}
        if 'requirement' in item_data:
            update_fields["sections.$[].items.$[item].requirement"] = item_data['requirement']
        
        if not update_fields:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="No valid fields to update"
            )
        
        # Update the item in template (use the template ID we found)
        result = await db.checklist_templates.update_one(
            {"templateId": template_id},
            {"$set": update_fields},
            array_filters=[{"item.id": item_id}]
        )
        
        if result.modified_count > 0:
            logger.info(f"Successfully updated item {item_id} in template")
            return {
                "success": True,
                "message": "Item updated successfully",
                "data": item_data
            }
        else:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Item not found or no changes made"
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error updating item {item_id} in template: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to update item: {str(e)}"
        )

@app.delete("/api/checklist-template/item/{item_id}", response_model=Dict[str, Any])
async def delete_template_item(item_id: str):
    """
    Delete an item from the shared checklist template
    
    Args:
        item_id: ID of the item to delete
        
    Returns:
        Dictionary confirming the item was deleted
        
    Raises:
        HTTPException: If database operation fails
    """
    try:
        logger.info(f"Deleting item {item_id} from shared template")
        
        # Ensure template exists first and get it
        template = await ensure_default_template_exists()
        template_id = template.get("templateId") if template else "default"
        
        # Remove the item from the template
        result = await db.checklist_templates.update_one(
            {"templateId": template_id},
            {"$pull": {"sections.$[].items": {"id": item_id}}}
        )
        
        if result.modified_count > 0:
            logger.info(f"Successfully deleted item {item_id} from template")
            return {
                "success": True,
                "message": "Item deleted successfully"
            }
        else:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Item not found"
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error deleting item {item_id} from template: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to delete item: {str(e)}"
        )

@app.post("/api/checklist-template/section", response_model=Dict[str, Any])
async def add_template_section(section_data: dict):
    """
    Add a new section to the shared checklist template
    
    Args:
        section_data: Dictionary containing section information
        
    Returns:
        Dictionary confirming the section was added
        
    Raises:
        HTTPException: If database operation fails
    """
    try:
        logger.info(f"Adding new section to shared template")
        
        # Ensure template exists first and get it
        template = await ensure_default_template_exists()
        
        if not template:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Template not found"
            )
        
        template_id = template.get("templateId", "default")
        
        # Create new section
        new_section = {
            "id": section_data.get('id', f"S{len(template['sections'])+1}"),
            "title": section_data.get('title', 'New Section'),
            "icon": section_data.get('icon', 'Settings'),
            "items": []
        }
        
        # Add the new section
        result = await db.checklist_templates.update_one(
            {"templateId": template_id},
            {"$push": {"sections": new_section}}
        )
        
        if result.modified_count > 0:
            logger.info(f"Successfully added section to template")
            return {
                "success": True,
                "message": "Section added successfully",
                "data": new_section
            }
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Failed to add section"
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error adding section to template: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to add section: {str(e)}"
        )

@app.delete("/api/checklist-template/section/{section_id}", response_model=Dict[str, Any])
async def delete_template_section(section_id: str):
    """
    Delete a section from the shared checklist template
    
    Args:
        section_id: ID of the section to delete
        
    Returns:
        Dictionary confirming the section was deleted
        
    Raises:
        HTTPException: If database operation fails
    """
    try:
        logger.info(f"Deleting section {section_id} from shared template")
        
        # Ensure template exists first and get it
        template = await ensure_default_template_exists()
        template_id = template.get("templateId") if template else "default"
        
        # Remove the section from the template
        result = await db.checklist_templates.update_one(
            {"templateId": template_id},
            {"$pull": {"sections": {"id": section_id}}}
        )
        
        if result.modified_count > 0:
            logger.info(f"Successfully deleted section {section_id} from template")
            return {
                "success": True,
                "message": "Section deleted successfully"
            }
        else:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Section not found"
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error deleting section {section_id} from template: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to delete section: {str(e)}"
        )

@app.post("/api/checklist/{user_id}/item", response_model=Dict[str, Any])
async def add_checklist_item(user_id: str, item_data: dict):
    """
    Add a new item to a checklist
    
    Args:
        user_id: Unique identifier for the user
        item_data: Dictionary containing item information (sectionId, requirement, etc.)
        
    Returns:
        Dictionary confirming the item was added
        
    Raises:
        HTTPException: If database operation fails
    """
    try:
        logger.info(f"Adding new item to checklist for user: {user_id}")
        
        # Get the user's checklist
        checklist_doc = await db.checklists.find_one({"userId": user_id})
        
        if not checklist_doc:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Checklist not found for user"
            )
        
        # Find the section and add the new item
        section_id = item_data.get('sectionId')
        new_item = {
            "id": item_data.get('id', f"I{section_id}.{len(checklist_doc['sections'][int(section_id[-1])-1]['items'])+1}"),
            "requirement": item_data.get('requirement', ''),
            "compliance": "N/A",
            "deviation": "",
            "action": "",
            "imageData": None,
            "checkedAt": None,
            "checkedBy": ""
        }
        
        # Update the checklist
        result = await db.checklists.update_one(
            {"userId": user_id, "sections.id": section_id},
            {"$push": {f"sections.$.items": new_item}}
        )
        
        if result.modified_count > 0:
            logger.info(f"Successfully added item to checklist for user {user_id}")
            return {
                "success": True,
                "message": "Item added successfully",
                "data": new_item
            }
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Failed to add item"
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error adding item for user {user_id}: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to add item: {str(e)}"
        )

@app.put("/api/checklist/{user_id}/item/{item_id}", response_model=Dict[str, Any])
async def update_checklist_item(user_id: str, item_id: str, item_data: dict):
    """
    Update an existing checklist item
    
    Args:
        user_id: Unique identifier for the user
        item_id: ID of the item to update
        item_data: Dictionary containing updated item information
        
    Returns:
        Dictionary confirming the item was updated
        
    Raises:
        HTTPException: If database operation fails
    """
    try:
        logger.info(f"Updating item {item_id} for user: {user_id}")
        
        # Check if checklist exists
        checklist = await db.checklists.find_one({"userId": user_id})
        if not checklist:
            logger.warning(f"No checklist found for user {user_id}")
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Checklist not found for user {user_id}. Please create a checklist first."
            )
        
        # Prepare update fields
        update_fields = {}
        for field in ['requirement', 'compliance', 'deviation', 'action']:
            if field in item_data:
                update_fields[f"sections.$[].items.$[item].{field}"] = item_data[field]
        
        if not update_fields:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="No valid fields to update"
            )
        
        # Update the item
        result = await db.checklists.update_one(
            {"userId": user_id},
            {"$set": update_fields},
            array_filters=[{"item.id": item_id}]
        )
        
        if result.modified_count > 0:
            logger.info(f"Successfully updated item {item_id} for user {user_id}")
            return {
                "success": True,
                "message": "Item updated successfully",
                "data": item_data
            }
        else:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Item not found or no changes made"
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error updating item {item_id} for user {user_id}: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to update item: {str(e)}"
        )

@app.delete("/api/checklist/{user_id}/item/{item_id}", response_model=Dict[str, Any])
async def delete_checklist_item(user_id: str, item_id: str):
    """
    Delete a checklist item
    
    Args:
        user_id: Unique identifier for the user
        item_id: ID of the item to delete
        
    Returns:
        Dictionary confirming the item was deleted
        
    Raises:
        HTTPException: If database operation fails
    """
    try:
        logger.info(f"Deleting item {item_id} for user: {user_id}")
        
        # Check if checklist exists
        checklist = await db.checklists.find_one({"userId": user_id})
        if not checklist:
            logger.warning(f"No checklist found for user {user_id}")
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Checklist not found for user {user_id}. Please create a checklist first."
            )
        
        # Remove the item from the checklist
        result = await db.checklists.update_one(
            {"userId": user_id},
            {"$pull": {"sections.$[].items": {"id": item_id}}}
        )
        
        if result.modified_count > 0:
            logger.info(f"Successfully deleted item {item_id} for user {user_id}")
            return {
                "success": True,
                "message": "Item deleted successfully"
            }
        else:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Item not found"
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error deleting item {item_id} for user {user_id}: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to delete item: {str(e)}"
        )

@app.post("/api/checklist/{user_id}/section", response_model=Dict[str, Any])
async def add_checklist_section(user_id: str, section_data: dict):
    """
    Add a new section to a checklist
    
    Args:
        user_id: Unique identifier for the user
        section_data: Dictionary containing section information
        
    Returns:
        Dictionary confirming the section was added
        
    Raises:
        HTTPException: If database operation fails
    """
    try:
        logger.info(f"Adding new section to checklist for user: {user_id}")
        
        # Get the user's checklist
        checklist_doc = await db.checklists.find_one({"userId": user_id})
        
        if not checklist_doc:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Checklist not found for user"
            )
        
        # Create new section
        new_section = {
            "id": section_data.get('id', f"S{len(checklist_doc['sections'])+1}"),
            "title": section_data.get('title', 'New Section'),
            "icon": section_data.get('icon', 'Settings'),
            "items": []
        }
        
        # Add the new section
        result = await db.checklists.update_one(
            {"userId": user_id},
            {"$push": {"sections": new_section}}
        )
        
        if result.modified_count > 0:
            logger.info(f"Successfully added section to checklist for user {user_id}")
            return {
                "success": True,
                "message": "Section added successfully",
                "data": new_section
            }
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail="Failed to add section"
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error adding section for user {user_id}: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to add section: {str(e)}"
        )

@app.delete("/api/checklist/{user_id}/section/{section_id}", response_model=Dict[str, Any])
async def delete_checklist_section(user_id: str, section_id: str):
    """
    Delete a checklist section and all its items
    
    Args:
        user_id: Unique identifier for the user
        section_id: ID of the section to delete
        
    Returns:
        Dictionary confirming the section was deleted
        
    Raises:
        HTTPException: If database operation fails
    """
    try:
        logger.info(f"Deleting section {section_id} for user: {user_id}")
        
        # Check if checklist exists
        checklist = await db.checklists.find_one({"userId": user_id})
        if not checklist:
            logger.warning(f"No checklist found for user {user_id}")
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=f"Checklist not found for user {user_id}. Please create a checklist first."
            )
        
        # Remove the section from the checklist
        result = await db.checklists.update_one(
            {"userId": user_id},
            {"$pull": {"sections": {"id": section_id}}}
        )
        
        if result.modified_count > 0:
            logger.info(f"Successfully deleted section {section_id} for user {user_id}")
            return {
                "success": True,
                "message": "Section deleted successfully"
            }
        else:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Section not found"
            )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error deleting section {section_id} for user {user_id}: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to delete section: {str(e)}"
        )

@app.get("/api/checklists", response_model=Dict[str, Any])
async def get_all_checklists():
    """
    Retrieve all checklists (admin endpoint)
    
    This endpoint returns all checklists in the database. It's intended for
    administrative purposes and should be protected with proper authentication
    in a production environment.
    
    Returns:
        Dictionary containing list of all checklists
        
    Raises:
        HTTPException: If database operation fails
    """
    try:
        logger.info("Retrieving all checklists")
        
        # Find all checklists
        cursor = db.checklists.find({})
        checklists = []
        
        async for checklist_doc in cursor:
            serialized_checklist = serialize_checklist(checklist_doc)
            checklists.append(serialized_checklist)
        
        return {
            "success": True,
            "data": checklists,
            "count": len(checklists),
            "message": f"Retrieved {len(checklists)} checklists"
        }
        
    except Exception as e:
        logger.error(f"Error retrieving all checklists: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to retrieve checklists: {str(e)}"
        )

# =============================================================================
# ERROR HANDLERS
# =============================================================================

@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    """Handle HTTP exceptions with consistent error format"""
    logger.error(f"HTTP Exception: {exc.detail}")
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "success": False,
            "error": exc.detail,
            "status_code": exc.status_code
        }
    )

@app.exception_handler(Exception)
async def general_exception_handler(request, exc):
    """Handle general exceptions with logging"""
    logger.error(f"Unhandled exception: {exc}", exc_info=True)
    return JSONResponse(
        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
        content={
            "success": False,
            "error": "Internal server error",
            "detail": str(exc) if os.getenv("DEBUG", "false").lower() == "true" else "An unexpected error occurred"
        }
    )

# =============================================================================
# MAIN EXECUTION
# =============================================================================

if __name__ == "__main__":
    """
    Main execution block for running the server
    
    This block is executed when the script is run directly (not imported).
    It starts the Uvicorn ASGI server with the configured settings.
    """
    import uvicorn
    
    logger.info("Starting FastAPI server...")
    
    # Run the server
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=PORT,
        reload=True,  # Enable auto-reload for development
        log_level="info"
    )