File size: 72,639 Bytes
2f6bb1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c38cde
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
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
// server.js
import fs from "fs";
import path from "path";
import crypto from "crypto";
import fetch from "node-fetch";
import express from "express";
import bodyParser from "body-parser";
import PDFDocument from "pdfkit";
import sharp from "sharp";
import moment from "moment-timezone";
import cors from "cors";

// Configuration (all from environment variables)
const BASE_URL = process.env.BASE_URL || "https://rakshitjan-cps-b2c.hf.space";
const ADMIN_EMAIL = process.env.ADMIN_EMAIL || "admin123@example.com";
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || "SecurePass123";
const AES_KEY_STR = process.env.AES_KEY_STR || "7E892875A52C59A3B588306B13C31FBD";
const AES_IV_STR = process.env.AES_IV_STR || "XYE45DKJ0967GFAZ";
const GOOGLE_MAPS_API_KEY = process.env.GOOGLE_MAPS_API_KEY || "AIzaSyBpna0F0J-c9QNBh8lSnfT2Z2uzD_vS9Ag"; // For geocoding
const GEOAPIFY_API_KEY = process.env.GEOAPIFY_API_KEY || "ceaea8a8a8f14f46b73221384eb4b5f0" ; // For static maps
const LOGO_PATH = process.env.LOGO_PATH || "logo.png";
const statelist = JSON.parse(fs.readFileSync("state.json", "utf8"));
const citylist = JSON.parse(fs.readFileSync("city.json", "utf8"));
const districtlist = JSON.parse(fs.readFileSync("district.json", "utf8"));
const organizationlist = JSON.parse(fs.readFileSync("organization.json", "utf8"));
const genderlist = JSON.parse(fs.readFileSync("gender.json", "utf8"));
const qualificationlist = JSON.parse(fs.readFileSync("qualification.json", "utf8"));
const ownershiplist = JSON.parse(fs.readFileSync("ownership.json", "utf8"));
const app = express();
app.use(bodyParser.json({ limit: "50mb" }));

// Allow ALL origins
app.use(cors());

// Utility: convert cm to PDF points (1 pt = 1/72 in; 1 cm = 28.3464567 pt)
const CM = 28.3464567;
const A4_WIDTH = 595.2755905511812; // points (210mm)
const A4_HEIGHT = 841.8897637795277; // points (297mm)
const MARGIN = 1.2 * CM;

// AES encryption like Python's Crypto.Cipher AES-CBC w/ PKCS7 padding
function aesEncrypt(plaintext, keyStr, ivStr) {
  // Validate inputs
  if (!plaintext) throw new Error("Plaintext is required for encryption");
  if (!keyStr) throw new Error("AES key is required");
  if (!ivStr) throw new Error("AES IV is required");
  
  const key = Buffer.from(keyStr, "utf8");
  const iv = Buffer.from(ivStr, "utf8");
  
  // Validate key and IV lengths
  if (key.length !== 16 && key.length !== 24 && key.length !== 32) {
    throw new Error(`Invalid AES key length: ${key.length} bytes. Must be 16, 24, or 32 bytes.`);
  }
  
  // Node's createCipheriv uses PKCS#7 padding by default (called PKCS#5 in OpenSSL)
  const cipher = crypto.createCipheriv(`aes-${key.length * 8}-cbc`, key, iv);
  const encrypted = Buffer.concat([
    cipher.update(Buffer.from(plaintext, "utf8")), 
    cipher.final()
  ]);
  return encrypted.toString("base64");
}

// HTTP session mimic (we reuse fetch)
let token = null;
async function adminLogin() {
  try {
    // encrypt email same as python
    const encryptedEmail = aesEncrypt(ADMIN_EMAIL, AES_KEY_STR, AES_IV_STR);
    
    const payload = {
      email: encryptedEmail,
      password: ADMIN_PASSWORD
    };
    
    console.log(`Logging in to ${BASE_URL} with admin email...`);
    
    const res = await fetch(`${BASE_URL}/api/admin/login`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
      timeout: 30000
    });
    
    const data = await res.json();
    
    if (res.status !== 200 || !data.token) {
      console.error(`Login failed. Status: ${res.status}, Response:`, data);
      throw new Error(`Login failed: ${JSON.stringify(data)}`);
    }
    
    token = data.token;
    console.log("Admin login successful");
    return token;
  } catch (error) {
    console.error("Admin login error:", error.message);
    throw error;
  }
}

async function getCase(caseId) {
  if (!token) await adminLogin();
  
  console.log(`Fetching case ${caseId}...`);
  const res = await fetch(`${BASE_URL}/api/cases/${caseId}`, {
    headers: { 
      "Content-Type": "application/json", 
      "Authorization": `Bearer ${token}` 
    },
    timeout: 30000
  });
  
  if (!res.ok) {
    console.error(`Failed to get case ${caseId}: ${res.status} ${res.statusText}`);
    throw new Error(`Failed get_case: ${res.status}`);
  }
  
  return await res.json();
}

async function getFiles(caseId) {
  if (!token) await adminLogin();
  
  console.log(`Fetching files for case ${caseId}...`);
  const res = await fetch(`${BASE_URL}/api/cases/${caseId}/files`, {
    headers: { 
      "Content-Type": "application/json", 
      "Authorization": `Bearer ${token}` 
    },
    timeout: 60000
  });
  
  if (!res.ok) {
    console.error(`Failed to get files for case ${caseId}: ${res.status} ${res.statusText}`);
    throw new Error(`Failed get_files: ${res.status}`);
  }
  
  const json = await res.json();
  console.log(`Retrieved ${json.files?.length || 0} files for case ${caseId}`);
  return json.files || [];
}

async function downloadFile(fileId) {
  if (!token) await adminLogin();
  
  console.log(`Downloading file ${fileId}...`);
  const res = await fetch(`${BASE_URL}/api/files/${fileId}`, {
    headers: { "Authorization": `Bearer ${token}` },
    timeout: 60000
  });
  
  if (!res.ok) {
    console.error(`File download failed for ${fileId}: ${res.status} ${res.statusText}`);
    throw new Error(`File download failed for ${fileId}: ${res.status}`);
  }
  
  const buf = await res.arrayBuffer();
  return Buffer.from(buf);
}

// Google Maps Geocoding API helpers (for forward/reverse geocoding)
async function forwardGeocode(address) {
  if (!address) {
    console.log("No address provided for geocoding");
    return [null, null];
  }
  
  if (!GOOGLE_MAPS_API_KEY) {
    console.error("GOOGLE_MAPS_API_KEY is not set");
    return [null, null];
  }
  
  console.log(`Geocoding address: ${address.substring(0, 50)}...`);
  
  try {
    const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}&key=${GOOGLE_MAPS_API_KEY}`;
    const res = await fetch(url, { timeout: 20000 });
    
    if (!res.ok) {
      console.error(`Geocoding API error: ${res.status} ${res.statusText}`);
      return [null, null];
    }
    
    const json = await res.json();
    
    if (json.status === "OK" && json.results && json.results[0] && json.results[0].geometry && json.results[0].geometry.location) {
      const loc = json.results[0].geometry.location;
      console.log(`Geocoding successful: ${loc.lat}, ${loc.lng}`);
      return [loc.lat, loc.lng];
    } else {
      console.warn(`Geocoding failed: ${json.status} - ${json.error_message || 'No results'}`);
      return [null, null];
    }
  } catch (error) {
    console.error("Geocoding error:", error.message);
    return [null, null];
  }
}

async function reverseGeocode(lat, lon) {
  if (lat == null || lon == null) {
    console.log("No coordinates provided for reverse geocoding");
    return "Unknown Address";
  }
  
  if (!GOOGLE_MAPS_API_KEY) {
    console.error("GOOGLE_MAPS_API_KEY is not set");
    return "Unknown Address";
  }
  
  console.log(`Reverse geocoding coordinates: ${lat}, ${lon}`);
  
  try {
    const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lon}&key=${GOOGLE_MAPS_API_KEY}`;
    const res = await fetch(url, { timeout: 20000 });
    
    if (!res.ok) {
      console.error(`Reverse geocoding API error: ${res.status} ${res.statusText}`);
      return "Unknown Address";
    }
    
    const json = await res.json();
    
    if (json.status === "OK" && json.results && json.results[0] && json.results[0].formatted_address) {
      const address = json.results[0].formatted_address;
      console.log(`Reverse geocoding successful: ${address.substring(0, 50)}...`);
      return address;
    } else {
      console.warn(`Reverse geocoding failed: ${json.status} - ${json.error_message || 'No results'}`);
      return "Unknown Address";
    }
  } catch (error) {
    console.error("Reverse geocoding error:", error.message);
    return "Unknown Address";
  }
}

// Geoapify Static Maps API (for static maps with markers and path)
async function staticMapWithPath(captureLat, captureLng, caseLat = null, caseLng = null, zoom = 17, size = "1800x600") {
  if (captureLat == null || captureLng == null) {
    console.log("No capture coordinates provided for static map");
    return null;
  }
  
  if (!GEOAPIFY_API_KEY) {
    console.error("GEOAPIFY_API_KEY is not set");
    return null;
  }
  
  console.log(`Generating static map for: ${captureLat}, ${captureLng}`);
  
  try {
    let parts = [
      `center=lonlat:${captureLng},${captureLat}`,
      `zoom=${zoom}`,
      `size=${size}`,
      `scaleFactor=2`,
      `marker=lonlat:${captureLng},${captureLat};color:%23ff0000;size:large`
    ];
    
    if (caseLat != null && caseLng != null) {
      parts.push(`marker=lonlat:${caseLng},${caseLat};color:%23007bff;size:large`);
      parts.push(`path=color:%23ff0000;weight:4|lonlat:${caseLng},${caseLat}|lonlat:${captureLng},${captureLat}`);
    }
    
    const url = `https://maps.geoapify.com/v1/staticmap?${parts.join("&")}&apiKey=${GEOAPIFY_API_KEY}`;
    const res = await fetch(url, { timeout: 30000 });
    
    if (!res.ok) {
      console.error(`Static map API error: ${res.status} ${res.statusText}`);
      return null;
    }
    
    const buf = Buffer.from(await res.arrayBuffer());
    console.log("Static map generated successfully");
    return buf;
  } catch (error) {
    console.error("Static map generation error:", error.message);
    return null;
  }
}

