Spaces:
Sleeping

File size: 71,716 Bytes
34a733e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
577d72f
34a733e
577d72f
 
34a733e
577d72f
 
 
 
 
 
34a733e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
577d72f
34a733e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
577d72f
34a733e
 
 
577d72f
 
 
 
 
34a733e
 
 
 
577d72f
 
 
 
 
 
34a733e
 
 
 
 
577d72f
 
34a733e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""MHS_Variable_Payout.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1I5F6Yxj8GpAhw_AEF-u-SijO3rBOa6yi
"""

"""
HTML to Excel Converter for Hospital Revenue Report (Stable Version)
"""

import pandas as pd
from bs4 import BeautifulSoup
import os

def convert_html_to_excel(input_file, output_file):
    # 1. Read the HTML file with verification
    print(f"\n[1/6] Reading HTML file: {os.path.basename(input_file)}")
    with open(input_file, 'r', encoding='utf-8', errors='ignore') as f:
        html_content = f.read()
    print("βœ“ File read successfully")

    # 2. Parse HTML with lxml for consistency
    print("[2/6] Parsing HTML content...")
    soup = BeautifulSoup(html_content, 'lxml')
    tables = soup.find_all('table')
    print(f"βœ“ Found {len(tables)} tables in document")

    # 3. Identify main table by headers
    print("[3/6] Locating main data table...")
    expected_headers = ['Sr.\xa0No.']  # UPDATE THESE
    main_table = None

    for i, table in enumerate(tables):
        first_row = table.find('tr')
        if first_row:
            headers = [th.get_text(strip=True) for th in first_row.find_all(['th', 'td'])]
            if all(h in headers for h in expected_headers):
                main_table = table
                print(f"βœ“ Identified table {i+1} as main data table")
                print(f"   Table dimensions: {len(table.find_all('tr'))} rows")
                break

    if not main_table:
        raise ValueError("Γ— ERROR: Could not find main data table with expected headers")

    # 4. Extract and validate data rows
    print("[4/6] Processing table rows...")
    rows = main_table.find_all('tr')
    header_row = rows[0]
    headers = [col.get_text(strip=True) for col in header_row.find_all(['th', 'td'])]
    valid_col_count = len(headers)

    print(f"βœ“ Header row identified with {valid_col_count} columns:")
    print(f"   {headers}")
    print(f"βœ“ Processing {len(rows)-1} data rows...")

    # Process data rows with validation
    data = []
    skipped_rows = 0
    for i, row in enumerate(rows[1:]):  # Skip header
        cols = row.find_all(['td', 'th'])
        if len(cols) != valid_col_count:
            skipped_rows += 1
            continue
        data.append([col.get_text(strip=True) for col in cols])

    print(f"βœ“ Clean rows extracted: {len(data)}")
    print(f"   Skipped {skipped_rows} malformed rows")

    # [5/6] Total Row Removal (Guaranteed Last Row + "Total Net Amount" Check)
    print("[5/6] Checking for total row...")

    if data:
        last_row = data[-1]

        # Check if "total net amount" exists in ANY cell of the last row
        if any("total net amount" in cell.lower() for cell in last_row):
            print("βœ“ Removed TOTAL NET AMOUNT row")
            data = data[:-1]

    print(f"βœ“ Final data rows: {len(data)}")

    # 6. Create and save DataFrame
    print("[6/6] Creating Excel file...")
    df = pd.DataFrame(data, columns=headers)

    # Final verification
    print(f"βœ“ DataFrame created with dimensions: {df.shape}")
    print(f"βœ“ First 3 columns: {df.columns.tolist()[:3]}...")
    print(f"βœ“ Last 3 columns: {df.columns.tolist()[-3:]}...")

    df.to_excel(output_file, index=False)
    print(f"\nProcessing complete! Saved to: {output_file}")
    print(f"Final verification:")
    print(f"- Total rows: {len(df):,}")
    print(f"- Total columns: {len(df.columns):,}")

    return output_file

def process_multiple_files(file_list):
    """
    Process multiple HTML files and convert them to Excel.

    Args:
        file_list: List of input HTML filenames to process
    """
    print(f"Starting batch processing of {len(file_list)} files...")

    results = []
    for i, input_file in enumerate(file_list):
        print(f"\n[File {i+1}/{len(file_list)}] Processing: {input_file}")

        # Extract base name for output file
        base_name = os.path.splitext(os.path.basename(input_file))[0]
        output_file = f"processed_{base_name}.xlsx"

        try:
            result = convert_html_to_excel(input_file, output_file)
            results.append((input_file, result, "Success"))
        except Exception as e:
            print(f"Γ— ERROR processing {input_file}: {str(e)}")
            results.append((input_file, None, f"Error: {str(e)}"))

    # Print summary
    print("\n" + "="*50)
    print("BATCH PROCESSING SUMMARY")
    print("="*50)
    for input_file, output_file, status in results:
        print(f"{input_file} β†’ {output_file if output_file else 'FAILED'} ({status})")

    success_count = sum(1 for _, _, status in results if status == "Success")
    print(f"\nProcessed {success_count}/{len(file_list)} files successfully")

    return results

if __name__ == "__main__":
  file_list = [
      '/content/drive/MyDrive/VarAuto/mhs_print_hospital_revenue_report.php (16).xls',
      '/content/drive/MyDrive/VarAuto/maatri_print_hospital_revenue_report.php (16).xls',
      '/content/drive/MyDrive/VarAuto/print_hospital_revenue_report.php (11).xls',
      '/content/drive/MyDrive/VarAuto/doctor_visit_report_without_package.xls',
      '/content/drive/MyDrive/VarAuto/doctor_visit_report_with_package.xls',
      '/content/drive/MyDrive/VarAuto/maatri_doctor_visit_report_with_package.xls',
      '/content/drive/MyDrive/VarAuto/maatri_doctor_visit_report_without_package.xls',
      '/content/drive/MyDrive/VarAuto/print_inpatient_bill_register_report.xls',
      '/content/drive/MyDrive/VarAuto/maatri_print_inpatient_bill_register_report.xls'
  ]

  process_multiple_files(file_list)

# OPD Consultations

import pandas as pd
import re

def normalize_name(name):
    """Clean doctor names for robust matching"""
    # Remove 'Dr' prefixes with any formatting
    name = re.sub(r'^dr[\.\s]*', '', str(name), flags=re.IGNORECASE)
    # Remove all non-alphanumeric characters and spaces
    name = re.sub(r'[^a-zA-Z0-9]', '', name)
    return name.lower().strip()

def filter_patient_records(file_path, search_term):
    # Load Excel data
    df = pd.read_excel(file_path)

    # Preprocess doctor names in dataframe
    df['clean_name'] = df['Dr. Name'].apply(normalize_name)

    # Preprocess search term
    search_clean = normalize_name(search_term)

    # Apply filters
    filtered = df[
        (df['Patient Type'] == 'OPD') &
        (df['Service Type'] == 'Consultation') &
        (df['clean_name'].str.contains(search_clean, regex=False, na=False))
    ]

    return filtered.drop(columns=['clean_name'])

# Example usage
if __name__ == "__main__":
    excel_file = "/content/processed_mhs_print_hospital_revenue_report.php (16).xlsx"
    search = 'Dr. Amit kumar'
    output_file = 'processed_opd_consultations.xlsx'
    results = filter_patient_records(excel_file, search)

    if not results.empty:
        results.to_excel(output_file, index=False)
        print(f"\nFound {len(results)} matches:")
        print(results[['Date', 'Patient Name', 'Dr. Name', 'Dr. Department', 'Service Name', 'Net Amount']])
    else:
        print("\nNo matches found")

# Diag and Path Cases

import pandas as pd
import re

def normalize_name(name):
    """Clean doctor names for robust matching"""
    # Remove 'Dr' prefixes with any formatting
    name = re.sub(r'^dr[\.\s]*', '', str(name), flags=re.IGNORECASE)
    # Remove all non-alphanumeric characters and spaces
    name = re.sub(r'[^a-zA-Z0-9]', '', name)
    return name.lower().strip()

def filter_diag_path_records(file_path, search_term):
    # Load Excel data
    df = pd.read_excel(file_path)

    # Preprocess doctor names in dataframe
    df['clean_name'] = df['Dr. Name'].apply(normalize_name)

    # Preprocess search term
    search_clean = normalize_name(search_term)

    # Apply filters: Patient Type OPD, Service Type Diagnostic OR Pathology, and doctor match
    filtered = df[
        (df['Patient Type'].str.strip().str.upper() == 'OPD')
        &
        df['Service Type']
          .str.contains(r'Diagnostic|Pathology', case=False, na=False)
        &
        df['clean_name'].str.contains(search_clean, regex=False, na=False)
    ]

    return filtered.drop(columns=['clean_name'])

# Example usage
if __name__ == "__main__":
    excel_file = "/content/processed_mhs_print_hospital_revenue_report.php (16).xlsx"
    search = 'Dr. Amit Kumar'
    output_file = 'processed_diag_and_path.xlsx'
    results = filter_diag_path_records(excel_file, search)

    if not results.empty:
        results.to_excel(output_file, index=False)
        print(f"\nFound {len(results)} matches:")
        print(results[['Date', 'Patient Name', 'Dr. Name', 'Dr. Department', 'Service Name', 'Net Amount']])
    else:
        print("\nNo matches found")

# Enhanced Day Care Procedure Cases with Additional Service Types
# Day Care and Other Charges

import pandas as pd
import re

def normalize_name(name):
    """Clean doctor names for robust matching"""
    # Handle missing values
    if pd.isna(name):
        return ""
    # Remove 'Dr' prefixes with any formatting
    name = re.sub(r'^dr[\.\s]*', '', str(name), flags=re.IGNORECASE)
    # Remove all non-alphanumeric characters and spaces
    name = re.sub(r'[^a-zA-Z0-9]', '', name)
    return name.lower().strip()

def normalize_service_type(service_type):
    """Normalize service type for consistent matching"""
    if pd.isna(service_type):
        return ""
    # Convert to lowercase and remove special characters/extra spaces
    service_type = str(service_type).lower().strip()
    service_type = re.sub(r'[^a-z0-9\s]', '', service_type)
    # Consolidate variations
    service_type = re.sub(r'\s+', ' ', service_type)  # Collapse multiple spaces
    return service_type

def filter_daycare_records(file_path, search_term):
    # Load Excel data
    df = pd.read_excel(file_path)

    # Preprocess doctor names in dataframe
    df['clean_name'] = df['Dr. Name'].apply(normalize_name)

    # Preprocess service types
    df['clean_service'] = df['Service Type'].apply(normalize_service_type)

    # Preprocess search term
    search_clean = normalize_name(search_term)

    # Define valid service types after normalization
    valid_services = ['day care procedure', 'other charges']

    # Apply filters
    filtered = df[
        (df['Patient Type'] == 'OPD') &
        (df['clean_service'].isin(valid_services)) &
        (df['clean_name'].str.contains(search_clean, regex=False, na=False))
    ]

    return filtered.drop(columns=['clean_name', 'clean_service'])

# Example usage
if __name__ == "__main__":
    excel_file = "/content/processed_mhs_print_hospital_revenue_report.php (16).xlsx"
    search = 'Dr. Amit Kumar'
    output_file = 'processed_daycare.xlsx'
    results = filter_daycare_records(excel_file, search)

    if not results.empty:
        results.to_excel(output_file, index=False)
        print(f"\nFound {len(results)} matches:")
        print(results[['Date', 'Patient Name', 'Dr. Name', 'Dr. Department',
                      'Service Type', 'Service Name', 'Net Amount']])
    else:
        print("\nNo matches found")

import pandas as pd
import re

def normalize_doctor_name(name: str) -> str:
    """Hospital-standard cleaning logic."""
    name = re.sub(r'\(.*?\)', '', str(name))
    name = re.sub(r'^dr[.\s]*', '', name, flags=re.IGNORECASE)
    name = re.sub(r'[^a-zA-Z]', '', name)
    return name.lower().strip()


def combine_doctor_visit_reports(
    with_pkg_path: str,
    without_pkg_path: str,
    output_path: str
) -> pd.DataFrame:
    """Combine package and non-package visit reports, add Type column."""
    df_with = pd.read_excel(with_pkg_path)
    df_without = pd.read_excel(without_pkg_path)

    df_with['Type'] = 'Package'
    df_without['Type'] = 'Open'

    combined = pd.concat([df_with, df_without], axis=0, ignore_index=True)
    combined.to_excel(output_path, index=False)
    print(f"Saved combined visit report: {output_path}")
    return combined


def get_cross_consultations(
    visit_file: str,
    bill_file: str,
    doctor_list: list[str],
    unit_name: str  # New parameter for hospital/unit name
) -> pd.DataFrame:
    """
    Process one hospital's reports and extract only Cross consultations
    for the specified doctors. Adds a 'Unit' column.
    """
    df_visit = pd.read_excel(visit_file)
    df_bill =  pd.read_excel(bill_file)

    # Add Consultation Type column
    df_visit['Consultation Type'] = pd.NA

    # Normalize admitting doctor names and map admissions
    df_bill['clean_admit'] = df_bill['Admiting Doctor'].map(normalize_doctor_name)
    admission_map = (
        df_bill[['clean_admit', 'Admission No.']]
        .groupby('clean_admit')['Admission No.']
        .unique()
    )

    # Normalize doctor names in visit report
    df_visit['clean_doc'] = df_visit['Doctor Name'].map(normalize_doctor_name)

    # Prepare normalized doctor set
    norm_docs = {normalize_doctor_name(d) for d in doctor_list}

    # With this corrected logic:
    for norm_doc in norm_docs:
        mask_doc = df_visit['clean_doc'] == norm_doc
        if norm_doc not in admission_map:
            # No admissions for this doctor β†’ all visits are Cross
            df_visit.loc[mask_doc, 'Consultation Type'] = 'Cross'
        else:
            mask_adm = df_visit['Admission No.'].isin(admission_map[norm_doc])
            df_visit.loc[mask_doc & mask_adm, 'Consultation Type'] = 'Self'
            df_visit.loc[mask_doc & ~mask_adm, 'Consultation Type'] = 'Cross'

    # Filter only Cross consults for target doctors
    result = df_visit[df_visit['clean_doc'].isin(norm_docs) &
                      (df_visit['Consultation Type'] == 'Cross')].copy()

    result.drop(columns='clean_doc', inplace=True)

    # Add Unit column
    result['Unit'] = unit_name

    return result


def main():
    # Doctors to analyze
    doctors = [
        'Dr. Amit Kumar'
        ]

    # Maatri Hospital Files
    maatri_files = {
        'with_pkg': '/content/processed_maatri_doctor_visit_report_with_package.xlsx',
        'without_pkg': '/content/processed_maatri_doctor_visit_report_without_package.xlsx',
        'bill_register': '/content/processed_maatri_print_inpatient_bill_register_report.xlsx',
        'visit_output': 'final_processed_maatri_doctor_visit_report.xlsx'
    }

    # Another Hospital Files (update these paths accordingly)
    mssh_files = {
        'with_pkg': '/content/processed_doctor_visit_report_with_package.xlsx',
        'without_pkg': '/content/processed_doctor_visit_report_without_package.xlsx',
        'bill_register': '/content/processed_print_inpatient_bill_register_report.xlsx',
        'visit_output': 'final_processed_mssh_doctor_visit_report.xlsx'
    }

    # Step 1: Combine doctor visit reports for both hospitals
    print("\n--- Combining Visit Reports ---")
    combine_doctor_visit_reports(
        maatri_files['with_pkg'],
        maatri_files['without_pkg'],
        maatri_files['visit_output']
    )

    combine_doctor_visit_reports(
        mssh_files['with_pkg'],
        mssh_files['without_pkg'],
        mssh_files['visit_output']
    )

    # Step 2: Get cross consultations from both hospitals
    print("\n--- Extracting Cross Consultations ---")
    cross_maatri = get_cross_consultations(
        maatri_files['visit_output'],
        maatri_files['bill_register'],
        doctors,
        unit_name='Maatri'
    )
    print(f"Found {len(cross_maatri)} cross consultations in Maatri")

    cross_mssh = get_cross_consultations(
        mssh_files['visit_output'],
        mssh_files['bill_register'],
        doctors,
        unit_name='MSSH'
    )
    print(f"Found {len(cross_mssh)} cross consultations in MSSH")

    # Step 3: Combine both hospitals' cross consults
    combined_cross = pd.concat([cross_maatri, cross_mssh], ignore_index=True)

    # Step 4: Save final merged file
    output_file = 'combined_cross_consultations_from_both_hospitals.xlsx'
    combined_cross.to_excel(output_file, index=False)
    print(f"Final merged report saved at: {output_file}")
    print("Each record now includes a 'Unit' column indicating the source hospital.")

if __name__ == "__main__":
    main()

# code for handling both surgical and medical management cases
# this one is for MHS Doctors (takes maatri and mssh reports both)

import pandas as pd
import re

def normalize_doctor_name(name: str) -> str:
    """Normalize doctor names to plain lowercase alphabetic."""
    name = re.sub(r'\(.*?\)', '', str(name))
    name = re.sub(r'^dr[.\s]*', '', name, flags=re.IGNORECASE)
    name = re.sub(r'[^A-Za-z]', '', name)
    return name.lower().strip()

def classify_type(service_series: pd.Series) -> str:
    """Assign Type based on Service Type values in the doctor’s records."""
    if service_series.str.contains(r'Package\(IPD\)', case=False, na=False).any():
        return 'Surgical-Package'
    if service_series.str.contains(r'OT Procedure', case=False, na=False).any():
        return 'Surgical-Open'
    return 'Medical'

def preprocess_revenue(
    file_path: str,
    doctor_name: str,
)-> pd.DataFrame:
    # 1) Load and convert Net Amount β†’ float
    df = pd.read_excel(
        file_path,
        converters={'Net Amount': lambda x: float(str(x).replace(',', '') or 0)}
    )

    # 2) Normalize & filter by doctor + IPD
    df['Clean Doctor'] = df['Name'].apply(normalize_doctor_name)
    norm_doc = normalize_doctor_name(doctor_name)
    df_doc = df[
        (df['Clean Doctor'] == norm_doc) &
        (df['Patient Type'].str.contains('IPD', case=False, na=False))
    ].copy()

    # Handle empty DataFrame gracefully without raising error
    if df_doc.empty:
        print(f"Note: No IPD records found for {doctor_name}. Skipping surgical/medical management processing.")
        # Create an empty Excel file (this is expected by the workflow)
        # But the empty DataFrame will signal to other functions not to create sheets
        empty_df = pd.DataFrame()
        empty_df.to_excel(output_path, index=False)
        return empty_df

    # 3) Admission numbers for this doctor’s IPD cases
    admission_nos = df_doc['Admission No.'].unique()

    # 4) Build df_adm: all records for those admissions, excluding 'Doctors Visit'
    mask_not_visit = df['Service Type'].str.strip().str.lower() != 'doctors visit'
    df_adm = df[df['Admission No.'].isin(admission_nos) & mask_not_visit].copy()

    # 5) net bill: sum Net Amount per admission (excl. Doctors Visit)
    net_sums = (
        df_adm
        .groupby('Admission No.')['Net Amount']
        .sum()
        .rename('Net Bill')
    )

    # 6) Exclusions-Drugs & Implants: filter to this doctor's records, then by service type
    drug_implant_sums = (
        df_adm[
            (df_adm['Clean Doctor'] == norm_doc) &
            df_adm['Service Type'].str.contains(r'IP Pharmacy|IP Implants', case=False, na=False)
        ]
        .groupby('Admission No.')['Net Amount']
        .sum()
        .rename('Exclusions-Drugs & Implants')
    )

    # 7) Exclusions-Other Doctors' Fees
    other_fees_sums = (
        df_adm[df_adm['Clean Doctor'] != norm_doc]
        .groupby('Admission No.')['Net Amount']
        .sum()
        .rename("Exclusions-Other Doctors' Fees")
    )

    # 8) classify Type using only this doctor’s IPD records
    type_map = (
        df_doc
        .groupby('Admission No.')['Service Type']
        .apply(classify_type)
    )

    # 9) pick one row per Admission No. (cols B–I)
    cols_B_to_I = df_doc.columns[2:12]  # adjust if layout differs
    sample = df_doc.drop_duplicates('Admission No.')[list(cols_B_to_I)].copy()
    if 'Admission No.' not in sample.columns:
        sample.insert(0, 'Admission No.', admission_nos)

    # 10) map computed series back onto sample, filling missing with 0
    sample['Net Bill'] = sample['Admission No.'].map(net_sums).fillna(0)
    sample['Type'] = sample['Admission No.'].map(type_map)
    sample['Exclusions-Drugs & Implants'] = (
        sample['Admission No.'].map(drug_implant_sums).fillna(0)
    )
    sample["Exclusions-Other Doctors' Fees"] = (
        sample['Admission No.'].map(other_fees_sums).fillna(0)
    )

    # 11) round all numeric columns to nearest integer
    num_cols = sample.select_dtypes(include='number').columns
    sample[num_cols] = sample[num_cols].round(0).astype(int)

    # 12) swap 'Type' and 'Net Bill' using the second method
    cols = sample.columns.tolist()
    i, j = cols.index('Type'), cols.index('Net Bill')
    cols[i], cols[j] = cols[j], cols[i]
    sample = sample[cols]

    return sample

def combine_reports(
    file_paths: list,
    doctor_name: str,
    output_path: str
) -> pd.DataFrame:
    """Process multiple files and merge results. Assumes NO DUPLICATES between files."""
    dfs = []
    
    for file in file_paths:
        try:
            df = preprocess_revenue(file, doctor_name)
            # Only append non-empty DataFrames
            if not df.empty:
                dfs.append(df)
            else:
                print(f"No IPD records found in {file} for {doctor_name}")
        except Exception as e:
            print(f"Error processing {file}: {e}")

    if not dfs:
        print(f"Note: No IPD records found for {doctor_name} in any file. Creating empty dataset.")
        # Create an empty Excel file (this is expected by the workflow)
        # But the empty DataFrame will signal to other functions not to create sheets
        empty_df = pd.DataFrame()
        empty_df.to_excel(output_path, index=False)
        return empty_df

    # Simply concatenate all DataFrames
    combined_df = pd.concat(dfs, ignore_index=True)

    # Sort by Admission No. (optional but improves readability)
    if 'Admission No.' in combined_df.columns and not combined_df.empty:
        combined_df.sort_values(by='Admission No.', inplace=True)

    # Export to Excel
    combined_df.to_excel(output_path, index=False)
    print(f"Combined report saved at: {output_path}")
    return combined_df

if __name__ == "__main__":
    # Input files
    file_paths = [
        '/content/processed_print_hospital_revenue_report.php (11).xlsx',
        '/content/processed_maatri_print_hospital_revenue_report.php (16).xlsx'
    ]

    doctor_name = 'Dr. Amit Kumar'
    output_path = f'processed_medical_and_surgical_cases_with_exclusions.xlsx'

    # Combine reports
    combined_summary = combine_reports(file_paths, doctor_name, output_path)

    # Print first few rows of the combined report
    print(combined_summary.head())

# code to dump the dictionary in .json file

import json

# Custom formatter for more compact JSON
def dump_compact_json(data, file):
    """Dump JSON in a compact format with properly aligned exclusions"""
    with open(file, 'w') as f:
        f.write('{\n')
        items = []
        for i, (doctor, config) in enumerate(data.items()):
            # Format services as single-line array
            services = ', '.join(str(v) for v in config['services'])

            # Format exclusions with proper indentation
            exclusions = []
            for excl in config['exclusions']:
                excl_str = ', '.join('true' if v else 'false' for v in excl)
                # Add 6-space indentation for each exclusion line
                exclusions.append(f'      [ {excl_str} ]')
            exclusions_str = ',\n'.join(exclusions)

            # Create the doctor entry with consistent formatting
            doctor_entry = f'  "{doctor}": {{\n' \
                          f'    "services": [ {services} ],\n' \
                          f'    "exclusions": [\n' \
                          f'{exclusions_str}\n' \
                          f'    ]\n' \
                          f'  }}'
            items.append(doctor_entry)

        f.write(',\n'.join(items))
        f.write('\n}')

# Save using our custom formatter
# dump_compact_json(DOCTORS, 'mhs_doctors_config.json')

"""
SERVICES = [
    "OPD Consultation",
    "IPD Cross Consultation",
    "OPD Diagnostics & Pathology",
    "Daycare Procedure",
    "Surgery (Package cases)",
    "Surgery (Open cases)",
    "Medical Management"
]

  [[Exclusions - Drugs & Implants, Exclusions - Other Doctor Fees]] in 2nd List
  [Surgical (Package) 1, Surgical (Package) 2, Surgical Management (Non-Package) 1,
   Surgical Management (Non-Package) 2, Medical Management 1, Medical Management 2]

