File size: 84,800 Bytes
8304ec0
 
 
07d9303
 
 
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07d9303
8304ec0
07d9303
8304ec0
07d9303
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07d9303
be1d7b8
 
 
 
 
 
07d9303
 
 
 
8304ec0
07d9303
8304ec0
 
07d9303
8304ec0
07d9303
8304ec0
07d9303
 
 
 
 
 
 
 
 
 
 
8304ec0
 
 
 
07d9303
 
 
 
 
 
 
 
 
 
66162e0
07d9303
66162e0
 
 
 
 
 
 
 
07d9303
 
 
be1d7b8
8304ec0
be1d7b8
 
 
 
 
 
 
 
07d9303
 
66162e0
8304ec0
 
66162e0
8304ec0
 
 
 
 
07d9303
8304ec0
 
07d9303
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07d9303
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be1d7b8
 
8304ec0
be1d7b8
 
07d9303
 
 
 
 
 
 
 
 
8304ec0
07d9303
 
 
 
 
 
8304ec0
07d9303
 
 
 
 
8304ec0
 
 
07d9303
8304ec0
 
 
07d9303
8304ec0
 
 
 
 
 
 
 
 
 
 
 
07d9303
8304ec0
 
07d9303
 
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07d9303
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e8f973
 
 
 
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66162e0
 
 
 
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e8f973
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07d9303
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d875c8
 
 
 
 
 
 
 
 
 
 
39c3242
2d875c8
 
07d9303
be1d7b8
 
8304ec0
07d9303
 
 
8304ec0
07d9303
 
8304ec0
07d9303
8304ec0
 
 
07d9303
8304ec0
 
 
07d9303
 
 
8304ec0
 
 
07d9303
8304ec0
 
 
 
 
 
 
 
 
 
 
 
07d9303
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07d9303
8304ec0
07d9303
8304ec0
 
 
 
 
 
 
 
 
 
 
 
07d9303
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
2d875c8
 
 
 
 
 
 
 
 
 
 
66162e0
2d875c8
 
 
 
 
 
07d9303
8304ec0
 
07d9303
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
07d9303
8304ec0
07d9303
8304ec0
07d9303
 
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07d9303
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07d9303
 
8304ec0
07d9303
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07d9303
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d55948
 
 
 
 
 
8304ec0
 
 
0150680
8304ec0
 
 
 
 
 
 
 
 
 
 
bad12de
8304ec0
bad12de
8304ec0
2d875c8
 
 
 
 
 
 
 
66162e0
 
 
 
8304ec0
 
 
 
 
 
 
 
bad12de
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d875c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8304ec0
 
 
 
 
 
 
 
 
2d875c8
 
 
 
 
 
 
8304ec0
 
2d875c8
8304ec0
 
 
2d875c8
 
 
 
 
 
 
 
 
8304ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d55948
 
 
 
 
 
 
 
8304ec0
 
 
 
 
 
 
 
 
 
 
3d55948
 
 
 
 
 
 
8304ec0
 
 
 
 
 
 
 
 
2d875c8
 
 
 
8304ec0
 
66162e0
8304ec0
 
2d875c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8304ec0
 
 
 
2d875c8
8304ec0
 
 
07d9303
 
 
8304ec0
 
 
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
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
import json
import os
import secrets
import hashlib
import hmac
import uuid
import tempfile
from io import BytesIO
from queue import Queue
from threading import Thread

from dotenv import load_dotenv
from flask import (
    Flask,
    Response,
    render_template_string,
    request,
    send_file,
    stream_with_context,
    jsonify,
)
from werkzeug.utils import secure_filename
import razorpay
from pypdf import PdfReader
from openpyxl import load_workbook
import pandas as pd

from services import (
    excel_to_csv_process,
    pdf_delete_pages_process,
    pdf_merge_process,
    pdf_split_process,
    pdf_to_word_process,
    summarize_process,
    pdf_ocr_process,
    bank_statement_process,
)
from statement_parser import BANK_NAMES as STAT_BANK_NAMES
from statement_parser import excel_bytes_from_df
from statement_parser import parse_statement_pdf

load_dotenv()

OCR_PRICE_PER_PAGE_PAISE = 500
PDF_FREE_PAGES = 10
PDF_EXTRA_PAGE_PRICE_PAISE = 200
EXCEL_FREE_ROWS = 500
EXCEL_PRICE_PER_EXTRA_ROW_PAISE = 20
EXCEL_MAX_ROWS = 50000
PENDING_ORDERS = {}
BYPASS_ACCESS_KEY = os.getenv("OCR_BYPASS_KEY", "215836").strip()

PDF_SERVICES = {
    "pdf-ocr": "Searchable PDF OCR",
    "pdf-to-word": "PDF to Word",
    "pdf-split": "PDF Splitter",
    "pdf-merge": "PDF Merger",
    "pdf-delete-pages": "PDF Delete Pages",
    "summarize": "Document Summarizer",
}
EXCEL_SERVICE = "excel-to-csv"


def razorpay_keys():
    key_id = os.getenv("RAZORPAY_KEY_ID", "").strip()
    key_secret = os.getenv("RAZORPAY_KEY_SECRET", "").strip()
    if not key_id or not key_secret:
        raise RuntimeError("Razorpay keys are not configured. Set RAZORPAY_KEY_ID and RAZORPAY_KEY_SECRET.")
    return key_id, key_secret


def verify_razorpay_signature(order_id, payment_id, signature):
    try:
        _, key_secret = razorpay_keys()
    except RuntimeError:
        return False
    message = f"{order_id}|{payment_id}".encode("utf-8")
    expected = hmac.new(key_secret.encode("utf-8"), message, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature or "")


def has_valid_bypass_key():
    access_key = request.form.get("access_key", "").strip()
    return bool(BYPASS_ACCESS_KEY and hmac.compare_digest(access_key, BYPASS_ACCESS_KEY))


def count_pdf_pages(path, password=None):
    reader = PdfReader(path)
    if reader.is_encrypted:
        if password:
            try:
                reader.decrypt(password)
            except Exception:
                raise ValueError("Incorrect password for protected PDF.")
        else:
            raise ValueError("This PDF is password-protected. Please enter the PDF password.")
    return len(reader.pages)


def count_excel_rows(input_path, extension):
    if extension in (".xlsx", ".xlsm"):
        workbook = load_workbook(input_path, read_only=True, data_only=True)
        try:
            sheet = workbook.active
            rows = sum(1 for _ in sheet.iter_rows(values_only=True))
        finally:
            workbook.close()
        return rows
    return len(pd.read_excel(input_path, header=None))


def order_amount_for(service, path=None, pages=None, num_pdfs=None, excel_rows=None, bank_entries=None, password=None):
    if path and pages is None:
        try:
            pages = count_pdf_pages(path, password=password)
        except Exception:
            pages = 0

    if service == "pdf-ocr":
        if pages is None or pages < 1:
            raise ValueError("This PDF does not contain any pages.")
        amount = pages * 200  # 2 Rs per page
        return amount, pages, f"{pages} page{'s' if pages != 1 else ''} x INR 2.00 = INR {amount / 100:.2f}"

    elif service == "pdf-split":
        if pages is None or pages < 1:
            raise ValueError("This PDF does not contain any pages.")
        if pages <= 100:
            amount = 0
            summary = f"{pages} page{'s' if pages != 1 else ''}. Free tier applied (up to 100 pages free)."
        else:
            extra = pages - 100
            if extra < 51:
                amount = 0
                summary = f"{pages} page{'s' if pages != 1 else ''}. Free tier applied (first 100 pages free + {extra} extra page{'s' if extra != 1 else ''} free, as extra is less than 51)."
            else:
                amount = extra * 2  # 2 paise per page
                summary = f"First 100 pages free + {extra} extra page{'s' if extra != 1 else ''} x INR 0.02 = INR {amount / 100:.2f}"
        return amount, pages, summary

    elif service == "pdf-merge":
        if num_pdfs is None:
            raise ValueError("Number of PDFs is required for merge calculation.")
        if num_pdfs <= 10:
            amount = 0
            summary = f"{num_pdfs} PDF{'s' if num_pdfs != 1 else ''}. Free tier applied (up to 10 PDFs free)."
        else:
            extra = num_pdfs - 10
            amount = extra * 2  # 2 paise per PDF
            summary = f"10 PDFs free + {extra} extra PDF{'s' if extra != 1 else ''} x INR 0.02 = INR {amount / 100:.2f}"
        return amount, num_pdfs, summary

    elif service == "pdf-to-word":
        if pages is None or pages < 1:
            raise ValueError("This PDF does not contain any pages.")
        if pages <= 100:
            amount = 0
            summary = f"{pages} page{'s' if pages != 1 else ''}. Free tier applied (up to 100 pages free)."
        else:
            extra = pages - 100
            amount = extra * 2  # 2 paise per page
            summary = f"100 pages free + {extra} extra page{'s' if extra != 1 else ''} x INR 0.02 = INR {amount / 100:.2f}"
        return amount, pages, summary

    elif service == "pdf-delete-pages":
        return 0, pages or 0, "Always free."

    elif service == "summarize":
        # Keep summarize free or default
        return 0, pages or 0, "Always free."

    elif service == "excel-to-csv":
        if excel_rows is None:
            raise ValueError("Excel row count is required.")
        if excel_rows > EXCEL_MAX_ROWS:
            raise ValueError("Excel files above 50,000 rows are not supported.")
        if excel_rows <= 10000:
            amount = 0
            summary = f"{excel_rows} rows. Free tier applied (up to 10,000 entries free)."
        else:
            extra = excel_rows - 10000
            groups = (extra + 9) // 10
            amount = groups * 2  # 2 paise for each 10 entry
            summary = f"10,000 entries free + {extra} extra entries ({groups} groups of 10) x INR 0.02 = INR {amount / 100:.2f}"
        return amount, excel_rows, summary

    elif service.startswith("bank-"):
        if bank_entries is None:
            raise ValueError("Bank entry count is required.")
        amount = bank_entries * 8  # 8 paise per entry
        summary = f"{bank_entries} entries x INR 0.08 = INR {amount / 100:.2f}"
        return amount, bank_entries, summary

    raise ValueError("Unknown paid service.")


def create_order(service, amount, pages_or_rows):
    if amount == 0:
        return "", None
    key_id, key_secret = razorpay_keys()
    client = razorpay.Client(auth=(key_id, key_secret))
    order = client.order.create(
        {
            "amount": amount,
            "currency": "INR",
            "receipt": f"scanly_{uuid.uuid4().hex[:25]}",
            "notes": {
                "service": service,
                "pages_or_rows": str(pages_or_rows),
                "amount": str(amount),
            },
        }
    )
    PENDING_ORDERS[order["id"]] = {
        "amount": amount,
        "pages_or_rows": pages_or_rows,
        "service": service,
        "currency": "INR",
    }
    return key_id, order