function haversineKm(lat1, lon1, lat2, lon2) {
  if ([lat1, lon1, lat2, lon2].some(v => v == null)) return null;
  const R = 6371.0;
  const phi1 = lat1 * Math.PI / 180;
  const phi2 = lat2 * Math.PI / 180;
  const dphi = (lat2 - lat1) * Math.PI / 180;
  const dlambda = (lon2 - lon1) * Math.PI / 180;
  const a = Math.sin(dphi / 2) * Math.sin(dphi / 2) + Math.cos(phi1) * Math.cos(phi2) * Math.sin(dlambda / 2) * Math.sin(dlambda / 2);
  return 2 * R * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}

// date formatting to IST similar to fmt_ist in python
function fmtIST(dtStr) {
  if (!dtStr) return "N/A";
  try {
    // Accept Z or offset
    const m = moment(dtStr);
    const ist = m.tz("Asia/Kolkata").format("DD/MM/YYYY hh:mm:ss A") + " IST";
    return ist;
  } catch {
    return dtStr;
  }
}

function exportedOnStr() {
  return moment().tz("Asia/Kolkata").format("MMMM DD, YYYY");
}

// Mapping display names
const DISPLAY_NAME = {
  "aadhaar_photo": "Photo of Aadhar",
  "customer_photo": "Customer's Photo",
  "residence_photo": "Residence Photo",
  "business_photo": "Business Address Photo"
};
function displayType(fileType) {
  return DISPLAY_NAME[fileType] || fileType || "Upload";
}

// create thumbnail similar to Python make_thumb
async function makeThumb(imgBuf, maxW = 860, maxH = 640) {
  try {
    // produce an RGB JPEG/PNG buffer sized with thumbnail
    const img = sharp(imgBuf).rotate().resize({ width: maxW, height: maxH, fit: "inside" }).flatten({ background: { r: 255, g: 255, b: 255 } });
    const png = await img.png().toBuffer();
    // create bordered image by extending canvas
    const bordered = await sharp(png)
      .extend({ top: 1, bottom: 1, left: 1, right: 1, background: { r: 170, g: 170, b: 170 } })
      .png()
      .toBuffer();
    return bordered;
  } catch (error) {
    console.error("Thumbnail creation error:", error.message);
    // Return original buffer if thumbnail creation fails
    return imgBuf;
  }
}

// text wrapping helper that attempts to match Python's draw_wrapped_label_value.
// We measure text widths using doc.widthOfString and output lines manually at exact coordinates.
function drawWrappedLabelValue(doc, x, y, label, text, maxWidthCm = 16.0) {
  const maxW = maxWidthCm * CM;
  const fontSize = 10;
  doc.font("Helvetica").fontSize(fontSize);
  const labelStr = `${label}: `;
  const labelW = doc.widthOfString(labelStr);
  const words = (text || "N/A").toString().split(/\s+/);
  let first = true;
  let line = "";
  let width = 0;
  let lines = [];

  for (let w of words) {
    const w_w = doc.widthOfString(w + " ");
    if (first) {
      if (labelW + width + w_w < maxW) {
        line += w + " ";
        width += w_w;
      } else {
        lines.push(labelStr + line.trim());
        first = false;
        line = w + " ";
        width = w_w;
      }
    } else {
      if (width + w_w < maxW) {
        line += w + " ";
        width += w_w;
      } else {
        // indent roughly by label_w/6 characters -> compute pixels
        const indentText = " ".repeat(Math.max(0, Math.floor(labelW / (fontSize * 0.6))));
        lines.push(indentText + line.trim());
        line = w + " ";
        width = w_w;
      }
    }
  }
  if (first) {
    lines.push(labelStr + (line.trim()));
  } else {
    if (line) {
      const indentText = " ".repeat(Math.max(0, Math.floor(labelW / (fontSize * 0.6))));
      lines.push(indentText + line.trim());
    }
  }

  for (let ln of lines) {
    doc.text(ln, x, y, { lineBreak: false });
    y += 0.45 * CM;
  }
  return y;
}

// Draw header/footer helpers (matching positions & fonts from python)
function drawHeader(doc, title) {
  // header blue rectangle at top: height 2.4 cm
  doc.save();
  doc.rect(0, 0, A4_WIDTH, 2.4 * CM).fill("#0F61A8");
  // logo
  let titleX = MARGIN;
  if (fs.existsSync(LOGO_PATH)) {
    try {
      doc.image(LOGO_PATH, MARGIN, 0.2 * CM, { width: 2.4 * CM, height: 2.0 * CM });
      titleX = MARGIN + 2.6 * CM;
    } catch (e) {
      console.warn(`Could not load logo from ${LOGO_PATH}:`, e.message);
    }
  }
  doc.fillColor("white").font("Helvetica-Bold").fontSize(15).text(title, titleX, 0.9 * CM, { continued: false });
  doc.font("Helvetica").fontSize(10);
  const exp = `Exported on ${exportedOnStr()}`;
  // draw right-aligned
  const w = doc.widthOfString(exp);
  doc.fillColor("white").text(exp, A4_WIDTH - MARGIN - w, 1.0 * CM);
  doc.fillColor("black");
  doc.restore();
}

function drawFooter(doc, page) {
  doc.font("Helvetica").fontSize(9).text(`Page ${page}`, A4_WIDTH - MARGIN - 50, A4_HEIGHT - 1.0 * CM);
}