"""

# SORTED ONE
# Doctor configuration - percentages for services and exclusions
# Backup

'''
DOCTORS = {
    "Dr. Akanksha Singh": {
        "services": [0.60, 0.60, 0.15, 0.60, 0, 0, 0],
        "exclusions": [
            [False, False],   # Surgical Management (Package)
            [False, False],   # Surgical Management (Non-Package)
            [False, False]   # Medical Management
        ]
    },
    "Dr. Amit Kumar": {
        "services": [0.80, 0.80, 0.10, 0.50, 0.20, 0.20, 0.20],
        "exclusions": [
            [False, True],   # Surgical Management (Package)
            [False, True],   # Surgical Management (Non-Package)
            [False, True]    # Medical Management
        ]
    },
    "Dr. Avinash Shekhar Jaiswal": {
        "services": [0.80, 0.80, 0.10, 0.50, 0.20, 0.20, 0.20],
        "exclusions": [
            [False, True],   # Surgical Management (Package)
            [False, True],   # Surgical Management (Non-Package)
            [False, True]    # Medical Management
        ]
    },
    "Dr. Bharti Anand": {
        "services": [0.70, 0.70, 0.10, 0.50, 0, 0, 0],
        "exclusions": [
            [False, False],   # Surgical Management (Package)
            [False, False],   # Surgical Management (Non-Package)
            [False, False]   # Medical Management
        ]
    },
    "Dr. Deepti Sinha": {
        "services": [0.70, 0.70, 0.10, 0, 0.20, 0.20, 0],
        "exclusions": [
            [True, True],     # Surgical Management (Package)
            [True, True],     # Surgical Management (Non-Package)
            [False, False]    # Medical Management
        ]
    },
    "Dr. Farheen Fatma": {
        "services": [0.70, 0.70, 0.10, 0, 0, 0, 0],
        "exclusions": [
            [False, False],   # Surgical Management (Package)
            [False, False],   # Surgical Management (Non-Package)
            [False, False]   # Medical Management
        ]
    },
    "Dr. Ginny": {
        "services": [0.70, 0.70, 0.10, 0.50, 0, 0, 0],
        "exclusions": [
            [False, False],   # Surgical Management (Package)
            [False, False],   # Surgical Management (Non-Package)
            [False, False]   # Medical Management
        ]
    },
    "Dr. Govind Kumar": {
        "services": [0.60, 0.60, 0.15, 0.60, 0, 0, 0],
        "exclusions": [
            [False, False],   # Surgical Management (Package)
            [False, False],   # Surgical Management (Non-Package)
            [False, False]   # Medical Management
        ]
    },
    "Dr. Jyotsana": {
        "services": [0.70, 0.70, 0.10, 0.50, 0, 0, 0],
        "exclusions": [
            [False, False],   # Surgical Management (Package)
            [False, False],   # Surgical Management (Non-Package)
            [False, False]   # Medical Management
        ]
    },
    "Dr. Khalid Husain": {
        "services": [0.70, 0.70, 0.20, 0, 0, 0, 0],
        "exclusions": [
            [False, False],   # Surgical Management (Package)
            [False, False],   # Surgical Management (Non-Package)
            [False, False]   # Medical Management
        ]
    },
    "Dr. Komal Kumari": {
        "services": [0.70, 0.70, 0.10, 0.50, 0, 0, 0],
        "exclusions": [
            [False, False],   # Surgical Management (Package)
            [False, False],   # Surgical Management (Non-Package)
            [False, False]   # Medical Management
        ]
    },
    "Dr. Manvi Singh": {
        "services": [0.70, 0.70, 0.10, 0.50, 0, 0, 0],
        "exclusions": [
            [False, False],   # Surgical Management (Package)
            [False, False],   # Surgical Management (Non-Package)
            [False, False]   # Medical Management
        ]
    },
    "Dr. Raushan Bhatt": {
        "services": [0.70, 0.70, 0.10, 0.50, 0, 0, 0],
        "exclusions": [
            [False, False],   # Surgical Management (Package)
            [False, False],   # Surgical Management (Non-Package)
            [False, False]   # Medical Management
        ]
    },
    "Dr. Raushan Kumar": {
        "services": [0.80, 0.80, 0.10, 0.50, 0.20, 0.20, 0.20],
        "exclusions": [
            [False, True],   # Surgical Management (Package)
            [False, True],   # Surgical Management (Non-Package)
            [False, True]   # Medical Management
        ]
    },
    "Dr. Shiksha Narang": {
        "services": [0.70, 0.70, 0.10, 0, 0, 0, 0],
        "exclusions": [
            [False, False],   # Surgical Management (Package)
            [False, False],   # Surgical Management (Non-Package)
            [False, False]   # Medical Management
        ]
    },
    "Dr. Shreeparna Deb": {
        "services": [0.60, 0.60, 0.15, 0.60, 0, 0, 0],
        "exclusions": [
            [False, False],   # Surgical Management (Package)
            [False, False],   # Surgical Management (Non-Package)
            [False, False]   # Medical Management
        ]
    },
    "Dr. Vanshika Rai": {
        "services": [0.60, 0.60, 0.15, 0.60, 0, 0, 0],
        "exclusions": [
            [False, False],   # Surgical Management (Package)
            [False, False],   # Surgical Management (Non-Package)
            [False, False]   # Medical Management
        ]
    }
}
'''

# FINAL UPDATED CODE handling medical and surgical visibility (without IPD Consultation services)
# and diag_path and daycare services added

import pandas as pd
import openpyxl
from openpyxl.styles import PatternFill, Border, Side, Alignment, Font
import os
import datetime
import json
from pathlib import Path

# Define all services in order
SERVICES = [
    "OPD Consultation",
    "IPD Cross Consultation",
    "OPD Diagnostics & Pathology",
    "Daycare Procedure",
    "Surgery (Package cases)",
    "Surgery (Open cases)",
    "Medical Management"
]

# Define management types for exclusions
MANAGEMENT_TYPES = [
    "Surgical Management (Package)",
    "Surgical Management (Non-Package)",
    "Medical Management"
]

# Define exclusion types
EXCLUSION_TYPES = [
    "Exclusions - Drugs & Implants",
    "Exclusions - Other Doctor Fees"
]

"""
SERVICES = [
    "OPD Consultation",
    "IPD Cross Consultation",
    "OPD Diagnostics & Pathology",
    "Daycare Procedure",
    "Surgery (Package cases)",
    "Surgery (Open cases)",
    "Medical Management"
]

  [[Exclusions - Drugs & Implants, Exclusions - Other Doctor Fees]] in 2nd List
  [Surgical (Package) 1, Surgical (Package) 2, Surgical Management (Non-Package) 1,
   Surgical Management (Non-Package) 2, Medical Management 1, Medical Management 2]