app = Flask(__name__)
ROOT = os.path.dirname(__file__)
INDEX_HTML = os.path.join(ROOT, "templatemo_622_clearwave", "index.html")

# ── In-memory task store ──────────────────────────────────────────────────
# task_id → {"queue": Queue, "result": bytes|None, "error": str|None, "fname": str, "mime": str}
_pending: dict[str, dict] = {}


def _run_task(task_id: str, fn, *args, **kwargs):
    entry = _pending[task_id]
    q: Queue = entry["queue"]

    def _progress(pct, msg):
        q.put({"type": "progress", "percent": pct, "message": msg})

    try:
        result = fn(*args, progress_callback=_progress, **kwargs)
        entry["result"] = result if isinstance(result, bytes) else result.read()
        q.put({"type": "done"})
    except Exception as exc:
        entry["error"] = str(exc)
        q.put({"type": "error", "message": str(exc)})


# ── Index ──────────────────────────────────────────────────────────────────

@app.route("/")
def index():
    if not os.path.exists(INDEX_HTML):
        return "SCANLY home page not found.", 404
    with open(INDEX_HTML, "r", encoding="utf-8") as fh:
        return fh.read()


@app.route("/assets/<path:filename>")
def assets(filename):
    from flask import send_from_directory

    return send_from_directory(ROOT, filename)


# ── SSE progress endpoint ─────────────────────────────────────────────────

@app.route("/progress/<task_id>")
def progress_stream(task_id):
    entry = _pending.get(task_id)
    if not entry:
        return Response(
            "data: " + json.dumps({"type": "done"}) + "\n\n",
            mimetype="text/event-stream",
        )

    q = entry["queue"]

    def generate():
        while True:
            msg = q.get()
            yield "data: " + json.dumps(msg) + "\n\n"
            if msg["type"] in ("done", "error"):
                break

    return Response(stream_with_context(generate()), mimetype="text/event-stream")


# ── Multi-purpose service page template ───────────────────────────────────

SERVICE_SHELL = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{{ title }} | SCANLY</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&family=DM+Sans:wght@400;500;700&family=Fredoka:wght@500;600;700;800&display=swap" rel="stylesheet">
<style>
  :root {
    --bg: #0b0f19;
    --card-bg: rgba(20, 28, 48, 0.6);
    --border: rgba(255, 255, 255, 0.08);
    --border-hover: rgba(0, 242, 254, 0.4);
    --text: #f3f4f6;
    --text-muted: #9ca3af;
    --accent: #00f2fe;
    --accent-hover: #4facfe;
    --glow: rgba(0, 242, 254, 0.15);
    --font-body: 'Plus Jakarta Sans', sans-serif;
    --font-title: 'Plus Jakarta Sans', sans-serif;
  }
  
  body.light-theme {
    --bg: #fff9f0;
    --card-bg: #fff;
    --border: rgba(47, 42, 34, 0.12);
    --border-hover: #2f2a22;
    --text: #2f2a22;
    --text-muted: #756d61;
    --accent: #2fd0af;
    --accent-hover: #1e8f77;
    --glow: rgba(47, 42, 34, 0.08);
    --font-body: "DM Sans", sans-serif;
    --font-title: "Fredoka", sans-serif;
    
    background-color: var(--bg);
    background-image: radial-gradient(circle, rgba(47,42,34,0.16) 0.8px, transparent 0.9px);
    background-size: 28px 28px;
  }
  
  * { box-sizing: border-box; transition: transform 0.25s ease, box-shadow 0.25s ease, background 0.25s ease, border-color 0.25s ease, color 0.25s ease; }
  body {
    margin: 0;
    min-height: 100vh;
    font-family: var(--font-body);
    background: var(--bg);
    color: var(--text);
    background-image: radial-gradient(circle at 50% 50%, #1e293b 0%, #0b0f19 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
  }
  
  body.light-theme {
    background-image: radial-gradient(circle, rgba(47,42,34,0.16) 0.8px, transparent 0.9px);
    background-size: 28px 28px;
  }

  .page {
    width: 100%;
    max-width: 600px;
    background: var(--card-bg);
    border: 1px solid var(--border);
    border-radius: 20px;
    padding: 40px;
    backdrop-filter: blur(16px);
    box-shadow: 0 20px 50px rgba(0, 0, 0, 0.4);
    position: relative;
  }
  body.light-theme .page {
    border-radius: 8px;
    border: 2px solid var(--border);
    box-shadow: 0 12px 28px rgba(47, 42, 34, 0.1);
    backdrop-filter: none;
  }
  
  .brand {
    font-weight: 800;
    letter-spacing: .25em;
    color: var(--accent);
    text-transform: uppercase;
    font-size: 0.9rem;
    margin-bottom: 24px;
    font-family: var(--font-title);
  }
  body.light-theme .brand {
    color: var(--text-muted);
  }
  
  h1 {
    margin: 0 0 10px;
    font-size: clamp(1.8rem, 4vw, 2.5rem);
    font-weight: 800;
    background: linear-gradient(to right, #ffffff, #9ca3af);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    font-family: var(--font-title);
  }
  
  body.light-theme h1 {
    margin: 28px 0 8px;
    font-size: clamp(2rem, 4vw, 3.2rem);
    background: none;
    -webkit-background-clip: initial;
    -webkit-text-fill-color: initial;
    color: var(--text);
  }
  
  .sub {
    color: var(--text-muted);
    margin-bottom: 30px;
    font-size: 1rem;
    line-height: 1.6;
  }
  .privacy-badge {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    background: rgba(16, 185, 129, 0.1);
    border: 1px solid rgba(16, 185, 129, 0.2);
    color: #34d399;
    padding: 12px 16px;
    border-radius: 12px;
    font-size: 0.85rem;
    font-weight: 600;
    margin-bottom: 24px;
    width: 100%;
  }
  body.light-theme .privacy-badge {
    background: rgba(16, 185, 129, 0.08);
    border: 2px solid rgba(47, 42, 34, 0.12);
    color: #0f766e;
    border-radius: 8px;
  }
  
  form {
    display: grid;
    gap: 20px;
  }
  body.light-theme form {
    gap: 16px;
    padding: 28px;
    border: 2px solid rgba(47, 42, 34, 0.12);
    border-radius: 8px;
    box-shadow: 0 12px 28px rgba(47, 42, 34, 0.1);
  }
  
  label {
    font-weight: 600;
    font-size: 0.9rem;
    color: var(--text);
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  input[type=file] {
    width: 100%;
    padding: 14px;
    border: 1px dashed var(--border);
    border-radius: 12px;
    background: rgba(255, 255, 255, 0.02);
    color: var(--text-muted);
    cursor: pointer;
  }
  input[type=file]:hover {
    border-color: var(--border-hover);
    background: rgba(0, 242, 254, 0.02);
  }
  
  body.light-theme input[type=file] {
    padding: 12px;
    border: 2px solid rgba(47, 42, 34, 0.14);
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.8);
  }
  
  select, input[type=password], input[type=text], input[type=number] {
    width: 100%;
    padding: 14px;
    border: 1px solid var(--border);
    border-radius: 12px;
    background: rgba(255, 255, 255, 0.04);
    color: var(--text);
    font-size: 1rem;
    font-family: inherit;
    outline: none;
  }
  select:focus, input[type=password]:focus, input[type=text]:focus, input[type=number]:focus {
    border-color: var(--accent);
    box-shadow: 0 0 10px var(--glow);
    background: rgba(255, 255, 255, 0.06);
  }
  
  body.light-theme select, body.light-theme input[type=password], body.light-theme input[type=text], body.light-theme input[type=number] {
    padding: 12px;
    border: 2px solid rgba(47, 42, 34, 0.14);
    border-radius: 8px;
    background: rgba(255, 255, 255, 0.8);
    font-size: 1rem;
  }
  
  button {
    padding: 16px;
    border: none;
    border-radius: 12px;
    background: linear-gradient(135deg, var(--accent), var(--accent-hover));
    color: #0b0f19;
    font-weight: 800;
    cursor: pointer;
    font-size: 1.05rem;
    box-shadow: 0 4px 15px rgba(0, 242, 254, 0.3);
  }
  button:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0, 242, 254, 0.4);
  }
  
  body.light-theme button {
    padding: 14px;
    border: 2px solid var(--border-hover);
    border-radius: 999px;
    background: var(--accent);
    box-shadow: 3px 4px 0 rgba(47, 42, 34, 0.12);
    color: #071915;
    font-weight: 800;
    font-size: 1rem;
  }
  body.light-theme button:hover {
    transform: translateY(-2px);
    box-shadow: 5px 6px 0 rgba(47, 42, 34, 0.12);
  }
  
  #progress-wrap {
    display: none;
    margin-top: 24px;
    background: rgba(255, 255, 255, 0.02);
    padding: 20px;
    border: 1px solid var(--border);
    border-radius: 12px;
  }
  
  body.light-theme #progress-wrap {
    background: #fff;
    padding: 18px;
    border: 2px solid rgba(47, 42, 34, 0.1);
    border-radius: 8px;
  }
  
  .pbar {
    height: 8px;
    background: rgba(255, 255, 255, 0.08);
    border-radius: 999px;
    overflow: hidden;
  }
  
  body.light-theme .pbar {
    height: 12px;
    background: #e8e2d8;
  }
  
  .pfill {
    height: 100%;
    width: 0%;
    background: linear-gradient(to right, var(--accent), var(--accent-hover));
    border-radius: 999px;
  }
  body.light-theme .pfill {
    background: var(--accent);
  }
  
  #pmsg {
    margin-top: 12px;
    color: var(--text-muted);
    font-size: .9rem;
  }
  .back {
    display: inline-flex;
    align-items: center;
    color: var(--text-muted);
    text-decoration: none;
    font-size: 0.9rem;
    margin-bottom: 20px;
    gap: 6px;
  }
  .back:hover {
    color: var(--accent);
  }
  
  body.light-theme .back:hover {
    text-decoration: underline;
    color: var(--text);
  }
  
  .note {
    background: rgba(251, 191, 36, 0.05);
    border: 1px solid rgba(251, 191, 36, 0.2);
    color: #fbbf24;
    padding: 14px;
    border-radius: 12px;
    margin-top: 20px;
    font-size: 0.9rem;
    line-height: 1.5;
  }
  
  body.light-theme .note {
    background: #fff2b8;
    border: 2px solid rgba(47, 42, 34, 0.12);
    border-radius: 8px;
    color: var(--text);
  }

  /* Theme Toggle Button */
  .theme-toggle-btn {
    position: absolute;
    top: 24px;
    right: 24px;
    width: 48px;
    height: 48px;
    border-radius: 12px;
    border: 1px solid var(--border);
    background: var(--card-bg);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    z-index: 100;
  }
  .theme-toggle-btn:hover {
    border-color: var(--accent);
    transform: scale(1.05);
  }
  body.light-theme .theme-toggle-btn {
    border: 2px solid var(--border-hover);
    background: #fff;
    box-shadow: 3px 4px 0 rgba(47,42,34,0.12);
    border-radius: 50%;
  }
  body.light-theme .theme-toggle-btn .sun-icon { display: none; }
  body.light-theme .theme-toggle-btn .moon-icon { display: block; }
  body:not(.light-theme) .theme-toggle-btn .sun-icon { display: block; }
  body:not(.light-theme) .theme-toggle-btn .moon-icon { display: none; }