// Build PDF function (mirrors build_pdf in Python)
async function buildPdf(caseObj, files, outPath) {
  return new Promise(async (resolve, reject) => {
    try {
      console.log(`Building PDF for case ${caseObj.case_id} with ${files.length} files...`);
      
      const doc = new PDFDocument({ size: "A4", margin: 0 });
      const ws = fs.createWriteStream(outPath);
      doc.pipe(ws);

      let page = 1;
      // prepare address and geocode
      const ad = ((caseObj.demographic_details || {}).address_details) || {};
      const caseAddr = `${ad.residential_address || ""}, ${ad.city || ""}, ${ad.state || ""} ${ad.pincode || ""}`.trim();
      console.log(`Case address: ${caseAddr}`);
      
      const [caseLat, caseLng] = await forwardGeocode(caseAddr);
      if (caseLat && caseLng) {
        console.log(`Case coordinates: ${caseLat}, ${caseLng}`);
      }

      const title = `Name : ${caseObj.case_applicant_name || ""}`;
      drawHeader(doc, title);
      let y = 3.4 * CM;

      // Customer Details section
      const customerstate = statelist.find(state => state.id === caseObj.residenceDetail.stateId);
      const customerdistrict = districtlist.find(district => district.id === caseObj.residenceDetail.districtId);
      const customercity = citylist.find(city => city.id === caseObj.residenceDetail.cityId);
      const customeraddress=caseObj.residenceDetail.address1 +", "+ caseObj.residenceDetail.address2 +", "+ caseObj.residenceDetail.address3 +", "+customercity.city_name +", "+ customerdistrict.district_name +", "+ customerstate.state_name +", "+ caseObj.residenceDetail.pincode;
      y = sectionTitle(doc, "Customer Details", MARGIN, y);
      labelValue(doc, MARGIN, y, "Customer Name", caseObj.case_applicant_name); y += 0.6 * CM;
      labelValue(doc, MARGIN, y, "Customer ID", caseObj.case_id); y += 0.6 * CM;
      labelValue(doc, MARGIN, y, "Phone Number", caseObj.case_applicant_contact); y += 0.6 * CM;
      //const emailId = (caseObj.applicantDetail.email || {}).contact_information && (caseObj.demographic_details.contact_information.email_id);
      labelValue(doc, MARGIN, y, "Email", caseObj.applicantDetail.email); y += 0.6 * CM;
      y = drawWrappedLabelValue(doc, MARGIN, y, "Customer Address", customeraddress, 18.0); y += 0.6 * CM;

      // Inspection Summary
      y = sectionTitle(doc, "Inspection Summary", MARGIN, y);
      doc.font("Helvetica").fontSize(10);
      doc.text(`Request Started: ${fmtIST(caseObj.created_at)}`, MARGIN, y); y += 0.5 * CM;
      doc.text(`Total Uploads: ${files.length} uploads`, MARGIN, y); y += 0.5 * CM;
      doc.text(`Status: ${caseObj.status}`, MARGIN, y); y += 0.5 * CM;
      doc.text(`Priority: ${caseObj.priority}`, MARGIN, y); y += 0.7 * CM;

      // render static map if caseLat present (attempt)
      if (caseLat) {
        console.log("Generating overview map...");
        const mapBuf = await staticMapWithPath(caseLat, caseLng, caseLat, caseLng, 12);
        if (mapBuf) {
          // approximate map size used in python: map_h = H/2 + 2*cm
          const mapH = A4_HEIGHT / 2 + 2 * CM;
          const mapW = A4_WIDTH - 2 * MARGIN;
          doc.image(mapBuf, MARGIN, y, { width: mapW, height: mapH });
          y += mapH + 0.8 * CM;
        }
      }

      drawFooter(doc, page);
      doc.addPage(); page += 1;

      // Page 2: thumbnails
      drawHeader(doc, title);
      y = 3.4 * CM;
      doc.font("Helvetica-Bold").fontSize(14).text("Image Thumbnails", MARGIN, y);
      y += 0.8 * CM;

      const x0 = MARGIN;
      const y0 = y;
      const colW = (A4_WIDTH - 2 * MARGIN) / 3;
      const rowH = 6.1 * CM;

      for (let i = 0; i < Math.min(6, files.length); ++i) {
        const f = files[i];
        console.log(`Creating thumbnail for upload ${i+1} (${f.file_type})...`);
        const imgBuf = await makeThumb(f._bin);
        const col = i % 3;
        const row = Math.floor(i / 3);
        const xi = x0 + col * colW + 0.2 * CM;
        const yi = y0 + row * rowH + 4.6 * CM;
        // draw image within width colW-0.6cm and height 4 cm
        try {
          doc.image(imgBuf, xi, yi, { width: colW - 0.6 * CM, height: 4.0 * CM, align: "center", valign: "center" });
        } catch (e) { 
          console.warn(`Could not draw thumbnail ${i+1}:`, e.message);
        }
        doc.font("Helvetica").fontSize(9).text(`Upload ${i + 1}${displayType(f.file_type)}`, xi, yi - 0.3 * CM);
      }

      drawFooter(doc, page);
      doc.addPage(); page += 1;

      // Page 3: Demographic, Business, Financial
      drawHeader(doc, title);
      y = 3.4 * CM;
      y = sectionTitle(doc, "Demographic Details", MARGIN, y);
      const demo = caseObj.applicantDetail || {};
      const ci = demo.contact_information || {};
      const pd = demo.personal_details || {};
      const gender = genderlist.find(gender => gender.id === demo.genderId);
      const qualification = qualificationlist.find(qualification => qualification.id === demo.qualification);
      labelValue(doc, MARGIN, y, "Aadhaar Photo Match", demo.aadhaar_photo_match); y += 0.5 * CM;
      labelValue(doc, MARGIN, y, "Email ID", demo.email); y += 0.5 * CM;
      labelValue(doc, MARGIN, y, "Mobile Number", demo.mobile); y += 0.5 * CM;
      labelValue(doc, MARGIN, y, "Gender", gender.gender_name); y += 0.5 * CM;
      labelValue(doc, MARGIN, y, "Education", qualification.qualification_name); y += 0.5 * CM;
      labelValue(doc, MARGIN, y, "Family Members", demo.numOfDependent); y += 1.0 * CM;

      y = sectionTitle(doc, "Business Details", MARGIN, y);
      const bd = caseObj.businessDetail || {};
      const ei = bd.enterprise_information || {};
      const bld = bd.business_location_details || {};
      const ba = bd.business_address || {};
      const state = statelist.find(state => state.id === bd.stateId);
      const district = districtlist.find(district => district.id === bd.districtId);
      const city = citylist.find(city => city.id === bd.cityId);
      const organization = organizationlist.find(organization => organization.id === bd.organizationType);
      //const city = citylist.find(city => city.id === bd.cityId);
      labelValue(doc, MARGIN, y, "Enterprise Name", bd.businessName); y += 0.5 * CM;
      labelValue(doc, MARGIN, y, "Organization Type", organization.organization_name); y += 0.5 * CM;
      labelValue(doc, MARGIN, y, "Business Location Type", bd.businessLocation); y += 0.5 * CM;
      labelValue(doc, MARGIN, y, "Address", `${bd.address1} ${bd.address2} ${bd.landmark }`); y += 0.5 * CM;
      labelValue(doc, MARGIN, y, "City/District/State/Pincode", `${city.city_name || ""}/ ${district.district_name || ""}/ ${state.state_name || ""} - ${bd.pincode || ""}`); y += 1.0 * CM;

      y = sectionTitle(doc, "Financial Details", MARGIN, y);
      const fin = caseObj.financial_details || {};
      const bfi = fin.business_financial_information || {};
      const ffi = fin.family_financial_information || {};
      function fmtInr(v) {
        try {
          if (v == null || v === "" || isNaN(v)) return "N/A";
          const amount = parseInt(v);
          // Format with Indian numbering system and ₹ symbol
          return `₹ ${amount.toLocaleString('en-IN')}`;
        } catch {
          return "N/A";
        }
      }
      labelValue(doc, MARGIN, y, "Monthly Income", fmtInr(caseObj.incomeExpenditure.monthlyIncome)); y += 0.5 * CM;
      labelValue(doc, MARGIN, y, "Monthly Expense", fmtInr(caseObj.familyExpenses.totalExp)); y += 0.5 * CM;
      labelValue(doc, MARGIN, y, "Family Income", fmtInr(caseObj.incomeExpenditure.totalIncome)); y += 0.5 * CM;

      drawFooter(doc, page);
      doc.addPage(); page += 1;

      // For each file, a detailed page
      for (let idx = 0; idx < files.length; ++idx) {
        const f = files[idx];
        console.log(`Processing detailed page for upload ${idx+1}...`);
        
        drawHeader(doc, title);
        y = 3.4 * CM;
        doc.font("Helvetica-Bold").fontSize(14).text(`Upload ${idx + 1}${displayType(f.file_type)}`, MARGIN, y);
        y += 0.8 * CM;

        // integrity_dashboard image insertion (if present)
        try {
          const integrityPath = "integrity_dashboard.png";
          if (fs.existsSync(integrityPath)) {
            const imageWidth = 16 * CM;
            const imageHeight = 2.5 * CM;
            const centerX = (A4_WIDTH - imageWidth) / 2;
            doc.image(integrityPath, centerX, y, { width: imageWidth, height: imageHeight });
            y = y + imageHeight + 0.8 * CM;
          } else {
            y += 0.5 * CM;
          }
        } catch (e) {
          y += 0.5 * CM;
        }

        const gl = f.geo_location || {};
        const lat = gl.lat;
        const lng = gl.lng;

        // draw the file image on left
        console.log(`Creating thumbnail for detailed view ${idx+1}...`);
        const imgBuf = await makeThumb(f._bin);
        try {
          doc.image(imgBuf, MARGIN, y, { width: 8.6 * CM, height: 9.0 * CM });
        } catch (e) {
          console.warn(`Could not draw main image ${idx+1}:`, e.message);
        }

        // draw static map for the single upload using Geoapify
        if (lat != null && lng != null) {
          console.log(`Generating static map for upload ${idx+1}...`);
          const mimgBuf = await staticMapWithPath(lat, lng, caseLat, caseLng, 17);
          if (mimgBuf) {
            try {
              doc.image(mimgBuf, 11.0 * CM, y, { width: 8.0 * CM, height: 9.0 * CM });
            } catch (e) {
              console.warn(`Could not draw static map ${idx+1}:`, e.message);
            }
          }
        }

        let yb = y + 10.4 * CM;
        // Use Google Maps for reverse geocoding
        const rev = await reverseGeocode(lat, lng);
        yb = drawWrappedLabelValue(doc, MARGIN, yb, "Location Address", rev, 18.0);

        const distKm = (caseLat != null && lat != null) ? haversineKm(caseLat, caseLng, lat, lng) : null;
        const distM = distKm ? Math.round(distKm * 1000) : null;
        doc.font("Helvetica").fontSize(10);
        doc.text(distM ? `Distance from case location: ${distM} meters` : "Distance from case location: N/A", MARGIN, yb);
        yb += 0.7 * CM;

        const upAt = fmtIST(f.uploaded_at);
        doc.text(`Uploaded At: ${upAt}`, MARGIN, yb); yb += 1.0 * CM;

        doc.font("Helvetica-Bold").fontSize(12).text("Metadata & Sensor Information", MARGIN, yb); yb += 0.6 * CM;
        doc.font("Helvetica").fontSize(10).text(`Server Time: ${upAt}`, MARGIN, yb); yb += 0.6 * CM;
        doc.text(`Device Time: ${upAt}`, MARGIN, yb); yb += 0.6 * CM;
        doc.text(distM ? `Accuracy: ${distM} meters` : "Distance from case location: N/A", MARGIN, yb); yb += 0.6 * CM;
        if (lat != null) {
          doc.text(`Geo: Lat ${lat.toFixed(6)}, Lng ${lng.toFixed(6)}`, MARGIN, yb);
        } else {
          doc.text("Geo: N/A", MARGIN, yb);
        }
        yb += 0.6 * CM;

        drawFooter(doc, page);
        doc.addPage(); page += 1;
      }

      // Timeline page (mirrors python)
      console.log("Creating timeline page...");
      drawHeader(doc, title);
      y = 3.4 * CM;
      doc.font("Helvetica-Bold").fontSize(14).text("Inspection Timeline", MARGIN, y); y += 0.8 * CM;

      // draw a rounded rect with a pale bg similar to python's setFillColorRGB
      doc.save();
      doc.roundedRect(MARGIN, y, A4_WIDTH - 2 * MARGIN, 1.1 * CM, 0.3 * CM).fillOpacity(1).fill("#E0F7E6");
      doc.fillColor("#1F743F").font("Helvetica-Bold").fontSize(12).text("Ready for Review", MARGIN + 0.6 * CM, y + 0.4 * CM);
      doc.fillColor("black");
      doc.restore();
      y += 2.0 * CM;

      const events = [];
      function evt(text, ts, sub = null) {
        if (ts) events.push({ text, ts, sub });
      }
      evt("Case Created", caseObj.created_at);
      evt("Assigned to Agent", caseObj.assigned_at);
      evt("Accepted by Agent", caseObj.accepted_at);
      for (let f of files) {
        const sub = await reverseGeocode((f.geo_location || {}).lat, (f.geo_location || {}).lng);
        evt(`Upload — ${displayType(f.file_type)}`, f.uploaded_at, sub);
      }
      evt("Case Updated", caseObj.updated_at);
      evt("Case Completed", caseObj.completed_at);

      function parseTs(s) {
        try {
          return new Date(s);
        } catch {
          return new Date(0);
        }
      }
      events.sort((a, b) => parseTs(a.ts) - parseTs(b.ts));

      for (let ev of events) {
        doc.font("Helvetica").fontSize(10).text(`• ${fmtIST(ev.ts)}`, MARGIN, y); y += 0.45 * CM;
        doc.font("Helvetica-Bold").fontSize(11).text(ev.text, MARGIN + 0.6 * CM, y); y += 0.45 * CM;
        if (ev.sub) {
          doc.font("Helvetica").fontSize(9).fillColor("gray");
          y = drawWrappedLabelValue(doc, MARGIN + 0.6 * CM, y, "Uploaded from", ev.sub, 17.0);
          doc.fillColor("black");
          y += 0.3 * CM;
        }
        y += 0.3 * CM;
        if (y > A4_HEIGHT - 3 * CM) {
          drawFooter(doc, page);
          doc.addPage(); page += 1;
          drawHeader(doc, title);
          y = 3.4 * CM;
          doc.font("Helvetica-Bold").fontSize(14).text("Inspection Timeline (Cont.)", MARGIN, y); y += 1.0 * CM;
        }
      }

      drawFooter(doc, page);
      doc.addPage(); // finalize
      doc.end();
      
      ws.on("finish", () => {
        console.log(`PDF created successfully at ${outPath}`);
        resolve();
      });
      ws.on("error", (e) => {
        console.error("PDF write stream error:", e);
        reject(e);
      });
    } catch (e) {
      console.error("PDF build error:", e);
      reject(e);
    }
  });
}