"""

# SORTED ONE
# Doctor configuration - percentages for services and exclusions
# -----> DOCTORS Dictionary

# Get the directory of the current script (Variable folder)
current_dir = Path(__file__).parent.resolve()

# Construct the full path to the config file
config_path = current_dir / "mhs_doctors_config.json"

with open(config_path, 'r') as f:
    DOCTORS = json.load(f)


# File mapping for each service
SERVICE_FILES = {
    "OPD Consultation": "processed_opd_consultations.xlsx",
    "IPD Cross Consultation": "combined_cross_consultations_from_both_hospitals.xlsx",
    "OPD Diagnostics & Pathology": "processed_diag_and_path.xlsx",
    "Daycare Procedure": "processed_daycare.xlsx",
    "Surgery (Package cases)": "processed_medical_and_surgical_cases_with_exclusions.xlsx",
    "Surgery (Open cases)": "processed_medical_and_surgical_cases_with_exclusions.xlsx",
    "Medical Management": "processed_medical_and_surgical_cases_with_exclusions.xlsx"
}

# Build DOCTOR_CONFIG from the simplified structure
DOCTOR_CONFIG = {
    "services": {},
    "exclusions": {}
}

# Build services configuration
for service in SERVICES:
    DOCTOR_CONFIG["services"][service] = {
        "file": SERVICE_FILES[service],
        "variable_share": {
            doctor: data["services"][SERVICES.index(service)]
            for doctor, data in DOCTORS.items()
        }
    }

# Build exclusions configuration
for mgmt_type in MANAGEMENT_TYPES:
    DOCTOR_CONFIG["exclusions"][mgmt_type] = {}
    for excl_type in EXCLUSION_TYPES:
        excl_index = EXCLUSION_TYPES.index(excl_type)
        mgmt_index = MANAGEMENT_TYPES.index(mgmt_type)

        DOCTOR_CONFIG["exclusions"][mgmt_type][excl_type] = {
            doctor: data["exclusions"][mgmt_index][excl_index]
            for doctor, data in DOCTORS.items()
         }

current_month = datetime.datetime.now().strftime("%B")
current_year = datetime.datetime.now().year

# Helper function to clean numeric strings and convert to float
def clean_and_convert_to_float(value):
    if isinstance(value, (int, float)):
        return float(value)
    elif isinstance(value, str):
        cleaned = value.replace(",", "") # Remove commas
        try:
            return float(cleaned)
        except ValueError:
            return 0.0
    else:
        return 0.0

# Global styling objects
header_fill = PatternFill(start_color="92D050", end_color="92D050", fill_type="solid")
subheader_fill = PatternFill(start_color="B8CCE4", end_color="B8CCE4", fill_type="solid")
thin_border = Side(border_style="thin", color="000000")
border = Border(top=thin_border, left=thin_border, right=thin_border, bottom=thin_border)
header_font = Font(bold=True, color="FFFFFF", size=13)
subheader_font = Font(bold=True, size=12)
data_font = Font(size=11)
center_alignment = Alignment(horizontal="center", vertical="center")
left_alignment = Alignment(horizontal="left", vertical="center")
right_alignment = Alignment(horizontal="right", vertical="center")
yellow_fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")

# for summary sheet
def create_summary_sheet(workbook, doctor_name, current_month, current_year):
    summary_sheet = workbook.create_sheet("Summary", 0)

    # Set column widths
    summary_sheet.column_dimensions["A"].width = 5
    summary_sheet.column_dimensions["B"].width = 55
    summary_sheet.column_dimensions["C"].width = 25
    summary_sheet.column_dimensions["D"].width = 30
    summary_sheet.column_dimensions["E"].width = 30

    # Add title row
    summary_sheet.merge_cells("B2:E2")
    title_cell = summary_sheet["B2"]
    title_cell.value = f"[{doctor_name}] Variable Payout Summary - {current_month} {current_year}"
    title_cell.fill = header_fill
    title_cell.font = header_font
    title_cell.alignment = center_alignment

    # Add column headers
    summary_sheet["B3"] = "Services"
    summary_sheet["C3"] = "Total Sum"
    summary_sheet["D3"] = "Variable Share"
    summary_sheet["E3"] = "Final Share"

    for col in ["B", "C", "D", "E"]:
        cell = summary_sheet[f"{col}3"]
        cell.fill = subheader_fill
        cell.font = subheader_font
        cell.alignment = center_alignment
        cell.border = border

    # Dynamically generate summary_rows based on DOCTOR_CONFIG
    summary_rows = []
    for service_name, service_data in DOCTOR_CONFIG["services"].items():
        variable_share_for_doctor = service_data["variable_share"].get(doctor_name)
        if variable_share_for_doctor is not None and (
            variable_share_for_doctor != 0.00 or
            service_name in ["Surgery (Package cases)", "Surgery (Open cases)"]
        ) and service_name != "Medical Management":
            summary_rows.append({"service": service_name, "file": service_data["file"], "variable_share": variable_share_for_doctor})

    # Initialize flags for surgery and medical management visibility
    show_surgery_package = DOCTOR_CONFIG["services"]["Surgery (Package cases)"]["variable_share"].get(doctor_name, 0.00) != 0.00
    show_surgery_open = DOCTOR_CONFIG["services"]["Surgery (Open cases)"]["variable_share"].get(doctor_name, 0.00) != 0.00
    show_medical_management = DOCTOR_CONFIG["services"]["Medical Management"]["variable_share"].get(doctor_name, 0.00) != 0.00
    show_total_surgeries_line = show_surgery_package or show_surgery_open

    # Separate the new services for positioning
    new_services_rows = []
    for service in ["OPD Diagnostics & Pathology", "Daycare Procedure"]:
        if DOCTOR_CONFIG["services"][service]["variable_share"].get(doctor_name, 0.00) != 0.00:
            new_services_rows.append({
                "service": service,
                "file": DOCTOR_CONFIG["services"][service]["file"],
                "variable_share": DOCTOR_CONFIG["services"][service]["variable_share"].get(doctor_name)
            })

    # Add specific surgical/medical management rows if applicable
    surgical_rows = []
    if show_total_surgeries_line:
        surgical_rows.append({"service": f"Surgeries (Total {0} Surgeries in {current_month} {current_year})", "file": None, "variable_share": None})
    if show_surgery_package:
        surgical_rows.append({"service": "    Surgery (Package cases)",  "file": DOCTOR_CONFIG["services"]["Surgery (Package cases)"]["file"],  "variable_share": DOCTOR_CONFIG["services"]["Surgery (Package cases)"]["variable_share"].get(doctor_name)})
    if show_surgery_open:
        surgical_rows.append({"service": "    Surgery (Open cases)",     "file": DOCTOR_CONFIG["services"]["Surgery (Open cases)"]["file"],     "variable_share": DOCTOR_CONFIG["services"]["Surgery (Open cases)"]["variable_share"].get(doctor_name)})
    if show_medical_management:
        surgical_rows.append({"service": "Medical Management",           "file": DOCTOR_CONFIG["services"]["Medical Management"]["file"],        "variable_share": DOCTOR_CONFIG["services"]["Medical Management"]["variable_share"].get(doctor_name)})

    # Remove duplicates from initial summary_rows
    services_to_remove = {"Surgery (Package cases)", "Surgery (Open cases)", "Medical Management", "OPD Diagnostics & Pathology", "Daycare Procedure"}
    summary_rows = [r for r in summary_rows if r["service"] not in services_to_remove]

    # Add new services after OPD/Cross but before surgery sections
    summary_rows.extend(new_services_rows)
    summary_rows.extend(surgical_rows)

    # Add data rows
    row_num = 4
    for row_data in summary_rows:
        summary_sheet[f"B{row_num}"] = row_data["service"]
        for col in ["B", "C", "D", "E"]:
            cell = summary_sheet[f"{col}{row_num}"]
            cell.border = border
            cell.font = data_font
            if col == "B":
                cell.alignment = left_alignment
            else:
                cell.alignment = right_alignment
        row_num += 1

    summary_sheet.insert_rows(row_num)
    for col in ["B", "C", "D", "E"]:
      summary_sheet[f"{col}{row_num}"].border = border

    row_num += 1

    # Add total and additional rows
    total_row = row_num
    summary_sheet[f"B{row_num}"] = f"Total Variable for {current_month}-{current_year}"
    summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)

    row_num += 1
    summary_sheet[f"B{row_num}"] = "Add: Previous Bills Realised from TPAs/Corporates"
    summary_sheet[f"B{row_num}"].font = Font(size=11)

    row_num += 1
    summary_sheet[f"B{row_num}"] = f"Less: TPA/Corporate Dues for {current_month}-25"
    summary_sheet[f"B{row_num}"].font = Font(size=11)

    row_num += 1
    variable_payable_row = row_num
    summary_sheet[f"B{row_num}"] = f"Variable Payable for {current_month}-2025"
    summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)

    row_num += 1
    tds_row = row_num
    summary_sheet[f"B{row_num}"] = "Less: TDS @ 10%"
    summary_sheet[f"B{row_num}"].font = Font(size=11)

    row_num += 1
    net_payable_row = row_num
    summary_sheet[f"B{row_num}"] = f"Net Payable for {current_month}-2025"
    summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)

    # Highlight the net payable row
    for col in ["B", "C", "D", "E"]:
        summary_sheet[f"{col}{net_payable_row}"].fill = yellow_fill

    # Apply borders to all additional rows
    for r in range(total_row, row_num + 1):
        for col in ["B", "C", "D", "E"]:
            cell = summary_sheet[f"{col}{r}"]
            cell.border = border
            if col != "B":
                cell.alignment = right_alignment

    # Add 3 blank rows before Note:
    row_num += 3

    # Add Exclusions table
    summary_sheet[f"B{row_num}"] = "Note:"
    row_num += 1
    summary_sheet[f"B{row_num}"] = "Exclusions:"
    row_num += 1

    # Exclusions table headers
    summary_sheet.merge_cells(start_row=row_num, start_column=2, end_row=row_num, end_column=3)
    header_services_cell = summary_sheet["B" + str(row_num)]
    header_services_cell.value = "Services"
    header_services_cell.font = subheader_font
    header_services_cell.alignment = center_alignment
    header_services_cell.fill = subheader_fill

    for col_idx in range(2, 4):
        summary_sheet.cell(row=row_num, column=col_idx).border = border

    summary_sheet["D" + str(row_num)] = "Exclusions - Drugs & Implants"
    summary_sheet["E" + str(row_num)] = "Exclusions - Other Doctor Fees"

    summary_sheet.column_dimensions["B"].width = 60
    summary_sheet.column_dimensions["D"].width = 25
    summary_sheet.column_dimensions["E"].width = 25

    for col_idx in [4, 5]:
            cell = summary_sheet.cell(row=row_num, column=col_idx)
            cell.font = subheader_font
            cell.alignment = center_alignment
            cell.fill = subheader_fill
            cell.border = border

    row_num += 1

    # Exclusions table content
    exclusion_data = [
        ("In Surgical Management (Package)", "Surgical Management (Package)"),
        ("In Surgical Management (Non Package)", "Surgical Management (Non-Package)"),
        ("In Medical Management", "Medical Management")
    ]

    for display_name, config_key in exclusion_data:
        summary_sheet.merge_cells(start_row=row_num, start_column=2, end_row=row_num, end_column=3)
        content_services_cell = summary_sheet["B" + str(row_num)]
        content_services_cell.value = display_name
        content_services_cell.font = data_font
        content_services_cell.alignment = left_alignment

        for col_idx in range(2, 4):
            summary_sheet.cell(row=row_num, column=col_idx).border = border

        drugs_excluded = DOCTOR_CONFIG["exclusions"][config_key]["Exclusions - Drugs & Implants"].get(doctor_name, False)
        other_fees_excluded = DOCTOR_CONFIG["exclusions"][config_key]["Exclusions - Other Doctor Fees"].get(doctor_name, False)

        drugs_cell = summary_sheet["D" + str(row_num)]
        other_fees_cell = summary_sheet["E" + str(row_num)]

        drugs_cell.value = "Yes" if drugs_excluded else "No"
        other_fees_cell.value = "Yes" if other_fees_excluded else "No"

        if drugs_excluded:
            drugs_cell.font = Font(bold=True)
        if other_fees_excluded:
            other_fees_cell.font = Font(bold=True)

        for col_idx in [4, 5]:
            cell = summary_sheet.cell(row=row_num, column=col_idx)
            cell.alignment = center_alignment
            cell.border = border

        row_num += 1

    return summary_sheet, summary_rows, net_payable_row, show_surgery_package, show_surgery_open, show_medical_management, show_total_surgeries_line

# Function to populate the summary sheet with data
def populate_summary_data(summary_sheet, summary_rows, data_dir, doctor_name, net_payable_row, show_surgery_package, show_surgery_open, show_medical_management, show_total_surgeries_line, current_month, current_year):
    total_sums = {}
    surgical_medical_df = None
    surgical_medical_file = DOCTOR_CONFIG["services"]["Surgery (Package cases)"]["file"]

    if os.path.exists(os.path.join(data_dir, surgical_medical_file)):
        surgical_medical_df = pd.read_excel(os.path.join(data_dir, surgical_medical_file))
        surgical_medical_df.dropna(how='all', inplace=True)
        for col in ["Net Bill", "Exclusions-Drugs & Implants", "Exclusions-Other Doctors' Fees"]:
            if col in surgical_medical_df.columns:
                surgical_medical_df[col] = surgical_medical_df[col].apply(clean_and_convert_to_float)

    row_num = 4
    for row_data in summary_rows:
        service = row_data["service"]
        file = row_data.get("file")
        variable_share = row_data.get("variable_share")
        current_total_sum = 0.0
        df_to_process = None

        if service == "OPD Consultation":
            if file and os.path.exists(os.path.join(data_dir, file)):
                df_to_process = pd.read_excel(os.path.join(data_dir, file))
                df_to_process.dropna(how='all', inplace=True)
                if "Net Amount" in df_to_process.columns:
                    df_to_process["Net Amount"] = df_to_process["Net Amount"].apply(clean_and_convert_to_float)
                    current_total_sum = df_to_process["Net Amount"].sum()

        # REMOVED: IPD Consultation (Non-Package) and IPD Consultation (Package) processing

        elif service == "IPD Cross Consultation":
            if file and os.path.exists(os.path.join(data_dir, file)):
                df_to_process = pd.read_excel(os.path.join(data_dir, file))
                df_to_process.dropna(how='all', inplace=True)
                if "Total" in df_to_process.columns:
                    df_to_process["Total"] = df_to_process["Total"].apply(clean_and_convert_to_float)
                    current_total_sum = df_to_process["Total"].sum()

        # New services: OPD Diagnostics & Pathology and Daycare Procedure
        elif service in ["OPD Diagnostics & Pathology", "Daycare Procedure"]:
            if file and os.path.exists(os.path.join(data_dir, file)):
                df_to_process = pd.read_excel(os.path.join(data_dir, file))
                df_to_process.dropna(how='all', inplace=True)
                if "Net Amount" in df_to_process.columns:
                    df_to_process["Net Amount"] = df_to_process["Net Amount"].apply(clean_and_convert_to_float)
                    current_total_sum = df_to_process["Net Amount"].sum()

        elif service == "    Surgery (Package cases)":
            if surgical_medical_df is not None:
                df_filtered = surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Package"].copy()
                if not df_filtered.empty and "Net Bill" in df_filtered.columns:
                    df_filtered["Final Bill"] = df_filtered["Net Bill"]
                    if DOCTOR_CONFIG["exclusions"]["Surgical Management (Package)"]["Exclusions - Drugs & Implants"].get(doctor_name, False):
                        df_filtered["Final Bill"] -= df_filtered["Exclusions-Drugs & Implants"]
                    if DOCTOR_CONFIG["exclusions"]["Surgical Management (Package)"]["Exclusions - Other Doctor Fees"].get(doctor_name, False):
                        df_filtered["Final Bill"] -= df_filtered["Exclusions-Other Doctors' Fees"]
                    current_total_sum = df_filtered["Final Bill"].sum()
                    if show_total_surgeries_line:
                        for i, row_data_summary in enumerate(summary_rows):
                            if "Surgeries (Total" in row_data_summary["service"]:
                                total_surgeries_count = 0
                                if show_surgery_package:
                                    total_surgeries_count += surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Package"].shape[0]
                                if show_surgery_open:
                                    total_surgeries_count += surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Open"].shape[0]
                                summary_sheet[f"B{i+4}"].value = f"Surgeries (Total {total_surgeries_count} Surgeries in {current_month} {current_year})"
                                break

        elif service == "    Surgery (Open cases)":
            if surgical_medical_df is not None:
                df_filtered = surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Open"].copy()
                if not df_filtered.empty and "Net Bill" in df_filtered.columns:
                    df_filtered["Final Bill"] = df_filtered["Net Bill"]
                    if DOCTOR_CONFIG["exclusions"]["Surgical Management (Non-Package)"]["Exclusions - Drugs & Implants"].get(doctor_name, False):
                        df_filtered["Final Bill"] -= df_filtered["Exclusions-Drugs & Implants"]
                    if DOCTOR_CONFIG["exclusions"]["Surgical Management (Non-Package)"]["Exclusions - Other Doctor Fees"].get(doctor_name, False):
                        df_filtered["Final Bill"] -= df_filtered["Exclusions-Other Doctors' Fees"]
                    current_total_sum = df_filtered["Final Bill"].sum()
                    if show_total_surgeries_line:
                        for i, row_data_summary in enumerate(summary_rows):
                            if "Surgeries (Total" in row_data_summary["service"]:
                                total_surgeries_count = 0
                                if show_surgery_package:
                                    total_surgeries_count += surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Package"].shape[0]
                                if show_surgery_open:
                                    total_surgeries_count += surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Open"].shape[0]
                                summary_sheet[f"B{i+4}"].value = f"Surgeries (Total {total_surgeries_count} Surgeries in {current_month} {current_year})"
                                break

        elif service == "Medical Management":
            if surgical_medical_df is not None:
                df_filtered = surgical_medical_df[surgical_medical_df["Type"] == "Medical"].copy()
                if not df_filtered.empty and "Net Bill" in df_filtered.columns:
                    df_filtered["Final Bill"] = df_filtered["Net Bill"]
                    if DOCTOR_CONFIG["exclusions"]["Medical Management"]["Exclusions - Drugs & Implants"].get(doctor_name, False):
                        df_filtered["Final Bill"] -= df_filtered["Exclusions-Drugs & Implants"]
                    if DOCTOR_CONFIG["exclusions"]["Medical Management"]["Exclusions - Other Doctor Fees"].get(doctor_name, False):
                        df_filtered["Final Bill"] -= df_filtered["Exclusions-Other Doctors' Fees"]
                    current_total_sum = df_filtered["Final Bill"].sum()

        total_sums[service] = current_total_sum

        if "Surgeries (Total" not in service:
          summary_sheet[f"C{row_num}"] = int(current_total_sum)
          summary_sheet[f"C{row_num}"].number_format = "β‚Ή #,##0"

        if variable_share is not None:
            if isinstance(variable_share, (int, float)) and variable_share <= 1.0:
                summary_sheet[f"D{row_num}"] = int(variable_share * 100)
                summary_sheet[f"D{row_num}"].number_format = "0\"%\""
                final_share = current_total_sum * variable_share
            elif isinstance(variable_share, (int, float)) and variable_share > 1.0:
                summary_sheet[f"D{row_num}"] = int(variable_share)
                summary_sheet[f"D{row_num}"].number_format = "#,##0"
                final_share = current_total_sum * variable_share
            else:
                summary_sheet[f"D{row_num}"] = int(variable_share * 100) if isinstance(variable_share, float) else variable_share
                summary_sheet[f"D{row_num}"].number_format = "0\"%\"" if isinstance(variable_share, float) else "General"
                final_share = current_total_sum * variable_share if isinstance(variable_share, float) else 0

            summary_sheet[f"E{row_num}"] = int(final_share)
            summary_sheet[f"E{row_num}"].number_format = "β‚Ή #,##0"
            total_sums[f"{service}_final"] = final_share

        row_num += 1

    row_num+=1
    total_final_share = sum([v for k, v in total_sums.items() if k.endswith("_final")])
    total_row = row_num
    summary_sheet[f"E{total_row}"] = int(total_final_share)
    summary_sheet[f"E{total_row}"].number_format = "β‚Ή #,##0"

    row_num += 1
    summary_sheet[f"B{row_num}"] = "Add: Previous Bills Realised from TPAs/Corporates"
    summary_sheet[f"B{row_num}"].font = Font(size=11)

    row_num += 1
    summary_sheet[f"B{row_num}"] = f"Less: TPA/Corporate Dues for {current_month}-{current_year}"
    summary_sheet[f"B{row_num}"].font = Font(size=11)

    row_num += 1
    variable_payable = total_final_share
    summary_sheet[f"B{row_num}"] = f"Variable Payable for {current_month}-{current_year}"
    summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)
    summary_sheet[f"E{row_num}"] = int(variable_payable)
    summary_sheet[f"E{row_num}"].number_format = "β‚Ή #,##0"

    row_num += 1
    tds = variable_payable * 0.10
    summary_sheet[f"B{row_num}"] = "Less: TDS @ 10%"
    summary_sheet[f"B{row_num}"].font = Font(size=11)
    summary_sheet[f"E{row_num}"] = int(tds)
    summary_sheet[f"E{row_num}"].number_format = "β‚Ή #,##0"

    row_num += 1
    net_payable = variable_payable - tds
    summary_sheet[f"B{row_num}"] = f"Net Payable for {current_month}-{current_year}"
    summary_sheet[f"B{row_num}"].font = Font(bold=True, size=11)
    summary_sheet[f"E{row_num}"] = int(net_payable)
    summary_sheet[f"E{row_num}"].number_format = "β‚Ή #,##0"

    for r in range(total_row, row_num + 1):
        for col in ["B", "C", "D", "E"]:
            cell = summary_sheet[f"{col}{r}"]
            cell.border = border
            if col != "B":
                cell.alignment = right_alignment

    for col in ["B", "C", "D", "E"]:
        summary_sheet[f"{col}{net_payable_row}"].fill = yellow_fill

    return total_sums

# Function to add individual report sheets
def add_report_sheets(workbook, summary_rows, data_dir, doctor_name, show_surgery_package, show_surgery_open, show_medical_management, show_total_surgeries_line):
    surgical_medical_df = None
    surgical_medical_file = DOCTOR_CONFIG["services"]["Surgery (Package cases)"]["file"]

    if os.path.exists(os.path.join(data_dir, surgical_medical_file)):
        surgical_medical_df = pd.read_excel(os.path.join(data_dir, surgical_medical_file))
        surgical_medical_df.dropna(how='all', inplace=True)
        for col in ["Net Bill", "Exclusions-Drugs & Implants", "Exclusions-Other Doctors' Fees"]:
            if col in surgical_medical_df.columns:
                surgical_medical_df[col] = surgical_medical_df[col].apply(clean_and_convert_to_float)

    for row_data in summary_rows:
        service = row_data["service"]
        file = row_data.get("file")

        # Skip services that shouldn't have sheets
        if service == "Medical Management" and not show_medical_management:
            continue
        if service == "    Surgery (Package cases)" and not show_surgery_package:
            continue
        if service == "    Surgery (Open cases)" and not show_surgery_open:
            continue
        if "Surgeries (Total" in service:
            continue

        df_to_add_sheet = None
        sheet_name = service.replace("    ", "")[:31]

        if service == "OPD Consultation":
            if file and os.path.exists(os.path.join(data_dir, file)):
                df_to_add_sheet = pd.read_excel(os.path.join(data_dir, file))
                df_to_add_sheet.dropna(how='all', inplace=True)

        # REMOVED: IPD Consultation sheet creation

        elif service == "IPD Cross Consultation":
            if file and os.path.exists(os.path.join(data_dir, file)):
                df_to_add_sheet = pd.read_excel(os.path.join(data_dir, file))
                df_to_add_sheet.dropna(how='all', inplace=True)

        # New service: Diagnostics & Pathology
        elif service == "OPD Diagnostics & Pathology":
            if file and os.path.exists(os.path.join(data_dir, file)):
                df_to_add_sheet = pd.read_excel(os.path.join(data_dir, file))
                df_to_add_sheet.dropna(how='all', inplace=True)

        # New service: Daycare Procedure
        elif service == "Daycare Procedure":
            if file and os.path.exists(os.path.join(data_dir, file)):
                df_to_add_sheet = pd.read_excel(os.path.join(data_dir, file))
                df_to_add_sheet.dropna(how='all', inplace=True)

        elif service == "    Surgery (Package cases)":
            if surgical_medical_df is not None:
                df_filtered = surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Package"].copy()
                if not df_filtered.empty:
                    df_filtered["Final Bill"] = df_filtered["Net Bill"]
                    if DOCTOR_CONFIG["exclusions"]["Surgical Management (Package)"]["Exclusions - Drugs & Implants"].get(doctor_name, False):
                        df_filtered["Final Bill"] -= df_filtered["Exclusions-Drugs & Implants"]
                    if DOCTOR_CONFIG["exclusions"]["Surgical Management (Package)"]["Exclusions - Other Doctor Fees"].get(doctor_name, False):
                        df_filtered["Final Bill"] -= df_filtered["Exclusions-Other Doctors' Fees"]
                    df_to_add_sheet = df_filtered

        elif service == "    Surgery (Open cases)":
            if surgical_medical_df is not None:
                df_filtered = surgical_medical_df[surgical_medical_df["Type"] == "Surgical-Open"].copy()
                if not df_filtered.empty:
                    df_filtered["Final Bill"] = df_filtered["Net Bill"]
                    if DOCTOR_CONFIG["exclusions"]["Surgical Management (Non-Package)"]["Exclusions - Drugs & Implants"].get(doctor_name, False):
                        df_filtered["Final Bill"] -= df_filtered["Exclusions-Drugs & Implants"]
                    if DOCTOR_CONFIG["exclusions"]["Surgical Management (Non-Package)"]["Exclusions - Other Doctor Fees"].get(doctor_name, False):
                        df_filtered["Final Bill"] -= df_filtered["Exclusions-Other Doctors' Fees"]
                    df_to_add_sheet = df_filtered

        elif service == "Medical Management":
            if surgical_medical_df is not None:
                df_filtered = surgical_medical_df[surgical_medical_df["Type"] == "Medical"].copy()
                if not df_filtered.empty:
                    df_filtered["Final Bill"] = df_filtered["Net Bill"]
                    if DOCTOR_CONFIG["exclusions"]["Medical Management"]["Exclusions - Drugs & Implants"].get(doctor_name, False):
                        df_filtered["Final Bill"] -= df_filtered["Exclusions-Drugs & Implants"]
                    if DOCTOR_CONFIG["exclusions"]["Medical Management"]["Exclusions - Other Doctor Fees"].get(doctor_name, False):
                        df_filtered["Final Bill"] -= df_filtered["Exclusions-Other Doctors' Fees"]
                    df_to_add_sheet = df_filtered

        if df_to_add_sheet is not None and not df_to_add_sheet.empty:
            sheet = workbook.create_sheet(sheet_name)
            for col_idx, col_name in enumerate(df_to_add_sheet.columns, 1):
                sheet.cell(row=1, column=col_idx, value=col_name)
                sheet.cell(row=1, column=col_idx).font = Font(bold=True)

            for row_idx, row in df_to_add_sheet.iterrows():
                for col_idx, value in enumerate(row, 1):
                    sheet.cell(row=row_idx+2, column=col_idx, value=value)

            for col in sheet.columns:
                max_length = 0
                column = col[0].column_letter
                for cell in col:
                    try:
                        if len(str(cell.value)) > max_length:
                            max_length = len(str(cell.value))
                    except:
                        pass
                adjusted_width = (max_length + 2)
                sheet.column_dimensions[column].width = min(adjusted_width, 30)

def create_combined_report(data_dir, output_file, doctor_name, current_month, current_year):
    workbook = openpyxl.Workbook()
    default_sheet = workbook.active
    workbook.remove(default_sheet)

    summary_sheet, summary_rows, net_payable_row, show_surgery_package, show_surgery_open, show_medical_management, show_total_surgeries_line = create_summary_sheet(workbook, doctor_name, current_month, current_year)
    total_sums = populate_summary_data(summary_sheet, summary_rows, data_dir, doctor_name, net_payable_row, show_surgery_package, show_surgery_open, show_medical_management, show_total_surgeries_line,  current_month, current_year)
    add_report_sheets(workbook, summary_rows, data_dir, doctor_name, show_surgery_package, show_surgery_open, show_medical_management, show_total_surgeries_line)

    workbook.save(output_file)
    return output_file, total_sums

if __name__ == "__main__":
    data_dir = "."

    #---------------------------------------------------------------------------
    doctor_to_process = "Dr. Amit Kumar"
    current_month = "Feb"
    current_year = "2025"
    #---------------------------------------------------------------------------


    output_file = f"{doctor_to_process}-{current_month}-{current_year}.xlsx"
    report_file, totals = create_combined_report(data_dir, output_file, doctor_to_process)
    print(f"Combined report created: {report_file}")
    print(f"Total sums: {totals}")

import tempfile
import shutil

def generate_mhs_doctor_report(
    doctor_name: str,
    mhs_hospital_revenue_report_path: str,
    maatri_hospital_revenue_report_path: str,
    print_hospital_revenue_report_path: str,
    doctor_visit_report_with_package_path: str,
    doctor_visit_report_without_package_path: str,
    maatri_doctor_visit_report_with_package_path: str,
    maatri_doctor_visit_report_without_package_path: str,
    print_inpatient_bill_register_report_path: str,
    maatri_print_inpatient_bill_register_report_path: str,
    current_month: str,
    current_year: str
):
    """
    End-to-end processing for a single doctor's variable payout report.
    """

    try:
        with tempfile.TemporaryDirectory() as tmpdir:
            print(f"--- Starting processing for {doctor_name} for {current_month} {current_year} ---")

            # Step 1: Convert HTML files to Excel
            print("\n[Step 1/7] Converting HTML files to Excel...")
            html_files_to_convert = {
                "mhs_hospital_revenue": mhs_hospital_revenue_report_path,
                "maatri_hospital_revenue": maatri_hospital_revenue_report_path,
                "print_hospital_revenue": print_hospital_revenue_report_path,
                "doctor_visit_with_package": doctor_visit_report_with_package_path,
                "doctor_visit_without_package": doctor_visit_report_without_package_path,
                "maatri_doctor_visit_with_package": maatri_doctor_visit_report_with_package_path,
                "maatri_doctor_visit_without_package": maatri_doctor_visit_report_without_package_path,
                "print_inpatient_bill_register": print_inpatient_bill_register_report_path,
                "maatri_print_inpatient_bill_register": maatri_print_inpatient_bill_register_report_path
            }
            converted_files = {}
            for key, path in html_files_to_convert.items():
                base_name = os.path.splitext(os.path.basename(path))[0]
                output_path = os.path.join(tmpdir, f"processed_{base_name}.xlsx")
                convert_html_to_excel(path, output_path)
                converted_files[key] = output_path
                print(f"βœ“ Converted {os.path.basename(path)} to Excel.")

            # Step 2: Process OPD Consultation (if applicable)
            if DOCTOR_CONFIG["services"]["OPD Consultation"]["variable_share"].get(doctor_name, 0.00) != 0.00:
                print("\n[Step 2/7] Processing OPD Consultations...")
                opd_consultations_path = os.path.join(tmpdir, DOCTOR_CONFIG["services"]["OPD Consultation"]["file"])
                results = filter_patient_records(converted_files["mhs_hospital_revenue"], doctor_name)
                results.to_excel(opd_consultations_path, index=False)
                print(f"βœ“ OPD consultations processed and saved.")
            else:
                print("\n[Step 2/7] Skipping OPD Consultations (0.00% variable share).")

            # Step 3: Process Diagnostics & Pathology (if applicable)
            if DOCTOR_CONFIG["services"]["OPD Diagnostics & Pathology"]["variable_share"].get(doctor_name, 0.00) != 0.00:
                print("\n[Step 3/7] Processing OPD Diagnostics & Pathology...")
                diag_path_output_path = os.path.join(tmpdir, DOCTOR_CONFIG["services"]["OPD Diagnostics & Pathology"]["file"])
                results = filter_diag_path_records(converted_files["mhs_hospital_revenue"], doctor_name)
                results.to_excel(diag_path_output_path, index=False)
                print(f"βœ“ Diagnostics & Pathology processed and saved.")
            else:
                print("\n[Step 3/7] Skipping Diagnostics & Pathology (0.00% variable share).")

            # Step 4: Process Daycare Procedure (if applicable)
            if DOCTOR_CONFIG["services"]["Daycare Procedure"]["variable_share"].get(doctor_name, 0.00) != 0.00:
                print("\n[Step 4/7] Processing Daycare Procedure...")
                daycare_output_path = os.path.join(tmpdir, DOCTOR_CONFIG["services"]["Daycare Procedure"]["file"])
                results = filter_daycare_records(converted_files["mhs_hospital_revenue"], doctor_name)
                results.to_excel(daycare_output_path, index=False)
                print(f"βœ“ Daycare Procedure processed and saved.")
            else:
                print("\n[Step 4/7] Skipping Daycare Procedure (0.00% variable share).")

            # Step 5: Process IPD Cross Consultation (if applicable)
            # Combine doctor visit reports for both hospitals first
            print("\n[Step 5/7] Combining and tagging IPD consultations for Cross Consultation...")
            maatri_visit_output = os.path.join(tmpdir, 'final_processed_maatri_doctor_visit_report.xlsx')
            combine_doctor_visit_reports(
                converted_files['maatri_doctor_visit_with_package'],
                converted_files['maatri_doctor_visit_without_package'],
                maatri_visit_output
            )
            mssh_visit_output = os.path.join(tmpdir, 'final_processed_mssh_doctor_visit_report.xlsx')
            combine_doctor_visit_reports(
                converted_files['doctor_visit_with_package'],
                converted_files['doctor_visit_without_package'],
                mssh_visit_output
            )

            if DOCTOR_CONFIG["services"]["IPD Cross Consultation"]["variable_share"].get(doctor_name, 0.00) != 0.00:
                print("\nProcessing IPD Cross Consultation...")
                cross_maatri = get_cross_consultations(
                    maatri_visit_output,
                    converted_files['maatri_print_inpatient_bill_register'],
                    [doctor_name],
                    unit_name='Maatri'
                )
                cross_mssh = get_cross_consultations(
                    mssh_visit_output,
                    converted_files['print_inpatient_bill_register'],
                    [doctor_name],
                    unit_name='MSSH'
                )
                combined_cross = pd.concat([cross_maatri, cross_mssh], ignore_index=True)
                cross_consultation_path = os.path.join(tmpdir, DOCTOR_CONFIG["services"]["IPD Cross Consultation"]["file"])
                combined_cross.to_excel(cross_consultation_path, index=False)
                print(f"βœ“ IPD Cross Consultation processed and saved.")
            else:
                print("\nSkipping IPD Cross Consultation (0.00% variable share).")

            # Step 6: Process Surgical and Medical Management (if applicable)
            run_surg_med_processing = (
                DOCTOR_CONFIG["services"]["Surgery (Package cases)"]["variable_share"].get(doctor_name, 0.00) != 0.00 or
                DOCTOR_CONFIG["services"]["Surgery (Open cases)"]["variable_share"].get(doctor_name, 0.00) != 0.00 or
                DOCTOR_CONFIG["services"]["Medical Management"]["variable_share"].get(doctor_name, 0.00) != 0.00
            )
            if run_surg_med_processing:
                print("\n[Step 6/7] Processing Surgical and Medical Management...")
                surg_med_output_path = os.path.join(tmpdir, DOCTOR_CONFIG["services"]["Surgery (Package cases)"]["file"])

                file_paths_for_combine = [
                    converted_files['print_hospital_revenue'],
                    converted_files['maatri_hospital_revenue']
                ]
                combine_reports(file_paths_for_combine, doctor_name, surg_med_output_path)
                print(f"βœ“ Surgical and Medical Management cases processed and saved.")
            else:
                print("\n[Step 6/7] Skipping Surgical and Medical Management (all 0.00% variable share).")

            # Final Step: Create the combined report
            print("\n--- Generating Final Report ---")

            final_report_name = f"{doctor_name}-{current_month}-{current_year}.xlsx"
            final_report_path = os.path.join(tmpdir, final_report_name)

            create_combined_report(tmpdir, final_report_path, doctor_name, current_month, current_year)

            permanent_output = os.path.join(os.getcwd(), final_report_name)
            shutil.copy(final_report_path, permanent_output)

            print(f"\nβœ“βœ“βœ“ Processing complete! Final report saved to: {permanent_output} βœ“βœ“βœ“")
            return permanent_output

    except Exception as e:
        print(f"❌ An error occurred during processing for {doctor_name}: {str(e)}")
        import traceback
        traceback.print_exc()
        return None

# Example usage of the wrapper function

if __name__ == "__main__":

  final_report_path = generate_mhs_doctor_report(
        doctor_name= "Dr. Amit Kumar",
        mhs_hospital_revenue_report_path= '/content/drive/MyDrive/VarAuto/mhs_print_hospital_revenue_report.php (16).xls',
        maatri_hospital_revenue_report_path= '/content/drive/MyDrive/VarAuto/maatri_print_hospital_revenue_report.php (16).xls',
        print_hospital_revenue_report_path=  '/content/drive/MyDrive/VarAuto/print_hospital_revenue_report.php (11).xls',
        doctor_visit_report_with_package_path= '/content/drive/MyDrive/VarAuto/doctor_visit_report_with_package.xls',
        doctor_visit_report_without_package_path= '/content/drive/MyDrive/VarAuto/doctor_visit_report_without_package.xls',
        maatri_doctor_visit_report_with_package_path= '/content/drive/MyDrive/VarAuto/maatri_doctor_visit_report_with_package.xls',
        maatri_doctor_visit_report_without_package_path= '/content/drive/MyDrive/VarAuto/maatri_doctor_visit_report_without_package.xls',
        print_inpatient_bill_register_report_path= '/content/drive/MyDrive/VarAuto/print_inpatient_bill_register_report.xls',
        maatri_print_inpatient_bill_register_report_path= '/content/drive/MyDrive/VarAuto/maatri_print_inpatient_bill_register_report.xls',
        current_month= "Feb",
        current_year= "2025"
    )

  if final_report_path:
        print(f"Report successfully generated at: {final_report_path}")
  else:
        print("Report generation failed.")