</style>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
</head>
<body>
<button id="theme-toggle" class="theme-toggle-btn" aria-label="Toggle theme">
  <span class="sun-icon">☀️</span>
  <span class="moon-icon">🌙</span>
</button>

<div class="page">
  <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
    <a class="back" href="/" style="margin-bottom: 0;">&larr; Home</a>
    <a class="back" href="/pricing" style="margin-bottom: 0;">💰 Pricing</a>
  </div>
  <div class="brand">SCANLY</div>
  <h1>{{ title }}</h1>
  <p class="sub">{{ subtitle }}</p>

  <div class="privacy-badge">🔒 We don't save your data. All processing is done in-memory and immediately deleted.</div>

  {% if hint %}
  <div class="note">💡 {{ hint }}</div>
  {% endif %}

  <form id="upload-form" enctype="multipart/form-data">
    <label>
      {{ field_label }}
      <input type="file" name="file"{% if accept %} accept="{{ accept }}"{% endif %} required{% if multiple %} multiple{% endif %}>
    </label>
    {% if select_input %}
    <label>
      {{ select_input.label }}
      <select name="{{ select_input.name }}">
        {% for val, display in select_input.options %}
          <option value="{{ val }}">{{ display }}</option>
        {% endfor %}
      </select>
    </label>
    {% endif %}
    {% if extra_input %}
    <label>
      {{ extra_input.label }}
      <input type="{{ extra_input.type }}" name="{{ extra_input.name }}" placeholder="{{ extra_input.placeholder }}" required>
    </label>
    {% endif %}
    <label>
      PDF Password (Optional, if protected)
      <input type="password" name="pdf_password" autocomplete="off" placeholder="Password (if file is encrypted)">
    </label>
    <label>
      Access Key (Optional)
      <input type="password" name="access_key" autocomplete="off" placeholder="Access key for free processing">
    </label>
    <button type="submit">{{ btn_label }}</button>
  </form>

  <div id="progress-wrap">
    <div class="pbar"><div class="pfill" id="pfill"></div></div>
    <p id="pmsg">Starting…</p>
  </div>
</div>

<script>
// Theme Initialization
const currentTheme = localStorage.getItem('theme') || 'dark';
if (currentTheme === 'light') {
  document.body.classList.add('light-theme');
}
document.getElementById('theme-toggle').addEventListener('click', () => {
  document.body.classList.toggle('light-theme');
  const theme = document.body.classList.contains('light-theme') ? 'light' : 'dark';
  localStorage.setItem('theme', theme);
});

const form = document.getElementById('upload-form');
const pw = document.getElementById('progress-wrap');
const pfill = document.getElementById('pfill');
const pmsg = document.getElementById('pmsg');