// small helpers to draw section title and label:value
function sectionTitle(doc, text, x, y) {
  doc.font("Helvetica-Bold").fontSize(14).text(text, x, y);
  return y + 0.9 * CM;
}

function labelValue(doc, x, y, label, value) {
  doc.font("Helvetica-Bold").fontSize(10).text(`${label}:`, x, y);
  doc.font("Helvetica").fontSize(10).text((value == null || value === "" || (Array.isArray(value) && value.length === 0)) ? "N/A" : value.toString(), x + 4.8 * CM, y);
}

// FastAPI-equivalent endpoints
app.get("/health", (req, res) => {
  console.log("Health check");
  res.json({ 
    status: "healthy",
    env_loaded: !!ADMIN_EMAIL && !!ADMIN_PASSWORD && !!AES_KEY_STR && !!AES_IV_STR
  });
});

app.post("/generate-report", async (req, res) => {
  console.log("Generate report request received");
  
  try {
    const caseId = (req.body || {}).case_id;
    if (!caseId) {
      console.error("Missing case_id in request");
      return res.status(400).json({ error: "case_id required" });
    }

    console.log(`Generating report for case: ${caseId}`);
    
    await adminLogin();
    const caseObj = await getCase(caseId);
    const files = await getFiles(caseId);
    console.log(caseObj)
    console.log(`Downloading ${files.length} files...`);
    // download binaries
    for (let i = 0; i < files.length; i++) {
      console.log(`Downloading file ${i+1}/${files.length}...`);
      files[i]._bin = await downloadFile(files[i].file_id);
    }

    // ensure output dir
    const outDir = "/app/output";
    if (!fs.existsSync(outDir)) {
      console.log(`Creating output directory: ${outDir}`);
      fs.mkdirSync(outDir, { recursive: true });
    }
    
    const outputFilename = `Report_${caseId}.pdf`;
    const outputPath = path.join(outDir, outputFilename);
    console.log(`Building PDF at: ${outputPath}`);

    await buildPdf(caseObj, files, outputPath);

    const pdfContent = fs.readFileSync(outputPath);
    // cleanup
    try { 
      fs.unlinkSync(outputPath); 
      console.log(`Cleaned up temporary file: ${outputPath}`);
    } catch { }

    console.log(`Sending PDF response: ${outputFilename} (${pdfContent.length} bytes)`);
    
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader("Content-Disposition", `attachment; filename="${outputFilename}"`);
    res.send(pdfContent);
    
    console.log("PDF sent successfully");
  } catch (e) {
    console.error("Error generating PDF:", e);
    res.status(500).json({ 
      error: `Error generating PDF: ${e.message || String(e)}`,
      stack: process.env.NODE_ENV === 'development' ? e.stack : undefined
    });
  }
});

app.get("/", (req, res) => {
  console.log("Root endpoint accessed");
  res.json({ 
    message: "Case Report Generator API", 
    status: "running",
    endpoints: {
      health: "GET /health",
      generate: "POST /generate-report"
    }
  });
});

const PORT = process.env.PORT || 7860;
app.listen(PORT, "0.0.0.0", () => {
  console.log(`Server listening on port ${PORT}`);
  console.log(`Environment check:`);
});


// // server.js
// import fs from "fs";
// import path from "path";
// import crypto from "crypto";
// import fetch from "node-fetch";
// import express from "express";
// import bodyParser from "body-parser";
// import PDFDocument from "pdfkit";
// import sharp from "sharp";
// import moment from "moment-timezone";
// import cors from "cors";

// // Configuration (all from environment variables)
// const BASE_URL = process.env.BASE_URL || "https://rakshitjan-cps-b2c.hf.space";
// const ADMIN_EMAIL = process.env.ADMIN_EMAIL || "admin123@example.com";
// const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || "SecurePass123";
// const AES_KEY_STR = process.env.AES_KEY_STR || "7E892875A52C59A3B588306B13C31FBD";
// const AES_IV_STR = process.env.AES_IV_STR || "XYE45DKJ0967GFAZ";
// const GOOGLE_MAPS_API_KEY = process.env.GOOGLE_MAPS_API_KEY || "AIzaSyBpna0F0J-c9QNBh8lSnfT2Z2uzD_vS9Ag"; // For geocoding
// const GEOAPIFY_API_KEY = process.env.GEOAPIFY_API_KEY || "ceaea8a8a8f14f46b73221384eb4b5f0" ; // For static maps
// const LOGO_PATH = process.env.LOGO_PATH || "logo.png";

// // PDF compression settings
// const PDF_COMPRESSION_ENABLED = process.env.PDF_COMPRESSION_ENABLED !== "false";
// const IMAGE_COMPRESSION_QUALITY = parseInt(process.env.IMAGE_COMPRESSION_QUALITY) || 65;
// const MAX_IMAGE_DIMENSION = parseInt(process.env.MAX_IMAGE_DIMENSION) || 1200;
// const THUMBNAIL_QUALITY = parseInt(process.env.THUMBNAIL_QUALITY) || 55;

// const app = express();
// app.use(bodyParser.json({ limit: "50mb" }));

// // Allow ALL origins
// app.use(cors());

// // Utility: convert cm to PDF points (1 pt = 1/72 in; 1 cm = 28.3464567 pt)
// const CM = 28.3464567;
// const A4_WIDTH = 595.2755905511812; // points (210mm)
// const A4_HEIGHT = 841.8897637795277; // points (297mm)
// const MARGIN = 1.2 * CM;

// // AES encryption like Python's Crypto.Cipher AES-CBC w/ PKCS7 padding
// function aesEncrypt(plaintext, keyStr, ivStr) {
//   // Validate inputs
//   if (!plaintext) throw new Error("Plaintext is required for encryption");
//   if (!keyStr) throw new Error("AES key is required");
//   if (!ivStr) throw new Error("AES IV is required");
  
//   const key = Buffer.from(keyStr, "utf8");
//   const iv = Buffer.from(ivStr, "utf8");
  
//   // Validate key and IV lengths
//   if (key.length !== 16 && key.length !== 24 && key.length !== 32) {
//     throw new Error(`Invalid AES key length: ${key.length} bytes. Must be 16, 24, or 32 bytes.`);
//   }
  
//   // Node's createCipheriv uses PKCS#7 padding by default (called PKCS#5 in OpenSSL)
//   const cipher = crypto.createCipheriv(`aes-${key.length * 8}-cbc`, key, iv);
//   const encrypted = Buffer.concat([
//     cipher.update(Buffer.from(plaintext, "utf8")), 
//     cipher.final()
//   ]);
//   return encrypted.toString("base64");
// }

// // HTTP session mimic (we reuse fetch)
// let token = null;
// async function adminLogin() {
//   try {
//     // encrypt email same as python
//     const encryptedEmail = aesEncrypt(ADMIN_EMAIL, AES_KEY_STR, AES_IV_STR);
    
//     const payload = {
//       email: encryptedEmail,
//       password: ADMIN_PASSWORD
//     };
    
//     console.log(`Logging in to ${BASE_URL} with admin email...`);
    
//     const res = await fetch(`${BASE_URL}/api/admin/login`, {
//       method: "POST",
//       headers: { "Content-Type": "application/json" },
//       body: JSON.stringify(payload),
//       timeout: 30000
//     });
    
//     const data = await res.json();
    
//     if (res.status !== 200 || !data.token) {
//       console.error(`Login failed. Status: ${res.status}, Response:`, data);
//       throw new Error(`Login failed: ${JSON.stringify(data)}`);
//     }
    
//     token = data.token;
//     console.log("Admin login successful");
//     return token;
//   } catch (error) {
//     console.error("Admin login error:", error.message);
//     throw error;
//   }
// }

// async function getCase(caseId) {
//   if (!token) await adminLogin();
  
//   console.log(`Fetching case ${caseId}...`);
//   const res = await fetch(`${BASE_URL}/api/cases/${caseId}`, {
//     headers: { 
//       "Content-Type": "application/json", 
//       "Authorization": `Bearer ${token}` 
//     },
//     timeout: 30000
//   });
  
//   if (!res.ok) {
//     console.error(`Failed to get case ${caseId}: ${res.status} ${res.statusText}`);
//     throw new Error(`Failed get_case: ${res.status}`);
//   }
  
//   return await res.json();
// }

// async function getFiles(caseId) {
//   if (!token) await adminLogin();
  