form.addEventListener('submit', async (e) => {
  e.preventDefault();
  pw.style.display = 'block';
  pfill.style.width = '0%';
  pmsg.textContent = 'Uploading…';

  const fd = new FormData(form);
  const accessKey = fd.get("access_key");

  if (accessKey && accessKey.trim()) {
    pmsg.textContent = 'Access key provided, bypassing payment check...';
  } else {
    pmsg.textContent = 'Calculating page/row count & cost...';
    fd.append("service", "{{ slug }}");
    try {
      const orderResp = await fetch("/payment/order", {
        method: "POST",
        body: fd
      });
      if (!orderResp.ok) {
        const errText = await orderResp.text();
        pmsg.textContent = '❌ ' + errText;
        return;
      }
      const order = await orderResp.json();
      if (!order.free) {
        pmsg.textContent = `Calculated cost: INR ${order.display_amount}. Opening Razorpay...`;
        const payment = await new Promise((resolve, reject) => {
          const checkout = new Razorpay({
            key: order.key,
            amount: order.amount,
            currency: order.currency,
            name: "SCANLY",
            description: order.description,
            order_id: order.order_id,
            handler: resolve,
            modal: {
              ondismiss: () => reject(new Error("Payment was not completed.")),
            },
            theme: {
              color: document.body.classList.contains('light-theme') ? "#2fd0af" : "#00f2fe",
            },
          });
          checkout.on("payment.failed", (response) => {
            reject(new Error(response.error ? response.error.description : "Payment failed."));
          });
          checkout.open();
        });

        fd.append("razorpay_payment_id", payment.razorpay_payment_id);
        fd.append("razorpay_order_id", payment.razorpay_order_id);
        fd.append("razorpay_signature", payment.razorpay_signature);
      }
    } catch (err) {
      pmsg.textContent = '❌ ' + err.message;
      return;
    }
  }

  pmsg.textContent = 'Starting service task...';
  const resp = await fetch('{{ action }}', { method:'POST', body:fd });
  if (!resp.ok) {
    pmsg.textContent = 'Error: ' + (await resp.text());
    return;
  }

  const taskId = resp.headers.get('X-Task-Id');
  if (!taskId) {
    const blob = await resp.blob();
    const disp = resp.headers.get('Content-Disposition') || '';
    const m = disp.match(/filename="?(.+?)"?$/);
    const fname = m ? m[1] : 'download';
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = fname;
    a.click();
    pw.style.display = 'none';
    return;
  }

  let startTime = Date.now();
  const evt = new EventSource('/progress/' + taskId);
  evt.onmessage = (ev) => {
    const d = JSON.parse(ev.data);
    if (d.type === 'progress') {
      pfill.style.width = Math.min(d.percent, 100) + '%';
      let elapsed = (Date.now() - startTime) / 1000;
      let timeRemainingStr = "";
      if (d.percent > 5 && d.percent < 100) {
        let totalEstimatedTime = (elapsed / d.percent) * 100;
        let remaining = totalEstimatedTime - elapsed;
        if (remaining > 0) {
          let mins = Math.floor(remaining / 60);
          let secs = Math.ceil(remaining % 60);
          timeRemainingStr = ` (Estimated time remaining: ${mins > 0 ? mins + 'm ' : ''}${secs}s)`;
        }
      }
      pmsg.textContent = d.message + timeRemainingStr;
    } else if (d.type === 'done') {
      pfill.style.width = '100%';
      pmsg.textContent = 'Downloading…';
      evt.close();
      fetch('/download/' + taskId).then(r => {
        const disp = r.headers.get('Content-Disposition') || '';
        const m = disp.match(/filename="?(.+?)"?$/);
        const fname = m ? m[1] : 'result';
        return r.blob().then(blob => ({ blob, fname }));
      }).then(({ blob, fname }) => {
        const a = document.createElement('a');
        a.href = URL.createObjectURL(blob);
        a.download = fname;
        a.click();
        pw.style.display = 'none';
      });
    } else if (d.type === 'error') {
      pmsg.textContent = '❌ ' + d.message;
      pw.style.display = 'none';
      evt.close();
    }
  };
});
</script>
</body>
</html>"""


PRICING_TEMPLATE = r"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Pricing Plans | SCANLY</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&family=DM+Sans:wght@400;500;700&family=Fredoka:wght@500;600;700;800&display=swap" rel="stylesheet">
<style>
  :root {
    --bg: #0b0f19;
    --card-bg: rgba(20, 28, 48, 0.6);
    --border: rgba(255, 255, 255, 0.08);
    --border-hover: rgba(0, 242, 254, 0.4);
    --text: #f3f4f6;
    --text-muted: #9ca3af;
    --accent: #00f2fe;
    --accent-hover: #4facfe;
    --glow: rgba(0, 242, 254, 0.15);
    --font-body: 'Plus Jakarta Sans', sans-serif;
    --font-title: 'Plus Jakarta Sans', sans-serif;
    --shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  }
  
  body.light-theme {
    --bg: #fff9f0;
    --card-bg: #fff;
    --border: rgba(47, 42, 34, 0.12);
    --border-hover: #2f2a22;
    --text: #2f2a22;
    --text-muted: #756d61;
    --accent: #2fd0af;
    --accent-hover: #1e8f77;
    --glow: rgba(47, 42, 34, 0.08);
    --font-body: "DM Sans", sans-serif;
    --font-title: "Fredoka", sans-serif;
    --shadow: 0 24px 48px rgba(47, 42, 34, 0.16);
  }
  
  * { box-sizing: border-box; transition: transform 0.25s ease, box-shadow 0.25s ease, background 0.25s ease, border-color 0.25s ease, color 0.25s ease; }
  body {
    margin: 0;
    min-height: 100vh;
    font-family: var(--font-body);
    background: var(--bg);
    color: var(--text);
    background-image: radial-gradient(circle at 50% 50%, #1e293b 0%, #0b0f19 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
  }
  
  body.light-theme {
    background-image: radial-gradient(circle, rgba(47,42,34,0.16) 0.8px, transparent 0.9px);
    background-size: 28px 28px;
  }

  .container {
    width: 100%;
    max-width: 1000px;
    margin: 0 auto;
    position: relative;
  }
  
  .back-link {
    display: inline-flex;
    align-items: center;
    color: var(--text-muted);
    text-decoration: none;
    font-size: 0.95rem;
    margin-bottom: 24px;
    gap: 8px;
    font-weight: 600;
  }
  .back-link:hover {
    color: var(--accent);
  }
  
  body.light-theme .back-link:hover {
    text-decoration: underline;
    color: var(--text);
  }
  
  header {
    text-align: center;
    margin-bottom: 48px;
  }

  .brand {
    font-weight: 800;
    letter-spacing: .25em;
    color: var(--accent);
    text-transform: uppercase;
    font-size: 0.9rem;
    margin-bottom: 16px;
    font-family: var(--font-title);
  }
  body.light-theme .brand {
    color: var(--text-muted);
  }
  
  h1 {
    margin: 0 0 12px;
    font-size: clamp(2rem, 5vw, 3.2rem);
    font-weight: 800;
    background: linear-gradient(to right, #ffffff, #9ca3af);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    font-family: var(--font-title);
  }
  
  body.light-theme h1 {
    background: none;
    -webkit-background-clip: initial;
    -webkit-text-fill-color: initial;
    color: var(--text);
  }
  
  .subtitle {
    color: var(--text-muted);
    font-size: 1.1rem;
    max-width: 600px;
    margin: 0 auto;
    line-height: 1.6;
  }

  .section-title {
    font-size: 1.6rem;
    font-weight: 800;
    margin: 40px 0 20px;
    color: var(--accent);
    font-family: var(--font-title);
    display: flex;
    align-items: center;
    gap: 10px;
  }
  body.light-theme .section-title {
    color: var(--text);
  }

  .grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 24px;
    margin-bottom: 40px;
  }

  .card {
    background: var(--card-bg);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 30px;
    backdrop-filter: blur(16px);
    box-shadow: var(--shadow);
    display: flex;
    flex-direction: column;
    position: relative;
    overflow: hidden;
  }
  .card:hover {
    border-color: var(--border-hover);
    box-shadow: 0 15px 35px var(--glow);
    transform: translateY(-5px);
  }
  
  body.light-theme .card {
    border-radius: 6px;
    border: 2px solid var(--border);
    box-shadow: 0 12px 28px rgba(47, 42, 34, 0.08);
    backdrop-filter: none;
  }
  body.light-theme .card:nth-child(even) { background: #fff2b8; }
  body.light-theme .card:nth-child(odd) { background: #d8f3e7; }
  body.light-theme .card:hover {
    transform: translateY(-5px) rotate(0.5deg);
    box-shadow: 0 20px 40px rgba(47, 42, 34, 0.15);
  }

  .card-badge {
    position: absolute;
    top: 16px;
    right: 16px;
    background: rgba(16, 185, 129, 0.15);
    border: 1px solid rgba(16, 185, 129, 0.3);
    color: #34d399;
    padding: 6px 12px;
    border-radius: 8px;
    font-size: 0.75rem;
    font-weight: 700;
    text-transform: uppercase;
  }
  body.light-theme .card-badge {
    background: #fff;
    border: 2px solid var(--border-hover);
    color: #0f766e;
    border-radius: 4px;
  }

  .card h3 {
    margin: 0 0 10px;
    font-size: 1.4rem;
    font-weight: 700;
    color: #ffffff;
  }
  body.light-theme .card h3 {
    color: var(--text);
  }

  .price {
    font-size: 2.2rem;
    font-weight: 800;
    color: var(--accent);
    margin: 16px 0;
    display: flex;
    align-items: baseline;
    gap: 4px;
    font-family: var(--font-title);
  }
  body.light-theme .price {
    color: var(--text);
  }
  .price span {
    font-size: 0.95rem;
    color: var(--text-muted);
    font-weight: 500;
  }

  .card p {
    color: var(--text-muted);
    font-size: 0.95rem;
    line-height: 1.6;
    margin: 0 0 20px;
    flex-grow: 1;
  }
  body.light-theme .card p {
    color: var(--text-muted);
  }

  .features-list {
    list-style: none;
    padding: 0;
    margin: 0;
    display: grid;
    gap: 12px;
  }
  .features-list li {
    font-size: 0.9rem;
    display: flex;
    align-items: center;
    gap: 8px;
    color: var(--text);
  }
  .features-list li::before {
    content: "✓";
    color: #10b981;
    font-weight: 800;
  }
  body.light-theme .features-list li::before {
    color: #0f766e;
  }

  /* Theme Toggle Button */
  .theme-toggle-btn {
    position: absolute;
    top: 0px;
    right: 0px;
    width: 48px;
    height: 48px;
    border-radius: 12px;
    border: 1px solid var(--border);
    background: var(--card-bg);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
    box-shadow: var(--shadow);
    z-index: 100;
  }
  .theme-toggle-btn:hover {
    border-color: var(--accent);
    transform: scale(1.05);
  }
  body.light-theme .theme-toggle-btn {
    border: 2px solid var(--border-hover);
    background: #fff;
    box-shadow: 3px 4px 0 rgba(47,42,34,0.12);
    border-radius: 50%;
  }
  body.light-theme .theme-toggle-btn .sun-icon { display: none; }
  body.light-theme .theme-toggle-btn .moon-icon { display: block; }
  body:not(.light-theme) .theme-toggle-btn .sun-icon { display: block; }
  body:not(.light-theme) .theme-toggle-btn .moon-icon { display: none; }

  @media (max-width: 600px) {
    .grid { grid-template-columns: 1fr; }
    .theme-toggle-btn { top: -20px; right: 0; }
  }
</style>
</head>
<body>
  <div class="container">
    <button id="theme-toggle" class="theme-toggle-btn" aria-label="Toggle theme">
      <span class="sun-icon">☀️</span>
      <span class="moon-icon">🌙</span>
    </button>

    <a class="back-link" href="/">&larr; Back to Dashboard</a>
    
    <header>
      <div class="brand">SCANLY</div>
      <h1>Simple & Transparent Pricing</h1>
      <p class="subtitle">No subscriptions, no hidden fees. Generous free tiers on almost all services, and pay-as-you-go rates when you scale.</p>
    </header>

    <h2 class="section-title">🎁 What's Free for You</h2>
    <div class="grid">
      <div class="card">
        <div class="card-badge">Free Tier</div>
        <h3>Delete Pages</h3>
        <div class="price">₹0.00</div>
        <p>Permanently remove selected pages (e.g. `1,3-5`) from your PDF documents.</p>
        <ul class="features-list">
          <li>100% Free always</li>
          <li>Unlimited files and pages</li>
          <li>In-memory local secure processing</li>
        </ul>
      </div>

      <div class="card">
        <div class="card-badge">100 Pages Free</div>
        <h3>PDF Splitter</h3>
        <div class="price">₹0.00<span>/ up to 100 pages</span></div>
        <p>Extract single pages or split a PDF into range groups inside a downloadable ZIP.</p>
        <ul class="features-list">
          <li>First 100 pages are completely free</li>
          <li>Next 50 pages are also free</li>
          <li>Only pays if extra pages exceed 50</li>
        </ul>
      </div>

      <div class="card">
        <div class="card-badge">100 Pages Free</div>
        <h3>PDF to Word</h3>
        <div class="price">₹0.00<span>/ up to 100 pages</span></div>
        <p>Convert PDF text layout into an editable Microsoft Word document.</p>
        <ul class="features-list">
          <li>First 100 pages are completely free</li>
          <li>Extracts all text structure</li>
          <li>Download as editable .docx</li>
        </ul>
      </div>

      <div class="card">
        <div class="card-badge">10 PDFs Free</div>
        <h3>PDF Merger</h3>
        <div class="price">₹0.00<span>/ up to 10 PDFs</span></div>
        <p>Combine multiple PDF files into a single master document.</p>
        <ul class="features-list">
          <li>First 10 PDFs merged are free</li>
          <li>Keep your pages in ordered structure</li>
        </ul>
      </div>

      <div class="card">
        <div class="card-badge">10,000 Rows Free</div>
        <h3>Excel → CSV</h3>
        <div class="price">₹0.00<span>/ up to 10k entries</span></div>
        <p>Instantly convert large Excel spreadsheets into clean flat CSV files.</p>
        <ul class="features-list">
          <li>First 10,000 entries (rows) are free</li>
          <li>Highly optimized conversion speed</li>
        </ul>
      </div>

      <div class="card">
        <div class="card-badge">Always Free</div>
        <h3>Summarizer</h3>
        <div class="price">₹0.00</div>
        <p>Generate clean bullet-point document summaries using AI.</p>
        <ul class="features-list">
          <li>AI-powered summaries</li>
          <li>Outputs formatted DOCX files</li>
        </ul>
      </div>
    </div>

    <h2 class="section-title">⚡ Pay As You Go (Beyond Free limits)</h2>
    <div class="grid">
      <div class="card">
        <div class="card-badge">Paid Service</div>
        <h3>Searchable PDF OCR</h3>
        <div class="price">₹2.00<span>/ page</span></div>
        <p>Run advanced ocrmypdf engines to overlay selectable text layers on scanned PDFs.</p>
        <ul class="features-list">
          <li>Accurate deskew and rotation</li>
          <li>Runs local OCR models</li>
          <li>Make any image PDF selectable</li>
        </ul>
      </div>

      <div class="card">
        <div class="card-badge">Paid Service</div>
        <h3>Bank Statement Parser</h3>
        <div class="price">₹0.08<span>/ entry</span></div>
        <p>Extract structured transactions from Axis, SBI, ICICI, Kotak, HDFC, and other PDF statements into Excel.</p>
        <ul class="features-list">
          <li>Select specific pages to parse</li>
          <li>Pay only for extracted entries</li>
          <li>Highly accurate rule-based extraction</li>
        </ul>
      </div>

      <div class="card">
        <div class="card-badge">Paid Service</div>
        <h3>Split PDF Extra</h3>
        <div class="price">₹0.02<span>/ extra page</span></div>
        <p>When splitting extremely large PDFs containing more than 150 pages.</p>
        <ul class="features-list">
          <li>Applies only from page 151+</li>
          <li>₹0.02 per additional page</li>
        </ul>
      </div>

      <div class="card">
        <div class="card-badge">Paid Service</div>
        <h3>Merge PDF Extra</h3>
        <div class="price">₹0.02<span>/ extra PDF</span></div>
        <p>When merging large batches containing more than 10 documents.</p>
        <ul class="features-list">
          <li>Applies only from 11th PDF+</li>
          <li>₹0.02 per additional file</li>
        </ul>
      </div>

      <div class="card">
        <div class="card-badge">Paid Service</div>
        <h3>PDF to Word Extra</h3>
        <div class="price">₹0.02<span>/ extra page</span></div>
        <p>When converting large PDFs containing more than 100 pages.</p>
        <ul class="features-list">
          <li>Applies only from page 101+</li>
          <li>₹0.02 per additional page</li>
        </ul>
      </div>

      <div class="card">
        <div class="card-badge">Paid Service</div>
        <h3>Excel → CSV Extra</h3>
        <div class="price">₹0.02<span>/ 10 extra entries</span></div>
        <p>When converting spreadsheets containing more than 10,000 entries (rows).</p>
        <ul class="features-list">
          <li>Applies only from row 10,001+</li>
          <li>₹0.02 per group of 10 extra rows</li>
        </ul>
      </div>
    </div>
  </div>

  <script>
    // Theme Initialization
    const toggleBtn = document.getElementById('theme-toggle');
    const currentTheme = localStorage.getItem('theme') || 'dark';
    if (currentTheme === 'light') {
      document.body.classList.add('light-theme');
    }
    toggleBtn.addEventListener('click', () => {
      document.body.classList.toggle('light-theme');
      const theme = document.body.classList.contains('light-theme') ? 'light' : 'dark';
      localStorage.setItem('theme', theme);
    });
  </script>
</body>
</html>
"""


@app.route("/pricing")
def pricing_page():
    return render_template_string(PRICING_TEMPLATE)


# ── Service definitions ───────────────────────────────────────────────────

SERVICE_ROUTES = {
    "pdf-ocr": {
        "title": "Searchable PDF OCR",
        "subtitle": "Convert scanned PDF documents into searchable PDFs with selectable text overlay.",
        "field_label": "Choose a scanned PDF",
        "accept": ".pdf",
        "btn_label": "Run OCR",
        "hint": "This service runs ocrmypdf locally to create a searchable text layer. Rate: INR 5.00 per PDF page.",
        "select_input": {
            "name": "mode",
            "label": "OCR Mode",
            "options": [
                ("fast", "Fast OCR - skip pages that already have text"),
                ("accurate", "High accuracy - slower full OCR")
            ]
        }
    },
    "pdf-split": {
        "title": "PDF Splitter",
        "subtitle": "Split a PDF into individual pages or groups of pages.",
        "field_label": "Choose a PDF",
        "accept": ".pdf",
        "btn_label": "Split PDF",
        "extra_input": {"name": "split_size", "type": "number", "placeholder": "Group size (e.g. 5, default: 1)", "label": "Pages per split group"},
        "hint": "Default splits into individual pages. Enter a group size (e.g., 5) to split into groups of pages.",
    },
    "pdf-merge": {
        "title": "PDF Merger",
        "subtitle": "Upload multiple PDFs and merge them into a single document.",
        "field_label": "Choose PDF files",
        "accept": ".pdf",
        "btn_label": "Merge PDFs",
        "multiple": True,
        "hint": "Select two or more PDFs. Order them correctly before uploading.",
    },
    "pdf-to-word": {
        "title": "PDF to Word",
        "subtitle": "Convert a PDF document into an editable Word (.docx) file.",
        "field_label": "Choose a PDF",
        "accept": ".pdf",
        "btn_label": "Convert to Word",
        "hint": "Extracts selectable text from PDF pages and writes as a nicely formatted Word document.",
    },
    "pdf-delete-pages": {
        "title": "PDF Delete Pages",
        "subtitle": "Remove specific pages from a PDF and download the cleaned version.",
        "field_label": "Choose a PDF",
        "accept": ".pdf",
        "btn_label": "Delete Pages",
        "extra_input": {"name": "pages", "type": "text", "placeholder": "Pages to delete, e.g. 1,3-5,7", "label": "Page numbers to remove"},
        "hint": "Specify pages like '1,3-5,7' to remove. The PDF must have at least one page remaining.",
    },
    "excel-to-csv": {
        "title": "Excel → CSV Converter",
        "subtitle": "Convert XLSX or XLS files to clean CSV format.",
        "field_label": "Choose a spreadsheet",
        "accept": ".xlsx,.xls,.csv",
        "btn_label": "Convert to CSV",
        "hint": "Supports .xlsx, .xls. Already-CSV files pass through.",
    },
    "summarize": {
        "title": "Document Summarizer",
        "subtitle": "Upload a PDF, DOCX, or TXT file and get a bullet-point summary as a DOCX.",
        "field_label": "Choose a document",
        "accept": ".pdf,.docx,.txt",
        "btn_label": "Summarize",
        "hint": "Output is a clean bullet-point DOCX file.",
    },
}

for slug, info in SERVICE_ROUTES.items():
    action_url = f"/api/{slug}"

    def _make_route(_slug, _info, _action):
        @app.route(f"/service/{_slug}", methods=["GET"], endpoint=f"service_{_slug}")
        def service_page():
            return render_template_string(SERVICE_SHELL, **_info, action=_action, slug=_slug)

    _make_route(slug, info, action_url)


# ── API endpoints ─────────────────────────────────────────────────────────

def verify_payment_before_processing(service, request_files_field="file"):
    if has_valid_bypass_key():
        return None

    amount = 0
    pages_or_rows = 0

    if service in PDF_SERVICES:
        if service == "pdf-merge":
            files = request.files.getlist(request_files_field)
            num_pdfs = len([f for f in files if f and f.filename])
            amount, pages_or_rows, _ = order_amount_for(service, num_pdfs=num_pdfs)
        else:
            f = request.files.get(request_files_field)
            if not f or not f.filename:
                return "No file uploaded", 400
            
            temp = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
            temp.write(f.read())
            temp.close()
            f.seek(0)
            try:
                pages = count_pdf_pages(temp.name)
                amount, pages_or_rows, _ = order_amount_for(service, pages=pages)
            finally:
                try:
                    os.remove(temp.name)
                except OSError:
                    pass
    elif service == EXCEL_SERVICE:
        f = request.files.get(request_files_field)
        if not f or not f.filename:
            return "No file uploaded", 400
        ext = os.path.splitext(secure_filename(f.filename))[1].lower()
        temp = tempfile.NamedTemporaryFile(suffix=ext, delete=False)
        temp.write(f.read())
        temp.close()
        f.seek(0)
        try:
            rows = count_excel_rows(temp.name, ext)
            amount, pages_or_rows, _ = order_amount_for(service, excel_rows=rows)
        finally:
            try:
                os.remove(temp.name)
            except OSError:
                pass
    elif service.startswith("bank-"):
        bank_slug = service.split("bank-")[1]
        uploads = request.files.getlist(request_files_field)
        valid_files = [up for up in uploads if up and up.filename and up.filename.lower().endswith(".pdf") and not os.path.basename(up.filename).startswith(".")]
        if not valid_files:
            return "No PDF file uploaded", 400

        total_entries = 0
        page_numbers = request.form.get("pages", "").strip()
        pdf_password = request.form.get("pdf_password", "").strip()
        for up in valid_files:
            pdf_bytes = up.read()
            up.seek(0)
            df = parse_statement_pdf(pdf_bytes, bank_slug=bank_slug, page_numbers=page_numbers, password=pdf_password)
            total_entries += len(df)
        amount, pages_or_rows, _ = order_amount_for(service, bank_entries=total_entries)

    if amount == 0:
        return None

    order_id = request.form.get("razorpay_order_id", "")
    payment_id = request.form.get("razorpay_payment_id", "")
    signature = request.form.get("razorpay_signature", "")
    
    order = PENDING_ORDERS.get(order_id)
    if not order_id or not payment_id or not signature:
        return "Complete the Razorpay payment before processing.", 402
    if not order:
        return "Payment order expired or invalid. Please pay again.", 402
    if order["service"] != service or order["amount"] != amount or order["pages_or_rows"] != pages_or_rows:
        return "Uploaded file page/row count does not match the payment. Please calculate payment again.", 400
    if not verify_razorpay_signature(order_id, payment_id, signature):
        return "Payment signature verification failed.", 402
    
    PENDING_ORDERS.pop(order_id, None)
    return None


@app.route("/payment/order", methods=["POST"])
def create_payment_order():
    service = request.form.get("service", "").strip()
    try:
        if has_valid_bypass_key():
            return jsonify({
                "key": "",
                "order_id": "",
                "amount": 0,
                "currency": "INR",
                "pages_or_rows": 0,
                "display_amount": "0.00",
                "summary": "Bypass key validated.",
                "description": "Bypass access key entered.",
                "free": True
            })

        if service in PDF_SERVICES:
            if service == "pdf-merge":
                files = request.files.getlist("file")
                if not files or len(files) < 2:
                    return jsonify({"error": "Upload at least 2 PDF files"}), 400
                num_pdfs = len([f for f in files if f and f.filename])
                amount, pages_or_rows, summary = order_amount_for(service, num_pdfs=num_pdfs)
            else:
                uploaded = request.files.get("file")
                if not uploaded or uploaded.filename == "":
                    return jsonify({"error": "Please upload a PDF file"}), 400
                filename = secure_filename(uploaded.filename)
                
                ext = os.path.splitext(filename)[1].lower()
                if ext != ".pdf":
                    return jsonify({"error": "Only PDFs are supported for this service"}), 400
                
                temp = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
                temp.close()
                uploaded.save(temp.name)
                try:
                    amount, pages_or_rows, summary = order_amount_for(service, path=temp.name)
                finally:
                    try:
                        os.remove(temp.name)
                    except OSError:
                        pass

            description = PDF_SERVICES[service]

        elif service == EXCEL_SERVICE:
            uploaded = request.files.get("file")
            if not uploaded or uploaded.filename == "":
                return jsonify({"error": "Please upload an Excel file"}), 400
            filename = secure_filename(uploaded.filename)
            ext = os.path.splitext(filename)[1].lower()
            if ext not in (".xlsx", ".xls", ".xlsm"):
                return jsonify({"error": "Please upload a valid Excel file"}), 400
            
            temp = tempfile.NamedTemporaryFile(suffix=ext, delete=False)
            temp.close()
            uploaded.save(temp.name)
            try:
                rows = count_excel_rows(temp.name, ext)
                amount, pages_or_rows, summary = order_amount_for(service, excel_rows=rows)
            finally:
                try:
                    os.remove(temp.name)
                except OSError:
                    pass
            description = "Excel to CSV"

        elif service.startswith("bank-"):
            bank_slug = service.split("bank-")[1]
            if bank_slug not in STAT_BANK_NAMES:
                return jsonify({"error": "Unknown bank service"}), 400
            uploads = request.files.getlist("file")
            valid_files = [up for up in uploads if up and up.filename and up.filename.lower().endswith(".pdf") and not os.path.basename(up.filename).startswith(".")]
            if not valid_files:
                return jsonify({"error": "Please upload one or more PDF statements"}), 400

            total_entries = 0
            page_numbers = request.form.get("pages", "").strip()
            pdf_password = request.form.get("pdf_password", "").strip()
            for up in valid_files:
                pdf_bytes = up.read()
                up.seek(0)
                df = parse_statement_pdf(pdf_bytes, bank_slug=bank_slug, page_numbers=page_numbers, password=pdf_password)
                total_entries += len(df)
            amount, pages_or_rows, summary = order_amount_for(service, bank_entries=total_entries)
            if len(valid_files) == 1:
                description = f"{STAT_BANK_NAMES[bank_slug]} Statement Parsing"
            else:
                description = f"{STAT_BANK_NAMES[bank_slug]} Batch Parsing ({len(valid_files)} statements)"

        else:
            return jsonify({"error": "Unknown service."}), 400

        key_id, order = create_order(service, amount, pages_or_rows)
        order_id = order["id"] if order else ""
        return jsonify({
            "key": key_id,
            "order_id": order_id,
            "amount": amount,
            "currency": "INR",
            "pages_or_rows": pages_or_rows,
            "display_amount": f"{amount / 100:.2f}",
            "summary": summary,
            "description": description,
            "free": amount == 0,
        })
    except ValueError as exc:
        return jsonify({"error": str(exc)}), 400
    except Exception as exc:
        return jsonify({"error": f"Could not create payment order: {exc}"}), 500