//   console.log(`Fetching files for case ${caseId}...`);
//   const res = await fetch(`${BASE_URL}/api/cases/${caseId}/files`, {
//     headers: { 
//       "Content-Type": "application/json", 
//       "Authorization": `Bearer ${token}` 
//     },
//     timeout: 60000
//   });
  
//   if (!res.ok) {
//     console.error(`Failed to get files for case ${caseId}: ${res.status} ${res.statusText}`);
//     throw new Error(`Failed get_files: ${res.status}`);
//   }
  
//   const json = await res.json();
//   console.log(`Retrieved ${json.files?.length || 0} files for case ${caseId}`);
//   return json.files || [];
// }

// async function downloadFile(fileId) {
//   if (!token) await adminLogin();
  
//   console.log(`Downloading file ${fileId}...`);
//   const res = await fetch(`${BASE_URL}/api/files/${fileId}`, {
//     headers: { "Authorization": `Bearer ${token}` },
//     timeout: 60000
//   });
  
//   if (!res.ok) {
//     console.error(`File download failed for ${fileId}: ${res.status} ${res.statusText}`);
//     throw new Error(`File download failed for ${fileId}: ${res.status}`);
//   }
  
//   const buf = await res.arrayBuffer();
//   return Buffer.from(buf);
// }

// // Google Maps Geocoding API helpers (for forward/reverse geocoding)
// async function forwardGeocode(address) {
//   if (!address) {
//     console.log("No address provided for geocoding");
//     return [null, null];
//   }
  
//   if (!GOOGLE_MAPS_API_KEY) {
//     console.error("GOOGLE_MAPS_API_KEY is not set");
//     return [null, null];
//   }
  
//   console.log(`Geocoding address: ${address.substring(0, 50)}...`);
  
//   try {
//     const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}&key=${GOOGLE_MAPS_API_KEY}`;
//     const res = await fetch(url, { timeout: 20000 });
    
//     if (!res.ok) {
//       console.error(`Geocoding API error: ${res.status} ${res.statusText}`);
//       return [null, null];
//     }
    
//     const json = await res.json();
    
//     if (json.status === "OK" && json.results && json.results[0] && json.results[0].geometry && json.results[0].geometry.location) {
//       const loc = json.results[0].geometry.location;
//       console.log(`Geocoding successful: ${loc.lat}, ${loc.lng}`);
//       return [loc.lat, loc.lng];
//     } else {
//       console.warn(`Geocoding failed: ${json.status} - ${json.error_message || 'No results'}`);
//       return [null, null];
//     }
//   } catch (error) {
//     console.error("Geocoding error:", error.message);
//     return [null, null];
//   }
// }

// async function reverseGeocode(lat, lon) {
//   if (lat == null || lon == null) {
//     console.log("No coordinates provided for reverse geocoding");
//     return "Unknown Address";
//   }
  
//   if (!GOOGLE_MAPS_API_KEY) {
//     console.error("GOOGLE_MAPS_API_KEY is not set");
//     return "Unknown Address";
//   }
  
//   console.log(`Reverse geocoding coordinates: ${lat}, ${lon}`);
  
//   try {
//     const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lon}&key=${GOOGLE_MAPS_API_KEY}`;
//     const res = await fetch(url, { timeout: 20000 });
    
//     if (!res.ok) {
//       console.error(`Reverse geocoding API error: ${res.status} ${res.statusText}`);
//       return "Unknown Address";
//     }
    
//     const json = await res.json();
    
//     if (json.status === "OK" && json.results && json.results[0] && json.results[0].formatted_address) {
//       const address = json.results[0].formatted_address;
//       console.log(`Reverse geocoding successful: ${address.substring(0, 50)}...`);
//       return address;
//     } else {
//       console.warn(`Reverse geocoding failed: ${json.status} - ${json.error_message || 'No results'}`);
//       return "Unknown Address";
//     }
//   } catch (error) {
//     console.error("Reverse geocoding error:", error.message);
//     return "Unknown Address";
//   }
// }

// // Geoapify Static Maps API (for static maps with markers and path)
// async function staticMapWithPath(captureLat, captureLng, caseLat = null, caseLng = null, zoom = 17, size = "1800x600") {
//   if (captureLat == null || captureLng == null) {
//     console.log("No capture coordinates provided for static map");
//     return null;
//   }
  
//   if (!GEOAPIFY_API_KEY) {
//     console.error("GEOAPIFY_API_KEY is not set");
//     return null;
//   }
  
//   console.log(`Generating static map for: ${captureLat}, ${captureLng}`);
  
//   try {
//     let parts = [
//       `center=lonlat:${captureLng},${captureLat}`,
//       `zoom=${zoom}`,
//       `size=${size}`,
//       `scaleFactor=2`,
//       `marker=lonlat:${captureLng},${captureLat};color:%23ff0000;size:large`
//     ];
    
//     if (caseLat != null && caseLng != null) {
//       parts.push(`marker=lonlat:${caseLng},${caseLat};color:%23007bff;size:large`);
//       parts.push(`path=color:%23ff0000;weight:4|lonlat:${caseLng},${caseLat}|lonlat:${captureLng},${captureLat}`);
//     }
    
//     const url = `https://maps.geoapify.com/v1/staticmap?${parts.join("&")}&apiKey=${GEOAPIFY_API_KEY}`;
//     const res = await fetch(url, { timeout: 30000 });
    
//     if (!res.ok) {
//       console.error(`Static map API error: ${res.status} ${res.statusText}`);
//       return null;
//     }
    
//     const buf = Buffer.from(await res.arrayBuffer());
//     console.log("Static map generated successfully");
//     return buf;
//   } catch (error) {
//     console.error("Static map generation error:", error.message);
//     return null;
//   }
// }

// function haversineKm(lat1, lon1, lat2, lon2) {
//   if ([lat1, lon1, lat2, lon2].some(v => v == null)) return null;
//   const R = 6371.0;
//   const phi1 = lat1 * Math.PI / 180;
//   const phi2 = lat2 * Math.PI / 180;
//   const dphi = (lat2 - lat1) * Math.PI / 180;
//   const dlambda = (lon2 - lon1) * Math.PI / 180;
//   const a = Math.sin(dphi / 2) * Math.sin(dphi / 2) + Math.cos(phi1) * Math.cos(phi2) * Math.sin(dlambda / 2) * Math.sin(dlambda / 2);
//   return 2 * R * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
// }

// // date formatting to IST similar to fmt_ist in python
// function fmtIST(dtStr) {
//   if (!dtStr) return "N/A";
//   try {
//     // Accept Z or offset
//     const m = moment(dtStr);
//     const ist = m.tz("Asia/Kolkata").format("DD/MM/YYYY hh:mm:ss A") + " IST";
//     return ist;
//   } catch {
//     return dtStr;
//   }
// }

// function exportedOnStr() {
//   return moment().tz("Asia/Kolkata").format("MMMM DD, YYYY");
// }

// // Mapping display names
// const DISPLAY_NAME = {
//   "aadhaar_photo": "Photo of Aadhar",
//   "customer_photo": "Customer's Photo",
//   "residence_photo": "Residence Photo",
//   "business_photo": "Business Address Photo"
// };
// function displayType(fileType) {
//   return DISPLAY_NAME[fileType] || fileType || "Upload";
// }

// // Optimized image compression - resize and compress aggressively
// async function compressImageBuffer(imageBuffer, quality = IMAGE_COMPRESSION_QUALITY, maxDimension = MAX_IMAGE_DIMENSION) {
//   try {
//     // Get image info
//     const image = sharp(imageBuffer);
//     const metadata = await image.metadata();
    
//     // Check if image is already small
//     if (imageBuffer.length < 100 * 1024) { // Less than 100KB
//       console.log(`Image already small (${Math.round(imageBuffer.length / 1024)}KB), skipping compression`);
//       return imageBuffer;
//     }
    
//     console.log(`Compressing image: ${Math.round(imageBuffer.length / 1024)}KB, ${metadata.width}x${metadata.height}`);
    
//     // Calculate new dimensions if needed
//     let newWidth = metadata.width;
//     let newHeight = metadata.height;
    
//     if (metadata.width > maxDimension || metadata.height > maxDimension) {
//       if (metadata.width > metadata.height) {
//         newWidth = maxDimension;
//         newHeight = Math.round((metadata.height / metadata.width) * maxDimension);
//       } else {
//         newHeight = maxDimension;
//         newWidth = Math.round((metadata.width / metadata.height) * maxDimension);
//       }
//       console.log(`Resizing image from ${metadata.width}x${metadata.height} to ${newWidth}x${newHeight}`);
//     }
    
//     // Use WebP for best compression (much better than JPEG for same quality)
//     const compressedBuffer = await sharp(imageBuffer)
//       .resize(newWidth, newHeight, {
//         fit: 'inside',
//         withoutEnlargement: true
//       })
//       .webp({ 
//         quality: Math.max(quality, 50), // Minimum 50% quality
//         effort: 6,  // Maximum compression effort (slowest but best)
//         lossless: false
//       })
//       .toBuffer()
//       .catch(async (webpError) => {
//         console.log(`WebP failed, using JPEG: ${webpError.message}`);
//         // Fallback to JPEG with mozjpeg for better compression
//         return await sharp(imageBuffer)
//           .resize(newWidth, newHeight, {
//             fit: 'inside',
//             withoutEnlargement: true
//           })
//           .flatten({ background: { r: 255, g: 255, b: 255 } }) // Remove transparency
//           .jpeg({ 
//             quality: Math.max(quality - 10, 40), // JPEG needs lower quality for similar size
//             mozjpeg: true,  // Better compression
//             chromaSubsampling: '4:4:4' // Better quality
//           })
//           .toBuffer();
//       });
    
//     const originalSize = imageBuffer.length;
//     const compressedSize = compressedBuffer.length;
//     const compressionRatio = ((originalSize - compressedSize) / originalSize * 100).toFixed(1);
    