def _start_task(task_id: str, fn, *, fname: str, mime: str, **kw):
    entry = {
        "queue": Queue(),
        "result": None,
        "error": None,
        "fname": fname,
        "mime": mime,
    }
    _pending[task_id] = entry
    t = Thread(target=_run_task, args=(task_id, fn), kwargs=kw, daemon=True)
    t.start()


@app.route("/api/pdf-ocr", methods=["POST"])
def api_pdf_ocr():
    payment_err = verify_payment_before_processing("pdf-ocr")
    if payment_err:
        return payment_err
    f = request.files.get("file")
    if not f or not f.filename:
        return "No file uploaded", 400
    data = f.read()
    filename = secure_filename(f.filename) or "scan.pdf"
    mode = request.form.get("mode", "fast")
    task_id = secrets.token_hex(8)
    base = os.path.splitext(filename)[0]

    def process(**kw):
        return pdf_ocr_process(data, filename, mode, **kw)

    _start_task(task_id, process, fname=f"{base}_ocr.pdf", mime="application/pdf")
    return _accepted(task_id)


@app.route("/api/pdf-split", methods=["POST"])
def api_pdf_split():
    payment_err = verify_payment_before_processing("pdf-split")
    if payment_err:
        return payment_err
    f = request.files.get("file")
    if not f or not f.filename:
        return "No file uploaded", 400

    split_size_str = request.form.get("split_size", "1").strip()
    try:
        split_size = int(split_size_str) if split_size_str else 1
        if split_size < 1:
            split_size = 1
    except ValueError:
        split_size = 1

    data = f.read()
    task_id = secrets.token_hex(8)
    base = os.path.splitext(secure_filename(f.filename))[0]

    _start_task(task_id, pdf_split_process, fname=f"{base}_pages.zip", mime="application/zip", file_bytes=data, split_size=split_size)
    return _accepted(task_id)


@app.route("/api/pdf-merge", methods=["POST"])
def api_pdf_merge():
    payment_err = verify_payment_before_processing("pdf-merge")
    if payment_err:
        return payment_err
    files = request.files.getlist("file")
    if len(files) < 2:
        return "Upload at least 2 PDF files", 400
    task_id = secrets.token_hex(8)
    files_data = [(secure_filename(f.filename) or "doc.pdf", f.read()) for f in files]

    _start_task(task_id, pdf_merge_process, fname="merged.pdf", mime="application/pdf", files_data=files_data)
    return _accepted(task_id)


@app.route("/api/excel-to-csv", methods=["POST"])
def api_excel_to_csv():
    payment_err = verify_payment_before_processing(EXCEL_SERVICE)
    if payment_err:
        return payment_err
    f = request.files.get("file")
    if not f or not f.filename:
        return "No file uploaded", 400
    data = f.read()
    filename = secure_filename(f.filename) or "sheet.xlsx"
    task_id = secrets.token_hex(8)
    base = os.path.splitext(filename)[0]

    def process(**kw):
        return excel_to_csv_process(data, filename, **kw)

    _start_task(task_id, process, fname=f"{base}.csv", mime="text/csv")
    return _accepted(task_id)


@app.route("/api/summarize", methods=["POST"])
def api_summarize():
    payment_err = verify_payment_before_processing("summarize")
    if payment_err:
        return payment_err
    f = request.files.get("file")
    if not f or not f.filename:
        return "No file uploaded", 400
    data = f.read()
    filename = secure_filename(f.filename) or "doc.pdf"
    task_id = secrets.token_hex(8)
    base = os.path.splitext(filename)[0]

    def process(**kw):
        return summarize_process(data, filename, **kw)

    _start_task(
        task_id,
        process,
        fname=f"{base}_summary.docx",
        mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    )
    return _accepted(task_id)


@app.route("/api/pdf-to-word", methods=["POST"])
def api_pdf_to_word():
    payment_err = verify_payment_before_processing("pdf-to-word")
    if payment_err:
        return payment_err
    f = request.files.get("file")
    if not f or not f.filename:
        return "No file uploaded", 400
    data = f.read()
    filename = secure_filename(f.filename) or "doc.pdf"
    task_id = secrets.token_hex(8)
    base = os.path.splitext(filename)[0]

    def process(**kw):
        return pdf_to_word_process(data, filename, **kw)

    _start_task(
        task_id,
        process,
        fname=f"{base}.docx",
        mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    )
    return _accepted(task_id)


@app.route("/api/pdf-delete-pages", methods=["POST"])
def api_pdf_delete_pages():
    payment_err = verify_payment_before_processing("pdf-delete-pages")
    if payment_err:
        return payment_err
    f = request.files.get("file")
    if not f or not f.filename:
        return "No file uploaded", 400
    pages_to_delete = request.form.get("pages", "").strip()
    if not pages_to_delete:
        return "Please specify pages to delete (e.g., '1,3-5,7')", 400
    data = f.read()
    filename = secure_filename(f.filename) or "doc.pdf"
    task_id = secrets.token_hex(8)
    base = os.path.splitext(filename)[0]

    def process(**kw):
        return pdf_delete_pages_process(data, pages_to_delete, **kw)

    _start_task(
        task_id,
        process,
        fname=f"{base}_cleaned.pdf",
        mime="application/pdf",
    )
    return _accepted(task_id)


def _accepted(task_id: str):
    resp = Response(status=202)
    resp.headers["X-Task-Id"] = task_id
    return resp


@app.route("/download/<task_id>")
def download_result(task_id):
    entry = _pending.pop(task_id, None)
    if entry is None:
        return "Task not found", 404
    if entry["error"]:
        return entry["error"], 400
    if entry["result"] is None:
        return "Result not ready", 202

    return send_file(
        BytesIO(entry["result"]),
        mimetype=entry["mime"],
        as_attachment=True,
        download_name=entry["fname"],
    )


# ── Bank statements ───────────────────────────────────────────────────────