//     console.log(`Image compressed: ${Math.round(originalSize / 1024)}KB → ${Math.round(compressedSize / 1024)}KB (${compressionRatio}% reduction)`);
    
//     return compressedBuffer;
//   } catch (error) {
//     console.error("Image compression error:", error.message);
//     // Return original buffer if compression fails
//     return imageBuffer;
//   }
// }

// // Optimized thumbnail creation with aggressive compression
// async function makeThumb(imgBuf, maxW = 860, maxH = 640) {
//   try {
//     // First compress and resize the image aggressively for thumbnails
//     const compressedImg = await compressImageBuffer(imgBuf, THUMBNAIL_QUALITY, Math.max(maxW, maxH));
    
//     // Create thumbnail with specific dimensions
//     const img = sharp(compressedImg)
//       .rotate()
//       .resize({ 
//         width: maxW, 
//         height: maxH, 
//         fit: "inside",
//         withoutEnlargement: true,
//         kernel: sharp.kernel.lanczos3 // Better downsampling
//       })
//       .flatten({ background: { r: 255, g: 255, b: 255 } });
    
//     // Use WebP for thumbnails
//     let outputBuffer;
//     try {
//       outputBuffer = await img
//         .webp({ 
//           quality: THUMBNAIL_QUALITY,
//           effort: 6,
//           lossless: false
//         })
//         .toBuffer();
//     } catch {
//       // Fallback to JPEG
//       outputBuffer = await img
//         .jpeg({ 
//           quality: THUMBNAIL_QUALITY - 10,
//           mozjpeg: true
//         })
//         .toBuffer();
//     }
    
//     // Add minimal border
//     const bordered = await sharp(outputBuffer)
//       .extend({ 
//         top: 1, 
//         bottom: 1, 
//         left: 1, 
//         right: 1, 
//         background: { r: 170, g: 170, b: 170 } 
//       });
    
//     let finalBuffer;
//     try {
//       finalBuffer = await bordered
//         .webp({ 
//           quality: THUMBNAIL_QUALITY,
//           effort: 6 
//         })
//         .toBuffer();
//     } catch {
//       finalBuffer = await bordered
//         .jpeg({ 
//           quality: THUMBNAIL_QUALITY - 10,
//           mozjpeg: true 
//         })
//         .toBuffer();
//     }
    
//     return finalBuffer;
//   } catch (error) {
//     console.error("Thumbnail creation error:", error.message);
//     // Return original if thumbnail creation fails
//     return await compressImageBuffer(imgBuf, THUMBNAIL_QUALITY);
//   }
// }

// // Compress static maps aggressively (maps don't need high quality)
// async function compressStaticMap(mapBuffer) {
//   if (!mapBuffer) return mapBuffer;
  
//   try {
//     const originalSize = mapBuffer.length;
    
//     // If already small, return as is
//     if (originalSize < 50 * 1024) {
//       return mapBuffer;
//     }
    
//     console.log(`Compressing static map: ${Math.round(originalSize / 1024)}KB`);
    
//     // Static maps can be heavily compressed
//     const compressedBuffer = await sharp(mapBuffer)
//       .webp({ 
//         quality: 50,  // Low quality for maps
//         effort: 6,
//         lossless: false
//       })
//       .toBuffer()
//       .catch(() => {
//         // Fallback to JPEG
//         return sharp(mapBuffer)
//           .jpeg({ 
//             quality: 55,
//             mozjpeg: true
//           })
//           .toBuffer();
//       });
    
//     const compressedSize = compressedBuffer.length;
//     const compressionRatio = ((originalSize - compressedSize) / originalSize * 100).toFixed(1);
    
//     console.log(`Static map compressed: ${Math.round(originalSize / 1024)}KB → ${Math.round(compressedSize / 1024)}KB (${compressionRatio}% reduction)`);
    
//     return compressedBuffer;
//   } catch (error) {
//     console.error("Static map compression error:", error.message);
//     return mapBuffer;
//   }
// }

// // Simple PDF optimization - we rely on image compression and PDFKit's built-in compression
// async function optimizePDF(inputPath, outputPath) {
//   if (!PDF_COMPRESSION_ENABLED) {
//     fs.copyFileSync(inputPath, outputPath);
//     return outputPath;
//   }
  
//   try {
//     // For Hugging Face, we can't use Ghostscript, so we rely on the compression
//     // we've already done at the image level and PDFKit's built-in compression
//     console.log("Using image-level compression (optimized for Hugging Face)");
    
//     // Just copy the file - compression was already done during creation
//     fs.copyFileSync(inputPath, outputPath);
    
//     return outputPath;
//   } catch (error) {
//     console.error("PDF optimization failed:", error.message);
//     // Fallback to original
//     fs.copyFileSync(inputPath, outputPath);
//     return outputPath;
//   }
// }

// // text wrapping helper that attempts to match Python's draw_wrapped_label_value.
// function drawWrappedLabelValue(doc, x, y, label, text, maxWidthCm = 16.0) {
//   const maxW = maxWidthCm * CM;
//   const fontSize = 10;
//   doc.font("Helvetica").fontSize(fontSize);
//   const labelStr = `${label}: `;
//   const labelW = doc.widthOfString(labelStr);
//   const words = (text || "N/A").toString().split(/\s+/);
//   let first = true;
//   let line = "";
//   let width = 0;
//   let lines = [];

//   for (let w of words) {
//     const w_w = doc.widthOfString(w + " ");
//     if (first) {
//       if (labelW + width + w_w < maxW) {
//         line += w + " ";
//         width += w_w;
//       } else {
//         lines.push(labelStr + line.trim());
//         first = false;
//         line = w + " ";
//         width = w_w;
//       }
//     } else {
//       if (width + w_w < maxW) {
//         line += w + " ";
//         width += w_w;
//       } else {
//         const indentText = " ".repeat(Math.max(0, Math.floor(labelW / (fontSize * 0.6))));
//         lines.push(indentText + line.trim());
//         line = w + " ";
//         width = w_w;
//       }
//     }
//   }
//   if (first) {
//     lines.push(labelStr + (line.trim()));
//   } else {
//     if (line) {
//       const indentText = " ".repeat(Math.max(0, Math.floor(labelW / (fontSize * 0.6))));
//       lines.push(indentText + line.trim());
//     }
//   }

//   for (let ln of lines) {
//     doc.text(ln, x, y, { lineBreak: false });
//     y += 0.45 * CM;
//   }
//   return y;
// }

// // Draw header/footer helpers
// function drawHeader(doc, title) {
//   // header blue rectangle at top: height 2.4 cm
//   doc.save();
//   doc.rect(0, 0, A4_WIDTH, 2.4 * CM).fill("#0F61A8");
//   // logo
//   let titleX = MARGIN;
//   if (fs.existsSync(LOGO_PATH)) {
//     try {
//       const logoBuffer = fs.readFileSync(LOGO_PATH);
//       doc.image(logoBuffer, MARGIN, 0.2 * CM, { width: 2.4 * CM, height: 2.0 * CM });
//       titleX = MARGIN + 2.6 * CM;
//     } catch (e) {
//       console.warn(`Could not load logo from ${LOGO_PATH}:`, e.message);
//     }
//   }
//   doc.fillColor("white").font("Helvetica-Bold").fontSize(15).text(title, titleX, 0.9 * CM, { continued: false });
//   doc.font("Helvetica").fontSize(10);
//   const exp = `Exported on ${exportedOnStr()}`;
//   const w = doc.widthOfString(exp);
//   doc.fillColor("white").text(exp, A4_WIDTH - MARGIN - w, 1.0 * CM);
//   doc.fillColor("black");
//   doc.restore();
// }

// function drawFooter(doc, page) {
//   doc.font("Helvetica").fontSize(9).text(`Page ${page}`, A4_WIDTH - MARGIN - 50, A4_HEIGHT - 1.0 * CM);
// }

// // Optimized Build PDF function
// async function buildPdf(caseObj, files, outPath) {
//   return new Promise(async (resolve, reject) => {
//     try {
//       console.log(`Building optimized PDF for case ${caseObj.case_id} with ${files.length} files...`);
      
//       const doc = new PDFDocument({ 
//         size: "A4", 
//         margin: 0,
//         compress: true,  // Enable PDF compression
//         pdfVersion: '1.5', // Better compression
//         info: {
//           Title: `Report for ${caseObj.case_applicant_name || ''}`,
//           Author: 'Case Report System',
//           Subject: 'Case Inspection Report',
//           Keywords: 'case,report,inspection',
//           Creator: 'PDFKit with Compression',
//           Producer: 'Hugging Face Optimized',
//           CreationDate: new Date()
//         }
//       });
      
//       const ws = fs.createWriteStream(outPath);
//       doc.pipe(ws);

//       let page = 1;
//       const ad = ((caseObj.demographic_details || {}).address_details) || {};
//       const caseAddr = `${ad.residential_address || ""}, ${ad.city || ""}, ${ad.state || ""} ${ad.pincode || ""}`.trim();
//       console.log(`Case address: ${caseAddr}`);
      
//       const [caseLat, caseLng] = await forwardGeocode(caseAddr);
//       if (caseLat && caseLng) {
//         console.log(`Case coordinates: ${caseLat}, ${caseLng}`);
//       }

//       const title = `Name : ${caseObj.case_applicant_name || ""}`;
//       drawHeader(doc, title);
//       let y = 3.4 * CM;

//       // Customer Details section
//       y = sectionTitle(doc, "Customer Details", MARGIN, y);
//       labelValue(doc, MARGIN, y, "Customer Name", caseObj.case_applicant_name); y += 0.6 * CM;
//       labelValue(doc, MARGIN, y, "Customer ID", caseObj.case_id); y += 0.6 * CM;
//       labelValue(doc, MARGIN, y, "Phone Number", caseObj.case_applicant_contact); y += 0.6 * CM;
//       const emailId = (caseObj.demographic_details || {}).contact_information && (caseObj.demographic_details.contact_information.email_id);
//       labelValue(doc, MARGIN, y, "Email", emailId); y += 0.6 * CM;
//       y = drawWrappedLabelValue(doc, MARGIN, y, "Customer Address", caseAddr, 18.0); y += 0.4 * CM;