BANK_STATEMENT_TEMPLATE = """<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bank Statement Parser | SCANLY</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&family=DM+Sans:wght@400;500;700&family=Fredoka:wght@500;600;700;800&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg: #0b0f19;
      --card-bg: rgba(20, 28, 48, 0.6);
      --border: rgba(255, 255, 255, 0.08);
      --border-hover: rgba(0, 242, 254, 0.4);
      --text: #f3f4f6;
      --text-muted: #9ca3af;
      --accent: #00f2fe;
      --accent-hover: #4facfe;
      --glow: rgba(0, 242, 254, 0.15);
      --shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
      --font-body: 'Plus Jakarta Sans', sans-serif;
      --font-title: 'Plus Jakarta Sans', sans-serif;
    }
    
    body.light-theme {
      --bg: #fff9f0;
      --card-bg: #fff;
      --border: rgba(47, 42, 34, 0.12);
      --border-hover: #2f2a22;
      --text: #2f2a22;
      --text-muted: #756d61;
      --accent: #2fd0af;
      --accent-hover: #1e8f77;
      --glow: rgba(47, 42, 34, 0.08);
      --shadow: 0 24px 48px rgba(47, 42, 34, 0.16);
      --font-body: "DM Sans", sans-serif;
      --font-title: "Fredoka", sans-serif;
    }
    
    * { box-sizing: border-box; transition: transform 0.25s ease, box-shadow 0.25s ease, background 0.25s ease, border-color 0.25s ease, color 0.25s ease; }
    body {
      margin: 0;
      min-height: 100vh;
      font-family: var(--font-body);
      background: var(--bg);
      color: var(--text);
      background-image: radial-gradient(circle at 50% 50%, #1e293b 0%, #0b0f19 100%);
    }
    
    body.light-theme {
      background-image: radial-gradient(circle, rgba(47,42,34,0.16) 0.8px, transparent 0.9px);
      background-size: 28px 28px;
    }
    
    a { color: inherit; text-decoration: none; }
    .page { max-width: 1200px; margin: 0 auto; padding: 40px 20px 80px; position: relative; }
    .topbar { display: flex; align-items: center; justify-content: space-between; gap: 16px; margin-bottom: 40px; }
    .brand { font-weight: 800; letter-spacing: 0.3em; text-transform: uppercase; color: var(--accent); font-size: 1.1rem; font-family: var(--font-title); }
    body.light-theme .brand { color: var(--text-muted); }
    .button-row { display: flex; gap: 12px; }
    .button-row a {
      display: inline-flex;
      align-items: center;
      padding: 10px 20px;
      border-radius: 10px;
      border: 1px solid var(--border);
      background: rgba(255, 255, 255, 0.02);
      font-weight: 700;
      font-size: 0.9rem;
    }
    .button-row a:hover {
      border-color: var(--accent);
      background: rgba(0, 242, 254, 0.05);
      color: var(--accent);
    }
    
    body.light-theme .button-row a {
      padding: 11px 16px;
      border-radius: 999px;
      border: 2px solid var(--border-hover);
      background: #fff2b8;
      font-weight: 800;
      box-shadow: 3px 4px 0 rgba(47,42,34,0.12);
    }
    body.light-theme .button-row a:hover {
      transform: translateY(-2px) rotate(-1deg);
      background: #d8f3e7;
    }
    
    .eyebrow {
      text-transform: uppercase;
      letter-spacing: 0.18em;
      color: var(--accent);
      font-size: 0.8rem;
      font-weight: 800;
      margin-bottom: 12px;
    }
    
    body.light-theme .eyebrow {
      margin-top: 34px;
      color: var(--text-muted);
      font-size: 0.82rem;
    }
    
    h1 {
      max-width: 820px;
      margin: 0 0 16px;
      font-size: clamp(2rem, 5vw, 3rem);
      line-height: 1.1;
      font-weight: 800;
      background: linear-gradient(to right, #ffffff, #9ca3af);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      font-family: var(--font-title);
    }
    
    body.light-theme h1 {
      margin: 16px 0 12px;
      font-size: clamp(2.4rem, 5vw, 4.4rem);
      line-height: 1.02;
      background: none;
      -webkit-background-clip: initial;
      -webkit-text-fill-color: initial;
      color: var(--text);
    }
    
    .lead { max-width: 760px; color: var(--text-muted); line-height: 1.8; margin-bottom: 24px; font-size: 1.05rem; }
    .privacy-badge {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      background: rgba(16, 185, 129, 0.1);
      border: 1px solid rgba(16, 185, 129, 0.2);
      color: #34d399;
      padding: 12px 16px;
      border-radius: 12px;
      font-size: 0.9rem;
      font-weight: 600;
      margin-bottom: 40px;
      max-width: 600px;
    }
    body.light-theme .privacy-badge {
      background: rgba(16, 185, 129, 0.08);
      border: 2px solid rgba(47, 42, 34, 0.12);
      color: #0f766e;
      border-radius: 8px;
    }
    
    .bank-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 24px;
    }
    
    body.light-theme .bank-grid {
      gap: 20px;
    }
    
    .bank-card {
      background: var(--card-bg);
      border: 1px solid var(--border);
      border-radius: 16px;
      padding: 28px;
      backdrop-filter: blur(16px);
      display: flex;
      flex-direction: column;
      gap: 16px;
      box-shadow: var(--shadow);
    }
    .bank-card:hover {
      border-color: var(--border-hover);
      box-shadow: 0 15px 35px var(--glow);
      transform: translateY(-4px);
    }
    
    body.light-theme .bank-card {
      position: relative;
      min-height: 230px;
      padding: 24px;
      border-radius: 6px;
      border: 2px solid rgba(47, 42, 34, 0.16);
      background: #fff;
      box-shadow: 0 20px 42px rgba(47, 42, 34, 0.14);
      transform: rotate(-0.8deg);
      backdrop-filter: none;
    }
    body.light-theme .bank-card:nth-child(even) { background: #d8f3e7; transform: rotate(1deg); }
    body.light-theme .bank-card:nth-child(3n) { background: #fff2b8; transform: rotate(-1.2deg); }
    body.light-theme .bank-card::before { content: ""; position: absolute; top: -8px; left: 22px; width: 64px; height: 20px; background: linear-gradient(135deg, rgba(135,206,235,0.64), rgba(135,206,235,0.24)); transform: rotate(-7deg); z-index: 2; }
    body.light-theme .bank-card:hover { transform: rotate(0deg) translateY(-7px) translateZ(18px); box-shadow: 0 28px 60px rgba(47, 42, 34, 0.2); }

    .bank-code {
      width: 48px;
      height: 48px;
      display: grid;
      place-items: center;
      border-radius: 10px;
      background: rgba(0, 242, 254, 0.1);
      color: var(--accent);
      border: 1px solid rgba(0, 242, 254, 0.2);
      font-weight: 800;
      font-size: 0.95rem;
    }
    
    body.light-theme .bank-code {
      width: 50px;
      height: 50px;
      border-radius: 12px;
      background: #fff;
      border: 2px solid rgba(47, 42, 34, 0.12);
      color: var(--text);
      font-weight: 900;
    }
    
    .bank-card h2 { margin: 0; font-size: 1.2rem; font-weight: 700; color: #ffffff; }
    body.light-theme .bank-card h2 { color: var(--text); font-size: 1.1rem; }
    .bank-card p { margin: 0; color: var(--text-muted); line-height: 1.5; font-size: 0.9rem; }
    .message {
      margin-bottom: 24px;
      padding: 14px 18px;
      border-radius: 12px;
      background: rgba(239, 68, 68, 0.1);
      border: 1px solid rgba(239, 68, 68, 0.2);
      color: #f87171;
      font-size: 0.95rem;
    }
    body.light-theme .message {
      background: #fff;
      border: 2px solid rgba(47,42,34,0.16);
      color: var(--text);
    }
    form { display: grid; gap: 14px; margin-top: auto; }
    input[type=file] {
      width: 100%;
      padding: 10px;
      border-radius: 8px;
      border: 1px dashed var(--border);
      background: rgba(255, 255, 255, 0.02);
      color: var(--text-muted);
      font-size: 0.85rem;
      cursor: pointer;
    }
    input[type=file]:hover {
      border-color: var(--border-hover);
    }
    
    body.light-theme input[type=file] {
      border: 2px solid rgba(47, 42, 34, 0.14);
      background: rgba(255, 255, 255, 0.78);
      color: var(--text);
    }
    
    button {
      padding: 12px;
      border: none;
      border-radius: 8px;
      background: linear-gradient(135deg, var(--accent), var(--accent-hover));
      color: #0b0f19;
      font-weight: 700;
      cursor: pointer;
      font-size: 0.95rem;
    }
    button:hover {
      box-shadow: 0 4px 15px rgba(0, 242, 254, 0.3);
      transform: translateY(-1px);
    }
    
    body.light-theme button {
      border-radius: 999px;
      border: 2px solid var(--border-hover);
      background: var(--accent);
      color: #071915;
      font-weight: 900;
      box-shadow: 3px 4px 0 rgba(47,42,34,0.12);
    }
    body.light-theme button:hover {
      transform: translateY(-1px);
      box-shadow: 4px 5px 0 rgba(47,42,34,0.12);
    }
    
    .footer { margin-top: 50px; color: var(--text-muted); text-align: center; font-size: 0.9rem; }
    
    /* Theme Toggle Button */
    .theme-toggle-btn {
      position: absolute;
      top: 24px;
      right: 24px;
      width: 48px;
      height: 48px;
      border-radius: 12px;
      border: 1px solid var(--border);
      background: var(--card-bg);
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 1.25rem;
      box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
      z-index: 100;
    }
    .theme-toggle-btn:hover {
      border-color: var(--accent);
      transform: scale(1.05);
    }
    body.light-theme .theme-toggle-btn {
      border: 2px solid var(--border-hover);
      background: #fff;
      box-shadow: 3px 4px 0 rgba(47,42,34,0.12);
      border-radius: 50%;
    }
    body.light-theme .theme-toggle-btn .sun-icon { display: none; }
    body.light-theme .theme-toggle-btn .moon-icon { display: block; }
    body:not(.light-theme) .theme-toggle-btn .sun-icon { display: block; }
    body:not(.light-theme) .theme-toggle-btn .moon-icon { display: none; }

    @media (max-width: 900px) {
      .bank-grid { grid-template-columns: 1fr; }
      body.light-theme .bank-card { transform: rotate(0deg) !important; }
    }
    
    #progress-wrap {
      display: none;
      margin-bottom: 30px;
      background: var(--card-bg);
      padding: 24px;
      border: 1px solid var(--border);
      border-radius: 16px;
    }
    body.light-theme #progress-wrap {
      background: #fff;
      padding: 18px;
      border: 2px solid rgba(47, 42, 34, 0.1);
      border-radius: 8px;
    }
    .pbar {
      height: 8px;
      background: rgba(255, 255, 255, 0.08);
      border-radius: 999px;
      overflow: hidden;
    }
    body.light-theme .pbar {
      height: 12px;
      background: #e8e2d8;
    }
    .pfill {
      height: 100%;
      width: 0%;
      background: linear-gradient(to right, var(--accent), var(--accent-hover));
      border-radius: 999px;
      transition: width 0.4s ease;
    }
    body.light-theme .pfill {
      background: var(--accent);
    }
    #pmsg {
      margin-top: 12px;
      color: var(--text-muted);
      font-size: .95rem;
      font-weight: 500;
    }
  </style>
  <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
</head>
<body>
  <button id="theme-toggle" class="theme-toggle-btn" aria-label="Toggle theme">
    <span class="sun-icon">☀️</span>
    <span class="moon-icon">🌙</span>
  </button>

  <div class="page">
    <div class="topbar">
      <div class="brand">SCANLY</div>
      <div class="button-row">
        <a href="/">Home</a>
        <a href="/pricing">Pricing</a>
        <a href="/#services">Services</a>
        <button onclick="clearCache()" style="padding: 6px 12px; border-radius: 8px; border: 1px solid var(--border); background: rgba(239,68,68,0.15); color: #f87171; cursor: pointer; font-weight: 600;">🧹 Reset Cache</button>
      </div>
    </div>
    <div class="eyebrow">Bank Parsers</div>
    <h1>Select the bank and upload the statement PDF.</h1>
    <p class="lead">Each sub-card runs its own parser. Supported options include Axis, SBI, ICICI, Kotak, HDFC, IDFC, IndusInd, Union Bank, PNB, IDBI, Credit Card Parser, and Other Bank (AI Parser).</p>
    
    <div class="privacy-badge">🔒 We don't save your data. All processing is done in-memory and immediately deleted.</div>

    <div id="progress-wrap">
      <div class="pbar"><div class="pfill" id="pfill"></div></div>
      <p id="pmsg">Starting…</p>
    </div>
    
    <div class="bank-grid">
      {% for slug, name in banks.items() %}
        <section class="bank-card">
          <div class="bank-code">{% if slug == 'other' %}🤖 AI{% elif slug == 'creditcard' %}💳 CC{% elif slug == 'amex' %}💳 AMEX{% else %}{{ slug[:3].upper() }}{% endif %}</div>
          <h2>{{ name }}</h2>
          <p>{% if slug == 'other' %}Upload any bank PDF statement. Uses AI API parsing directly with zero hardcoded heuristics.{% elif slug == 'amex' %}Upload American Express (Amex) Credit Card PDF statement. Extracts Spends (Debits), Payments/Credits, Membership Fees, and Installments with running balances.{% elif slug == 'creditcard' %}Upload any Credit Card PDF statement (SBI Card, HDFC, ICICI, Axis, Amex, RBL). Parses Spends (Dr) and Refunds/Payments (Cr) into Excel.{% else %}Upload this bank's PDF statement and download parsed transactions as Excel.{% endif %}</p>
          <form class="bank-upload-form" data-bank="{{ slug }}">
            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 6px; font-size: 0.8rem;">
              <label style="cursor: pointer; display: inline-flex; align-items: center; gap: 4px; color: var(--text-muted); user-select: none;">
                <input type="checkbox" class="folder-mode-checkbox" style="cursor: pointer; accent-color: var(--primary, #00f2fe);">
                📁 Folder Upload
              </label>
              <span class="file-count-badge" style="font-size: 0.78rem; font-weight: 600; color: #10b981; display: none;"></span>
            </div>
            <input type="file" name="file" accept=".pdf,application/pdf" multiple required style="width: 100%;">
            <label style="display: flex; flex-direction: column; gap: 4px; font-size: 0.85rem; margin-top: 8px; text-align: left;">
              PDF Password (if protected)
              <input type="password" name="pdf_password" placeholder="Password (if protected)" autocomplete="off" style="padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: rgba(255,255,255,0.02); color: var(--text);">
            </label>
            <label style="display: flex; flex-direction: column; gap: 4px; font-size: 0.85rem; margin-top: 8px; text-align: left;">
              Pages to Parse (e.g. 1, 3-5; leave blank for all)
              <input type="text" name="pages" placeholder="e.g. 1,3-5" style="padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: rgba(255,255,255,0.02); color: var(--text);">
            </label>
            <label style="display: flex; flex-direction: column; gap: 4px; font-size: 0.85rem; margin-top: 8px; text-align: left;">
              Access Key (Optional)
              <input type="password" name="access_key" autocomplete="off" placeholder="Access key for free processing" style="padding: 8px; border-radius: 6px; border: 1px solid var(--border); background: rgba(255,255,255,0.02); color: var(--text);">
            </label>
            <button type="submit" style="margin-top: 10px; width: 100%;">{% if slug == 'other' %}Parse with AI{% elif slug == 'amex' %}Parse AMEX{% elif slug == 'creditcard' %}Parse Credit Card{% else %}Parse {{ slug.upper() }}{% endif %}</button>
          </form>
        </section>
      {% endfor %}
    </div>
    <p class="footer">Choose the matching bank card for best extraction accuracy.</p>
  </div>

  <script>
    // Theme Initialization
    const toggleBtn = document.getElementById('theme-toggle');
    const currentTheme = localStorage.getItem('theme') || 'dark';
    if (currentTheme === 'light') {
      document.body.classList.add('light-theme');
    }
    toggleBtn.addEventListener('click', () => {
      document.body.classList.toggle('light-theme');
      const theme = document.body.classList.contains('light-theme') ? 'light' : 'dark';
      localStorage.setItem('theme', theme);
    });

    // Folder Upload & Multi-PDF toggle logic
    document.querySelectorAll('.bank-upload-form').forEach(form => {
      const chk = form.querySelector('.folder-mode-checkbox');
      const fileInput = form.querySelector('input[type="file"]');
      const badge = form.querySelector('.file-count-badge');
      if (chk && fileInput) {
        chk.addEventListener('change', () => {
          if (chk.checked) {
            fileInput.setAttribute('webkitdirectory', '');
            fileInput.setAttribute('directory', '');
            fileInput.removeAttribute('multiple');
          } else {
            fileInput.removeAttribute('webkitdirectory');
            fileInput.removeAttribute('directory');
            fileInput.setAttribute('multiple', '');
          }
          fileInput.value = '';
          if (badge) { badge.style.display = 'none'; }
        });

        fileInput.addEventListener('change', () => {
          const validPdfs = Array.from(fileInput.files).filter(f => f.name.toLowerCase().endsWith('.pdf') && !f.name.startsWith('.'));
          if (badge) {
            if (validPdfs.length > 1) {
              badge.textContent = `📁 ${validPdfs.length} PDFs`;
              badge.style.display = 'inline';
            } else if (validPdfs.length === 1) {
              badge.textContent = `📄 1 PDF`;
              badge.style.display = 'inline';
            } else {
              badge.style.display = 'none';
            }
          }
        });
      }
    });

    const forms = document.querySelectorAll('.bank-upload-form');
    const pw = document.getElementById('progress-wrap');
    const pfill = document.getElementById('pfill');
    const pmsg = document.getElementById('pmsg');

    forms.forEach(form => {
      form.addEventListener('submit', async (e) => {
        e.preventDefault();
        const bankSlug = form.getAttribute('data-bank');
        const fileInput = form.querySelector('input[type="file"]');
        const validPdfs = Array.from(fileInput.files).filter(f => f.name.toLowerCase().endsWith('.pdf') && !f.name.startsWith('.'));
        if (validPdfs.length === 0) {
          alert('Please select at least one valid PDF statement file.');
          return;
        }

        pw.style.display = 'block';
        pfill.style.width = '0%';
        pmsg.textContent = `Uploading ${validPdfs.length > 1 ? validPdfs.length + ' statement files…' : 'statement…'}`;

        pw.scrollIntoView({ behavior: 'smooth' });

        const fd = new FormData();
        for (const file of validPdfs) {
          fd.append('file', file, file.name);
        }
        for (const [key, val] of new FormData(form).entries()) {
          if (key !== 'file') {
            fd.append(key, val);
          }
        }
        const accessKey = fd.get("access_key");

        if (accessKey && accessKey.trim()) {
          pmsg.textContent = 'Access key provided, bypassing payment check...';
        } else {
          pmsg.textContent = 'Counting transactions & cost...';
          fd.append("service", "bank-" + bankSlug);
          try {
            const orderResp = await fetch("/payment/order", {
              method: "POST",
              body: fd
            });
            if (!orderResp.ok) {
              const errText = await orderResp.text();
              let parsedErr;
              try {
                parsedErr = JSON.parse(errText).error;
              } catch(e) {
                parsedErr = errText;
              }
              pmsg.textContent = '❌ ' + parsedErr;
              return;
            }
            const order = await orderResp.json();
            if (!order.free) {
              pmsg.textContent = `Calculated cost: INR ${order.display_amount}. Opening Razorpay...`;
              const payment = await new Promise((resolve, reject) => {
                const checkout = new Razorpay({
                  key: order.key,
                  amount: order.amount,
                  currency: order.currency,
                  name: "SCANLY",
                  description: order.description,
                  order_id: order.order_id,
                  handler: resolve,
                  modal: {
                    ondismiss: () => reject(new Error("Payment was not completed.")),
                  },
                  theme: {
                    color: document.body.classList.contains('light-theme') ? "#2fd0af" : "#00f2fe",
                  },
                });
                checkout.on("payment.failed", (response) => {
                  reject(new Error(response.error ? response.error.description : "Payment failed."));
                });
                checkout.open();
              });

              fd.append("razorpay_payment_id", payment.razorpay_payment_id);
              fd.append("razorpay_order_id", payment.razorpay_order_id);
              fd.append("razorpay_signature", payment.razorpay_signature);
            }
          } catch (err) {
            pmsg.textContent = '❌ ' + err.message;
            return;
          }
        }

        pmsg.textContent = 'Starting parsing task...';
        const actionUrl = `/api/bank-statements/${bankSlug}`;
        const resp = await fetch(actionUrl, { method:'POST', body:fd });
        if (!resp.ok) {
          pmsg.textContent = 'Error: ' + (await resp.text());
          return;
        }

        const taskId = resp.headers.get('X-Task-Id');
        if (!taskId) {
          pmsg.textContent = '❌ No task ID returned.';
          return;
        }

        let startTime = Date.now();
        const evt = new EventSource('/progress/' + taskId);
        evt.onmessage = (ev) => {
          const d = JSON.parse(ev.data);
          if (d.type === 'progress') {
            pfill.style.width = Math.min(d.percent, 100) + '%';
            let elapsed = (Date.now() - startTime) / 1000;
            let timeRemainingStr = "";
            if (d.percent > 5 && d.percent < 100) {
              let totalEstimatedTime = (elapsed / d.percent) * 100;
              let remaining = totalEstimatedTime - elapsed;
              if (remaining > 0) {
                let mins = Math.floor(remaining / 60);
                let secs = Math.ceil(remaining % 60);
                timeRemainingStr = ` (Estimated time remaining: ${mins > 0 ? mins + 'm ' : ''}${secs}s)`;
              }
            }
            pmsg.textContent = d.message + timeRemainingStr;
          } else if (d.type === 'done') {
            pfill.style.width = '100%';
            pmsg.textContent = 'Downloading…';
            evt.close();
            fetch('/download/' + taskId).then(r => {
              const disp = r.headers.get('Content-Disposition') || '';
              const m = disp.match(/filename="?(.+?)"?$/);
              const fname = m ? m[1] : 'result.xlsx';
              return r.blob().then(blob => ({ blob, fname }));
            }).then(({ blob, fname }) => {
              const a = document.createElement('a');
              a.href = URL.createObjectURL(blob);
              a.download = fname;
              a.click();
              pmsg.textContent = '✅ Download complete!';
              pfill.style.width = '100%';
            });
          } else if (d.type === 'error') {
            pmsg.textContent = '❌ ' + d.message;
            evt.close();
          }
        };
      });
    });

    async function clearCache() {
      if (confirm("Reset all learned parser memory and disk caches?")) {
        const res = await fetch("/api/clear-cache", { method: "POST" });
        const data = await res.json();
        alert("Parser cache cleared successfully! You can upload fresh files now.");
      }
    }
  </script>
</body>
</html>
"""