//       // Inspection Summary
//       y = sectionTitle(doc, "Inspection Summary", MARGIN, y);
//       doc.font("Helvetica").fontSize(10);
//       doc.text(`Request Started: ${fmtIST(caseObj.created_at)}`, MARGIN, y); y += 0.5 * CM;
//       doc.text(`Total Uploads: ${files.length} uploads`, MARGIN, y); y += 0.5 * CM;
//       doc.text(`Status: ${caseObj.status}`, MARGIN, y); y += 0.5 * CM;
//       doc.text(`Priority: ${caseObj.priority}`, MARGIN, y); y += 0.7 * CM;

//       // render static map if caseLat present
//       if (caseLat) {
//         console.log("Generating and compressing overview map...");
//         const mapBuf = await staticMapWithPath(caseLat, caseLng, caseLat, caseLng, 12, "1200x400"); // Smaller size
//         if (mapBuf) {
//           const compressedMapBuf = await compressStaticMap(mapBuf);
//           const mapH = 8 * CM; // Smaller height
//           const mapW = A4_WIDTH - 2 * MARGIN;
//           doc.image(compressedMapBuf, MARGIN, y, { width: mapW, height: mapH });
//           y += mapH + 0.8 * CM;
//         }
//       }

//       drawFooter(doc, page);
//       doc.addPage(); page += 1;

//       // Page 2: thumbnails (limited to 6 for size)
//       drawHeader(doc, title);
//       y = 3.4 * CM;
//       doc.font("Helvetica-Bold").fontSize(14).text("Image Thumbnails", MARGIN, y);
//       y += 0.8 * CM;

//       const x0 = MARGIN;
//       const y0 = y;
//       const colW = (A4_WIDTH - 2 * MARGIN) / 3;
//       const rowH = 5.5 * CM; // Smaller row height

//       // Limit thumbnails to 6 max for file size
//       const maxThumbnails = Math.min(6, files.length);
//       for (let i = 0; i < maxThumbnails; ++i) {
//         const f = files[i];
//         console.log(`Creating optimized thumbnail for upload ${i+1}...`);
//         const imgBuf = await makeThumb(f._bin);
//         const col = i % 3;
//         const row = Math.floor(i / 3);
//         const xi = x0 + col * colW + 0.2 * CM;
//         const yi = y0 + row * rowH + 4.0 * CM; // Adjusted position
        
//         try {
//           doc.image(imgBuf, xi, yi, { width: colW - 0.8 * CM, height: 3.5 * CM }); // Smaller thumbnails
//         } catch (e) { 
//           console.warn(`Could not draw thumbnail ${i+1}:`, e.message);
//         }
//         doc.font("Helvetica").fontSize(8).text(`Upload ${i + 1} — ${displayType(f.file_type)}`, xi, yi - 0.3 * CM);
//       }

//       drawFooter(doc, page);
//       doc.addPage(); page += 1;

//       // Page 3: Demographic, Business, Financial
//       drawHeader(doc, title);
//       y = 3.4 * CM;
//       y = sectionTitle(doc, "Demographic Details", MARGIN, y);
//       const demo = caseObj.demographic_details || {};
//       const ci = demo.contact_information || {};
//       const pd = demo.personal_details || {};
//       labelValue(doc, MARGIN, y, "Aadhaar Photo Match", demo.aadhaar_photo_match); y += 0.5 * CM;
//       labelValue(doc, MARGIN, y, "Email ID", ci.email_id); y += 0.5 * CM;
//       labelValue(doc, MARGIN, y, "Mobile Number", ci.mobile_number); y += 0.5 * CM;
//       labelValue(doc, MARGIN, y, "Gender", pd.gender); y += 0.5 * CM;
//       labelValue(doc, MARGIN, y, "Education", pd.education); y += 0.5 * CM;
//       labelValue(doc, MARGIN, y, "Family Members", pd.number_of_family_members); y += 1.0 * CM;

//       y = sectionTitle(doc, "Business Details", MARGIN, y);
//       const bd = caseObj.business_details || {};
//       const ei = bd.enterprise_information || {};
//       const bld = bd.business_location_details || {};
//       const ba = bd.business_address || {};
//       labelValue(doc, MARGIN, y, "Enterprise Name", ei.enterprise_name); y += 0.5 * CM;
//       labelValue(doc, MARGIN, y, "Organization Type", ei.type_of_organization); y += 0.5 * CM;
//       labelValue(doc, MARGIN, y, "Business Location Type", bld.business_location); y += 0.5 * CM;
//       labelValue(doc, MARGIN, y, "Address", ba.address); y += 0.5 * CM;
//       labelValue(doc, MARGIN, y, "City/District/State/Pincode", `${ba.city || ""}, ${ba.district || ""}, ${ba.state || ""} - ${ba.pincode || ""}`); y += 1.0 * CM;

//       y = sectionTitle(doc, "Financial Details", MARGIN, y);
//       const fin = caseObj.financial_details || {};
//       const bfi = fin.business_financial_information || {};
//       const ffi = fin.family_financial_information || {};
//       function fmtInr(v) {
//         try {
//           if (v == null || v === "" || isNaN(v)) return "N/A";
//           const amount = parseInt(v);
//           return `₹ ${amount.toLocaleString('en-IN')}`;
//         } catch {
//           return "N/A";
//         }
//       }
//       labelValue(doc, MARGIN, y, "Monthly Income", fmtInr(bfi.monthly_income_from_business)); y += 0.5 * CM;
//       labelValue(doc, MARGIN, y, "Monthly Expense", fmtInr(bfi.monthly_expense_of_business)); y += 0.5 * CM;
//       labelValue(doc, MARGIN, y, "Family Income", fmtInr(ffi.monthly_family_income)); y += 0.5 * CM;

//       drawFooter(doc, page);
//       doc.addPage(); page += 1;

//       // For each file, a detailed page (with aggressive image compression)
//       for (let idx = 0; idx < files.length; ++idx) {
//         const f = files[idx];
//         console.log(`Processing detailed page for upload ${idx+1}...`);
        
//         drawHeader(doc, title);
//         y = 3.4 * CM;
//         doc.font("Helvetica-Bold").fontSize(14).text(`Upload ${idx + 1} — ${displayType(f.file_type)}`, MARGIN, y);
//         y += 0.8 * CM;

//         // integrity_dashboard image (skip if not critical)
//         try {
//           const integrityPath = "integrity_dashboard.png";
//           if (fs.existsSync(integrityPath) && fs.statSync(integrityPath).size < 100 * 1024) {
//             const imageWidth = 16 * CM;
//             const imageHeight = 2.5 * CM;
//             const centerX = (A4_WIDTH - imageWidth) / 2;
//             doc.image(integrityPath, centerX, y, { width: imageWidth, height: imageHeight });
//             y = y + imageHeight + 0.8 * CM;
//           } else {
//             y += 0.5 * CM;
//           }
//         } catch (e) {
//           y += 0.5 * CM;
//         }

//         const gl = f.geo_location || {};
//         const lat = gl.lat;
//         const lng = gl.lng;

//         // Main image with aggressive compression
//         console.log(`Creating compressed main image for upload ${idx+1}...`);
//         const imgBuf = await compressImageBuffer(f._bin, IMAGE_COMPRESSION_QUALITY - 10, 1000);
//         try {
//           doc.image(imgBuf, MARGIN, y, { width: 8.0 * CM, height: 8.0 * CM }); // Smaller size
//         } catch (e) {
//           console.warn(`Could not draw main image ${idx+1}:`, e.message);
//         }

//         // Static map (only if coordinates exist)
//         if (lat != null && lng != null) {
//           console.log(`Generating compressed static map for upload ${idx+1}...`);
//           const mimgBuf = await staticMapWithPath(lat, lng, caseLat, caseLng, 17, "800x600"); // Smaller map
//           if (mimgBuf) {
//             const compressedMapBuf = await compressStaticMap(mimgBuf);
//             try {
//               doc.image(compressedMapBuf, 10.5 * CM, y, { width: 7.5 * CM, height: 7.5 * CM }); // Smaller
//             } catch (e) {
//               console.warn(`Could not draw static map ${idx+1}:`, e.message);
//             }
//           }
//         }

//         let yb = y + 9.0 * CM; // Adjusted for smaller images
        
//         // Reverse geocode
//         const rev = await reverseGeocode(lat, lng);
//         yb = drawWrappedLabelValue(doc, MARGIN, yb, "Location Address", rev, 18.0);

//         const distKm = (caseLat != null && lat != null) ? haversineKm(caseLat, caseLng, lat, lng) : null;
//         const distM = distKm ? Math.round(distKm * 1000) : null;
//         doc.font("Helvetica").fontSize(10);
//         doc.text(distM ? `Distance from case location: ${distM} meters` : "Distance from case location: N/A", MARGIN, yb);
//         yb += 0.7 * CM;

//         const upAt = fmtIST(f.uploaded_at);
//         doc.text(`Uploaded At: ${upAt}`, MARGIN, yb); yb += 0.8 * CM;

//         // Condensed metadata section
//         doc.font("Helvetica-Bold").fontSize(11).text("Metadata", MARGIN, yb); yb += 0.5 * CM;
//         doc.font("Helvetica").fontSize(9);
//         doc.text(`Server Time: ${upAt}`, MARGIN, yb); yb += 0.4 * CM;
//         if (lat != null) {
//           doc.text(`Location: ${lat.toFixed(4)}, ${lng.toFixed(4)}`, MARGIN, yb);
//         }
//         yb += 0.4 * CM;

//         drawFooter(doc, page);
        