@app.route("/bank-statements", methods=["GET"])
def bank_statements():
    return render_template_string(BANK_STATEMENT_TEMPLATE, banks=STAT_BANK_NAMES, message=None)


@app.route("/api/clear-cache", methods=["GET", "POST"])
def api_clear_cache():
    from statement_parser import clear_all_caches
    clear_all_caches()
    return jsonify({"status": "success", "message": "All statement parser caches cleared!"})


@app.route("/api/bank-statements/<bank_slug>", methods=["POST"])
def api_bank_statement_parser(bank_slug):
    if bank_slug not in STAT_BANK_NAMES:
        return "Unknown bank", 404

    payment_err = verify_payment_before_processing(f"bank-{bank_slug}")
    if payment_err:
        return payment_err

    uploads = request.files.getlist("file")
    valid_files = [up for up in uploads if up and up.filename and up.filename.lower().endswith(".pdf") and not os.path.basename(up.filename).startswith(".")]
    if not valid_files:
        return "No PDF files uploaded", 400

    page_numbers = request.form.get("pages", "").strip()
    pdf_password = request.form.get("pdf_password", "").strip()
    task_id = secrets.token_hex(8)

    if len(valid_files) == 1:
        upload = valid_files[0]
        data = upload.read()
        base_name = os.path.splitext(secure_filename(os.path.basename(upload.filename)))[0] or bank_slug

        def process(**kw):
            return bank_statement_process(data, bank_slug, page_numbers, password=pdf_password, **kw)

        out_fname = f"{base_name}_{bank_slug}_parsed.xlsx"
    else:
        valid_files.sort(key=lambda f: os.path.basename(f.filename).lower())
        file_inputs = [(os.path.basename(f.filename), f.read()) for f in valid_files]

        def process(**kw):
            return bank_statement_process(file_inputs, bank_slug, page_numbers, password=pdf_password, **kw)

        out_fname = f"{bank_slug}_batch_{len(valid_files)}_statements_parsed.xlsx"

    _start_task(
        task_id,
        process,
        fname=out_fname,
        mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    )
    return _accepted(task_id)


if __name__ == "__main__":
    host = os.getenv("HOST", "0.0.0.0")
    port = int(os.getenv("PORT", 7860))
    app.run(host=host, port=port, debug=False)