//         // Only add new page if not the last file
//         if (idx < files.length - 1) {
//           doc.addPage(); 
//           page += 1;
//         }
//       }

//       // Timeline page (optional - can be skipped for very large reports)
//       if (files.length <= 10) { // Only add timeline for reasonable number of files
//         console.log("Creating timeline page...");
//         doc.addPage(); page += 1;
//         drawHeader(doc, title);
//         y = 3.4 * CM;
//         doc.font("Helvetica-Bold").fontSize(14).text("Inspection Timeline", MARGIN, y); y += 0.8 * CM;

//         doc.save();
//         doc.roundedRect(MARGIN, y, A4_WIDTH - 2 * MARGIN, 1.1 * CM, 0.3 * CM).fillOpacity(1).fill("#E0F7E6");
//         doc.fillColor("#1F743F").font("Helvetica-Bold").fontSize(12).text("Ready for Review", MARGIN + 0.6 * CM, y + 0.4 * CM);
//         doc.fillColor("black");
//         doc.restore();
//         y += 2.0 * CM;

//         const events = [];
//         function evt(text, ts, sub = null) {
//           if (ts) events.push({ text, ts, sub });
//         }
//         evt("Case Created", caseObj.created_at);
//         evt("Assigned to Agent", caseObj.assigned_at);
//         evt("Accepted by Agent", caseObj.accepted_at);
//         // Limit timeline events
//         for (let i = 0; i < Math.min(files.length, 5); i++) {
//           const f = files[i];
//           const sub = await reverseGeocode((f.geo_location || {}).lat, (f.geo_location || {}).lng);
//           evt(`Upload — ${displayType(f.file_type)}`, f.uploaded_at, sub);
//         }
//         evt("Case Updated", caseObj.updated_at);
//         evt("Case Completed", caseObj.completed_at);

//         function parseTs(s) {
//           try {
//             return new Date(s);
//           } catch {
//             return new Date(0);
//           }
//         }
//         events.sort((a, b) => parseTs(a.ts) - parseTs(b.ts));

//         for (let ev of events) {
//           doc.font("Helvetica").fontSize(9).text(`• ${fmtIST(ev.ts)}`, MARGIN, y); y += 0.4 * CM;
//           doc.font("Helvetica-Bold").fontSize(10).text(ev.text, MARGIN + 0.6 * CM, y); y += 0.4 * CM;
//           if (ev.sub) {
//             doc.font("Helvetica").fontSize(8).fillColor("gray");
//             const subText = ev.sub.length > 50 ? ev.sub.substring(0, 47) + "..." : ev.sub;
//             doc.text(`  ${subText}`, MARGIN + 0.6 * CM, y);
//             doc.fillColor("black");
//             y += 0.4 * CM;
//           }
//           y += 0.2 * CM;
//           if (y > A4_HEIGHT - 3 * CM) {
//             drawFooter(doc, page);
//             doc.addPage(); page += 1;
//             drawHeader(doc, title);
//             y = 3.4 * CM;
//             doc.font("Helvetica-Bold").fontSize(14).text("Inspection Timeline (Cont.)", MARGIN, y); y += 1.0 * CM;
//           }
//         }
//         drawFooter(doc, page);
//       }

//       doc.end();
      
//       ws.on("finish", () => {
//         console.log(`Optimized PDF created successfully at ${outPath}`);
//         resolve();
//       });
//       ws.on("error", (e) => {
//         console.error("PDF write stream error:", e);
//         reject(e);
//       });
//     } catch (e) {
//       console.error("PDF build error:", e);
//       reject(e);
//     }
//   });
// }

// // Helper functions
// function sectionTitle(doc, text, x, y) {
//   doc.font("Helvetica-Bold").fontSize(14).text(text, x, y);
//   return y + 0.9 * CM;
// }

// function labelValue(doc, x, y, label, value) {
//   doc.font("Helvetica-Bold").fontSize(10).text(`${label}:`, x, y);
//   doc.font("Helvetica").fontSize(10).text((value == null || value === "" || (Array.isArray(value) && value.length === 0)) ? "N/A" : value.toString(), x + 4.8 * CM, y);
// }

// // FastAPI-equivalent endpoints
// app.get("/health", (req, res) => {
//   console.log("Health check");
//   res.json({ 
//     status: "healthy",
//     env_loaded: !!ADMIN_EMAIL && !!ADMIN_PASSWORD && !!AES_KEY_STR && !!AES_IV_STR,
//     pdf_compression: {
//       enabled: PDF_COMPRESSION_ENABLED,
//       image_quality: IMAGE_COMPRESSION_QUALITY,
//       thumbnail_quality: THUMBNAIL_QUALITY,
//       max_image_dimension: MAX_IMAGE_DIMENSION
//     }
//   });
// });

// app.post("/generate-report", async (req, res) => {
//   console.log("Generate report request received");
  
//   try {
//     const caseId = (req.body || {}).case_id;
//     if (!caseId) {
//       console.error("Missing case_id in request");
//       return res.status(400).json({ error: "case_id required" });
//     }

//     console.log(`Generating optimized report for case: ${caseId}`);
    
//     await adminLogin();
//     const caseObj = await getCase(caseId);
//     const files = await getFiles(caseId);
    
//     console.log(`Downloading and compressing ${files.length} files...`);
//     // Download and immediately compress files
//     for (let i = 0; i < files.length; i++) {
//       console.log(`Processing file ${i+1}/${files.length}...`);
//       const originalBuffer = await downloadFile(files[i].file_id);
//       // Store compressed version
//       files[i]._bin = await compressImageBuffer(originalBuffer, IMAGE_COMPRESSION_QUALITY);
//     }

//     // Create output directory
//     const outDir = "/tmp/output";
//     if (!fs.existsSync(outDir)) {
//       console.log(`Creating output directory: ${outDir}`);
//       fs.mkdirSync(outDir, { recursive: true });
//     }
    
//     // Create temporary files
//     const timestamp = Date.now();
//     const originalFilename = `Report_${caseId}_${timestamp}.pdf`;
//     const optimizedFilename = `Report_${caseId}_${timestamp}_optimized.pdf`;
//     const originalPath = path.join(outDir, originalFilename);
//     const optimizedPath = path.join(outDir, optimizedFilename);
    
//     console.log(`Building optimized PDF at: ${originalPath}`);
//     await buildPdf(caseObj, files, originalPath);

//     // Optimize the PDF
//     console.log(`Optimizing PDF...`);
//     await optimizePDF(originalPath, optimizedPath);

//     // Read the optimized PDF
//     const pdfContent = fs.readFileSync(optimizedPath);
    
//     // Get file sizes for logging
//     const originalStats = fs.existsSync(originalPath) ? fs.statSync(originalPath) : { size: 0 };
//     const optimizedStats = fs.statSync(optimizedPath);
//     const compressionRatio = originalStats.size > 0 ? 
//       ((originalStats.size - optimizedStats.size) / originalStats.size * 100).toFixed(1) : "N/A";
    
//     console.log(`PDF optimization results:`);
//     console.log(`  Final size: ${Math.round(optimizedStats.size / 1024)}KB`);
//     if (originalStats.size > 0) {
//       console.log(`  Reduction: ${compressionRatio}% (from ${Math.round(originalStats.size / 1024)}KB)`);
//     }
    
//     // Cleanup
//     [originalPath, optimizedPath].forEach(filePath => {
//       try { 
//         if (fs.existsSync(filePath)) {
//           fs.unlinkSync(filePath); 
//           console.log(`Cleaned up: ${path.basename(filePath)}`);
//         }
//       } catch (e) { 
//         console.warn(`Could not delete ${filePath}:`, e.message);
//       }
//     });

//     const outputFilename = `Report_${caseId}.pdf`;
//     console.log(`Sending optimized PDF: ${outputFilename} (${Math.round(optimizedStats.size / 1024)}KB)`);
    
//     res.setHeader("Content-Type", "application/pdf");
//     res.setHeader("Content-Disposition", `attachment; filename="${outputFilename}"`);
//     res.setHeader("X-PDF-Size", `${Math.round(optimizedStats.size / 1024)}KB`);
//     res.setHeader("X-PDF-Compression", "Hugging Face Optimized");
//     res.send(pdfContent);
    
//     console.log("Optimized PDF sent successfully");
//   } catch (e) {
//     console.error("Error generating PDF:", e);
//     res.status(500).json({ 
//       error: `Error generating PDF: ${e.message || String(e)}`,
//       stack: process.env.NODE_ENV === 'development' ? e.stack : undefined
//     });
//   }
// });

// app.get("/", (req, res) => {
//   console.log("Root endpoint accessed");
//   res.json({ 
//     message: "Case Report Generator API (Hugging Face Optimized)", 
//     status: "running",
//     pdf_compression: {
//       enabled: PDF_COMPRESSION_ENABLED,
//       image_quality: IMAGE_COMPRESSION_QUALITY,
//       thumbnail_quality: THUMBNAIL_QUALITY,
//       max_image_dimension: MAX_IMAGE_DIMENSION,
//       note: "Optimized for Hugging Face Spaces - uses aggressive WebP compression"
//     },
//     endpoints: {
//       health: "GET /health",
//       generate: "POST /generate-report"
//     }
//   });
// });

// const PORT = process.env.PORT || 7860;
// app.listen(PORT, "0.0.0.0", () => {
//   console.log(`Server listening on port ${PORT}`);
//   console.log(`PDF Compression: ${PDF_COMPRESSION_ENABLED ? 'ENABLED' : 'DISABLED'}`);
//   console.log(`Image Quality: ${IMAGE_COMPRESSION_QUALITY}%`);
//   console.log(`Thumbnail Quality: ${THUMBNAIL_QUALITY}%`);
//   console.log(`Max Image Dimension: ${MAX_IMAGE_DIMENSION}px`);
//   console.log(`Optimized for Hugging Face Spaces`);
// });