File size: 66,256 Bytes
0e7db6c
 
 
efc3d5f
6eaa6df
 
 
cd3a7a4
 
0e7db6c
efc3d5f
970b435
0e7db6c
958c1f2
efc3d5f
 
 
 
0e7db6c
efc3d5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e7db6c
3fb8ded
 
 
6eaa6df
3fb8ded
 
6eaa6df
3fb8ded
 
6eaa6df
3fb8ded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eaa6df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3fb8ded
6eaa6df
 
3fb8ded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efc3d5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
970b435
3fb8ded
970b435
3fb8ded
0e7db6c
970b435
 
 
3fb8ded
970b435
 
 
 
 
 
 
 
 
 
3fb8ded
0e7db6c
efc3d5f
 
 
0e7db6c
3fb8ded
 
efc3d5f
 
 
 
 
 
 
 
 
 
 
0e7db6c
3fb8ded
 
0e7db6c
970b435
 
 
0e7db6c
 
3fb8ded
0e7db6c
3fb8ded
 
 
0e7db6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
970b435
 
 
0e7db6c
970b435
 
 
 
 
 
 
 
 
3fb8ded
0e7db6c
970b435
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e7db6c
 
3fb8ded
970b435
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efc3d5f
958c1f2
3fb8ded
970b435
 
3fb8ded
970b435
 
 
 
 
 
 
 
 
 
 
 
 
 
3fb8ded
 
970b435
0e7db6c
 
 
970b435
958c1f2
970b435
 
0e7db6c
 
 
970b435
0e7db6c
 
efc3d5f
970b435
efc3d5f
970b435
 
 
0e7db6c
 
 
 
970b435
 
 
 
0e7db6c
3fb8ded
 
0e7db6c
 
958c1f2
 
970b435
958c1f2
0e7db6c
970b435
 
0e7db6c
970b435
efc3d5f
 
 
970b435
 
 
 
 
0e7db6c
970b435
 
 
 
0e7db6c
970b435
0e7db6c
 
3fb8ded
970b435
958c1f2
970b435
efc3d5f
 
958c1f2
efc3d5f
 
 
 
970b435
958c1f2
0e7db6c
3fb8ded
970b435
 
 
efc3d5f
 
 
 
970b435
efc3d5f
 
970b435
958c1f2
efc3d5f
 
 
970b435
 
 
 
 
3fb8ded
958c1f2
 
 
 
efc3d5f
 
 
958c1f2
3fb8ded
958c1f2
 
 
 
 
 
 
 
3fb8ded
958c1f2
 
 
 
 
 
 
3fb8ded
 
6eaa6df
 
 
 
3fb8ded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6eaa6df
 
 
 
 
 
 
 
 
056cedc
 
 
 
6eaa6df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e7db6c
421f744
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efc3d5f
6eaa6df
970b435
 
efc3d5f
0e7db6c
 
970b435
efc3d5f
4e78303
970b435
efc3d5f
 
 
3fb8ded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efc3d5f
 
 
 
 
 
421f744
 
efc3d5f
 
 
421f744
958c1f2
efc3d5f
 
421f744
958c1f2
efc3d5f
 
421f744
958c1f2
efc3d5f
 
421f744
958c1f2
efc3d5f
 
421f744
958c1f2
efc3d5f
 
 
421f744
efc3d5f
 
 
421f744
efc3d5f
 
 
421f744
efc3d5f
 
 
421f744
 
efc3d5f
 
 
421f744
efc3d5f
 
 
970b435
efc3d5f
958c1f2
970b435
c9443fe
efc3d5f
c9443fe
efc3d5f
970b435
 
efc3d5f
 
 
6eaa6df
 
 
 
 
efc3d5f
421f744
 
 
 
 
 
 
 
 
 
 
 
 
efc3d5f
 
 
 
970b435
3fb8ded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
970b435
 
efc3d5f
970b435
6eaa6df
0e7db6c
970b435
 
3fb8ded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
421f744
 
 
 
 
970b435
0e7db6c
 
970b435
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
import pandas as pd
import numpy as np
import gradio as gr
import os
import io
import tempfile
import time
import pytz
from datetime import datetime

# Path to the CSV file
CSV_FILE_PATH = "./dados/input.csv"

# --- Helper functions (create_8_band_inputs, create_2_band_inputs) remain the same ---
def create_8_band_inputs(prefix, defaults_lim, defaults_aliq):
    inputs = []
    labels_lim = [f"{prefix} Limite {i+1} (UFM)" for i in range(7)]
    labels_aliq = [f"{prefix} Alíquota {i+1} (ex: 0.004 para 0.4%)" for i in range(8)]
    
    with gr.Row():
        inputs.append(gr.Number(label=labels_lim[0], value=defaults_lim[0], min_width=50))
        inputs.append(gr.Number(label=labels_aliq[0], value=defaults_aliq[0], min_width=50))
    with gr.Row():
        inputs.append(gr.Number(label=labels_lim[1], value=defaults_lim[1], min_width=50))
        inputs.append(gr.Number(label=labels_aliq[1], value=defaults_aliq[1], min_width=50))
    with gr.Row():
        inputs.append(gr.Number(label=labels_lim[2], value=defaults_lim[2], min_width=50))
        inputs.append(gr.Number(label=labels_aliq[2], value=defaults_aliq[2], min_width=50))
    with gr.Row():
        inputs.append(gr.Number(label=labels_lim[3], value=defaults_lim[3], min_width=50))
        inputs.append(gr.Number(label=labels_aliq[3], value=defaults_aliq[3], min_width=50))
    with gr.Row():
        inputs.append(gr.Number(label=labels_lim[4], value=defaults_lim[4], min_width=50))
        inputs.append(gr.Number(label=labels_aliq[4], value=defaults_aliq[4], min_width=50))
    with gr.Row():
        inputs.append(gr.Number(label=labels_lim[5], value=defaults_lim[5], min_width=50))
        inputs.append(gr.Number(label=labels_aliq[5], value=defaults_aliq[5], min_width=50))
    with gr.Row():
        inputs.append(gr.Number(label=labels_lim[6], value=defaults_lim[6], min_width=50))
        inputs.append(gr.Number(label=labels_aliq[6], value=defaults_aliq[6], min_width=50))
    with gr.Row():
        inputs.append(gr.Number(label=labels_aliq[7], value=defaults_aliq[7], min_width=50)) # Only aliquot for the last band
    return inputs

def create_2_band_inputs(prefix, default_lim, defaults_aliq):
    inputs = []
    with gr.Row():
        inputs.append(gr.Number(label=f"{prefix} Limite 1 (UFM)", value=default_lim, min_width=50))
        inputs.append(gr.Number(label=f"{prefix} Alíquota 1 (ex: 0.0)", value=defaults_aliq[0], min_width=50))
    with gr.Row():
        inputs.append(gr.Number(label=f"{prefix} Alíquota 2 (ex: 0.03)", value=defaults_aliq[1], min_width=50))
    return inputs

# --- Function to create parameters sheet ---
def create_parameters_sheet(valor_venal_choice, ufm_value, diferencia_estacionamentos_flag, diferencia_predios_flag, all_parameters):
    """Create a DataFrame with all parameters used in the calculation"""
    
    # Extract parameters from the list in the correct order
    params = all_parameters
    
    # Parameter mapping
    param_data = []
    
    # General parameters
    param_data.append(['CONFIGURAÇÕES GERAIS', '', ''])
    param_data.append(['Valor Venal Utilizado', valor_venal_choice, ''])
    param_data.append(['Valor da UFM', ufm_value, ''])
    param_data.append(['Diferenciar Estacionamentos por Uso', 'Sim' if diferencia_estacionamentos_flag else 'Não', ''])
    param_data.append(['Diferenciar Prédios por Uso', 'Sim' if diferencia_predios_flag else 'Não', ''])
    param_data.append(['', '', ''])
    
    # Predial Geral (PG) - 15 parameters
    param_data.append(['PREDIAL GERAL (PG)', '', ''])
    pg_params = params[0:15]
    param_data.extend([
        ['PG Limite 1 (UFM)', pg_params[0], ''],
        ['PG Alíquota 1', pg_params[1], f'{pg_params[1]*100:.3f}%' if pg_params[1] else ''],
        ['PG Limite 2 (UFM)', pg_params[2], ''],
        ['PG Alíquota 2', pg_params[3], f'{pg_params[3]*100:.3f}%' if pg_params[3] else ''],
        ['PG Limite 3 (UFM)', pg_params[4], ''],
        ['PG Alíquota 3', pg_params[5], f'{pg_params[5]*100:.3f}%' if pg_params[5] else ''],
        ['PG Limite 4 (UFM)', pg_params[6], ''],
        ['PG Alíquota 4', pg_params[7], f'{pg_params[7]*100:.3f}%' if pg_params[7] else ''],
        ['PG Limite 5 (UFM)', pg_params[8], ''],
        ['PG Alíquota 5', pg_params[9], f'{pg_params[9]*100:.3f}%' if pg_params[9] else ''],
        ['PG Limite 6 (UFM)', pg_params[10], ''],
        ['PG Alíquota 6', pg_params[11], f'{pg_params[11]*100:.3f}%' if pg_params[11] else ''],
        ['PG Limite 7 (UFM)', pg_params[12], ''],
        ['PG Alíquota 7', pg_params[13], f'{pg_params[13]*100:.3f}%' if pg_params[13] else ''],
        ['PG Alíquota 8', pg_params[14], f'{pg_params[14]*100:.3f}%' if pg_params[14] else ''],
        ['', '', '']
    ])
    
    # Predial Residencial (PR) - 15 parameters
    param_data.append(['PREDIAL RESIDENCIAL (PR)', '', ''])
    pr_params = params[15:30]
    param_data.extend([
        ['PR Limite 1 (UFM)', pr_params[0], ''],
        ['PR Alíquota 1', pr_params[1], f'{pr_params[1]*100:.3f}%' if pr_params[1] else ''],
        ['PR Limite 2 (UFM)', pr_params[2], ''],
        ['PR Alíquota 2', pr_params[3], f'{pr_params[3]*100:.3f}%' if pr_params[3] else ''],
        ['PR Limite 3 (UFM)', pr_params[4], ''],
        ['PR Alíquota 3', pr_params[5], f'{pr_params[5]*100:.3f}%' if pr_params[5] else ''],
        ['PR Limite 4 (UFM)', pr_params[6], ''],
        ['PR Alíquota 4', pr_params[7], f'{pr_params[7]*100:.3f}%' if pr_params[7] else ''],
        ['PR Limite 5 (UFM)', pr_params[8], ''],
        ['PR Alíquota 5', pr_params[9], f'{pr_params[9]*100:.3f}%' if pr_params[9] else ''],
        ['PR Limite 6 (UFM)', pr_params[10], ''],
        ['PR Alíquota 6', pr_params[11], f'{pr_params[11]*100:.3f}%' if pr_params[11] else ''],
        ['PR Limite 7 (UFM)', pr_params[12], ''],
        ['PR Alíquota 7', pr_params[13], f'{pr_params[13]*100:.3f}%' if pr_params[13] else ''],
        ['PR Alíquota 8', pr_params[14], f'{pr_params[14]*100:.3f}%' if pr_params[14] else ''],
        ['', '', '']
    ])
    
    # PNR - 15 parameters
    param_data.append(['PREDIAL NÃO RESIDENCIAL (PNR)', '', ''])
    pnr_params = params[30:45]
    param_data.extend([
        ['PNR Limite 1 (UFM)', pnr_params[0], ''],
        ['PNR Alíquota 1', pnr_params[1], f'{pnr_params[1]*100:.3f}%' if pnr_params[1] else ''],
        ['PNR Limite 2 (UFM)', pnr_params[2], ''],
        ['PNR Alíquota 2', pnr_params[3], f'{pnr_params[3]*100:.3f}%' if pnr_params[3] else ''],
        ['PNR Limite 3 (UFM)', pnr_params[4], ''],
        ['PNR Alíquota 3', pnr_params[5], f'{pnr_params[5]*100:.3f}%' if pnr_params[5] else ''],
        ['PNR Limite 4 (UFM)', pnr_params[6], ''],
        ['PNR Alíquota 4', pnr_params[7], f'{pnr_params[7]*100:.3f}%' if pnr_params[7] else ''],
        ['PNR Limite 5 (UFM)', pnr_params[8], ''],
        ['PNR Alíquota 5', pnr_params[9], f'{pnr_params[9]*100:.3f}%' if pnr_params[9] else ''],
        ['PNR Limite 6 (UFM)', pnr_params[10], ''],
        ['PNR Alíquota 6', pnr_params[11], f'{pnr_params[11]*100:.3f}%' if pnr_params[11] else ''],
        ['PNR Limite 7 (UFM)', pnr_params[12], ''],
        ['PNR Alíquota 7', pnr_params[13], f'{pnr_params[13]*100:.3f}%' if pnr_params[13] else ''],
        ['PNR Alíquota 8', pnr_params[14], f'{pnr_params[14]*100:.3f}%' if pnr_params[14] else ''],
        ['', '', '']
    ])
    
    # EG, ER, ENR (each 15 parameters)
    categories = [
        ('ESTACIONAMENTOS GERAL (EG)', params[45:60], 'EG'),
        ('ESTACIONAMENTOS RESIDENCIAIS (ER)', params[60:75], 'ER'),
        ('ESTACIONAMENTOS NÃO RESIDENCIAIS (ENR)', params[75:90], 'EN')
    ]
    
    for cat_name, cat_params, prefix in categories:
        param_data.append([cat_name, '', ''])
        param_data.extend([
            [f'{prefix} Limite 1 (UFM)', cat_params[0], ''],
            [f'{prefix} Alíquota 1', cat_params[1], f'{cat_params[1]*100:.3f}%' if cat_params[1] else ''],
            [f'{prefix} Limite 2 (UFM)', cat_params[2], ''],
            [f'{prefix} Alíquota 2', cat_params[3], f'{cat_params[3]*100:.3f}%' if cat_params[3] else ''],
            [f'{prefix} Limite 3 (UFM)', cat_params[4], ''],
            [f'{prefix} Alíquota 3', cat_params[5], f'{cat_params[5]*100:.3f}%' if cat_params[5] else ''],
            [f'{prefix} Limite 4 (UFM)', cat_params[6], ''],
            [f'{prefix} Alíquota 4', cat_params[7], f'{cat_params[7]*100:.3f}%' if cat_params[7] else ''],
            [f'{prefix} Limite 5 (UFM)', cat_params[8], ''],
            [f'{prefix} Alíquota 5', cat_params[9], f'{cat_params[9]*100:.3f}%' if cat_params[9] else ''],
            [f'{prefix} Limite 6 (UFM)', cat_params[10], ''],
            [f'{prefix} Alíquota 6', cat_params[11], f'{cat_params[11]*100:.3f}%' if cat_params[11] else ''],
            [f'{prefix} Limite 7 (UFM)', cat_params[12], ''],
            [f'{prefix} Alíquota 7', cat_params[13], f'{cat_params[13]*100:.3f}%' if cat_params[13] else ''],
            [f'{prefix} Alíquota 8', cat_params[14], f'{cat_params[14]*100:.3f}%' if cat_params[14] else ''],
            ['', '', '']
        ])
    
    # Terrenos (T1DF, T2DF, T3DF - each 3 parameters)
    terreno_categories = [
        ('TERRENOS 1ª DF (T1DF)', params[90:93], '1'),
        ('TERRENOS 2ª DF (T2DF)', params[93:96], '2'),
        ('TERRENOS 3ª DF (T3DF)', params[96:99], '3')
    ]
    
    for cat_name, cat_params, num in terreno_categories:
        param_data.append([cat_name, '', ''])
        param_data.extend([
            [f'T{num}DF Limite 1 (UFM)', cat_params[0], ''],
            [f'T{num}DF Alíquota 1', cat_params[1], f'{cat_params[1]*100:.3f}%' if cat_params[1] else ''],
            [f'T{num}DF Alíquota 2', cat_params[2], f'{cat_params[2]*100:.3f}%' if cat_params[2] else ''],
            ['', '', '']
        ])
    
    # TAE and TAF (1 parameter each)
    param_data.extend([
        ['TERRENOS ALÍQUOTA ESPECIAL (TAE)', '', ''],
        ['TAE Alíquota 1', params[99], f'{params[99]*100:.3f}%' if params[99] else ''],
        ['', '', ''],
        ['TERRENOS ALÍQUOTA FIXA (TAF)', '', ''],
        ['TAF Alíquota 1', params[100], f'{params[100]*100:.3f}%' if params[100] else '']
    ])
    
    # Create DataFrame
    df = pd.DataFrame(param_data, columns=['Parâmetro', 'Valor', 'Percentual'])
    return df

def format_worksheet(worksheet, dataframe, currency_columns=None):
    """Format worksheet with currency formatting and auto-fit columns"""
    from openpyxl.styles import NamedStyle, Font, PatternFill, Alignment
    from openpyxl.utils import get_column_letter
    
    if currency_columns is None:
        currency_columns = []
    
    # Create currency style
    currency_style = NamedStyle(name="currency_brl")
    currency_style.number_format = 'R$ #,##0.00'
    
    # Create header style
    header_style = NamedStyle(name="header")
    header_style.font = Font(bold=True, color="FFFFFF")
    header_style.fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")
    header_style.alignment = Alignment(horizontal="center", vertical="center")
    
    # Apply header formatting
    for col_num in range(1, len(dataframe.columns) + 1):
        cell = worksheet.cell(row=1, column=col_num)
        cell.font = header_style.font
        cell.fill = header_style.fill
        cell.alignment = header_style.alignment
    
    # Apply currency formatting to specified columns
    for col_name in currency_columns:
        if col_name in dataframe.columns:
            col_idx = dataframe.columns.get_loc(col_name) + 1  # Excel is 1-indexed
            col_letter = get_column_letter(col_idx)
            
            # Apply currency format to all data cells in this column (skip header)
            for row_num in range(2, len(dataframe) + 2):
                cell = worksheet.cell(row=row_num, column=col_idx)
                cell.number_format = 'R$ #,##0.00'
    
    # Auto-fit column widths with 10% extra padding
    for column in worksheet.columns:
        max_length = 0
        column_letter = column[0].column_letter
        col_idx = column[0].column - 1  # Convert to 0-based index
        
        # Check if this is a currency column
        is_currency_column = False
        if col_idx < len(dataframe.columns):
            col_name = dataframe.columns[col_idx]
            is_currency_column = col_name in currency_columns
        
        for cell in column:
            try:
                if cell.value:
                    if is_currency_column and isinstance(cell.value, (int, float)):
                        # For currency columns, calculate based on formatted display length
                        # Format: "R$ 1,234,567,890.12" 
                        formatted_value = f"R$ {cell.value:,.2f}"
                        cell_length = len(formatted_value)
                    else:
                        # For non-currency columns, use actual string length
                        cell_length = len(str(cell.value))
                    
                    if cell_length > max_length:
                        max_length = cell_length
            except:
                pass
        
        # Set column width with 10% extra padding
        adjusted_width = min((max_length + 2) * 1.1, 55)  # 10% extra + cap at 55
        worksheet.column_dimensions[column_letter].width = adjusted_width
    
    # Set minimum width for very narrow columns
    for col_letter in [get_column_letter(i) for i in range(1, len(dataframe.columns) + 1)]:
        if worksheet.column_dimensions[col_letter].width < 12:
            worksheet.column_dimensions[col_letter].width = 12

# --- Function to create Excel file ---
def create_excel_download(df_resumo_iptu, result_agg, total_novo_str, total_atual_trib_str, total_atual_calc_str, 
                         valor_venal_choice, ufm_value, diferencia_estacionamentos_flag, diferencia_predios_flag, all_parameters):
    """Create an Excel file with multiple sheets containing the results and parameters"""
    
    # Create a BytesIO object to store the Excel file in memory
    output = io.BytesIO()
    
    # Create Excel writer
    with pd.ExcelWriter(output, engine='openpyxl') as writer:
        # Sheet 1: Detailed summary by category and range
        if df_resumo_iptu is not None and not df_resumo_iptu.empty:
            # Create a copy without formatting for Excel export
            df_export = df_resumo_iptu.copy()
            # Convert formatted numbers back to numeric for Excel
            if 'Total arrecadado na faixa' in df_export.columns:
                df_export['Total arrecadado na faixa'] = df_export['Total arrecadado na faixa'].astype(str).str.replace(',', '').astype(float)
            df_export.to_excel(writer, sheet_name='Resumo Detalhado', index=False)
            
            # Format the sheet
            worksheet = writer.sheets['Resumo Detalhado']
            format_worksheet(worksheet, df_export, currency_columns=['Total arrecadado na faixa'])
        
        # Sheet 2: Aggregated summary by category
        if result_agg is not None and not result_agg.empty:
            # Create a copy without formatting for Excel export
            result_export = result_agg.copy()
            # Convert formatted numbers back to numeric for Excel
            total_cols_to_convert = [col for col in result_export.columns if col.startswith("Total")]
            for col_name in total_cols_to_convert:
                if col_name in result_export.columns:
                    result_export[col_name] = result_export[col_name].astype(str).str.replace(',', '').astype(float)
            result_export.to_excel(writer, sheet_name='Resumo Agregado', index=False)
            
            # Format the sheet
            worksheet = writer.sheets['Resumo Agregado']
            currency_cols = [col for col in result_export.columns if col.startswith("Total")]
            format_worksheet(worksheet, result_export, currency_columns=currency_cols)
        
        # Sheet 3: Summary totals
        summary_data = {
            'Descrição': ['Total IPTU Novo', 'Total IPTU Atual Tributado', 'Total IPTU Atual Calculado'],
            'Valor': [
                float(total_novo_str.split(': ')[1].replace(',', '')) if ': ' in total_novo_str else 0,
                float(total_atual_trib_str.split(': ')[1].replace(',', '')) if ': ' in total_atual_trib_str else 0,
                float(total_atual_calc_str.split(': ')[1].replace(',', '')) if ': ' in total_atual_calc_str else 0
            ]
        }
        summary_df = pd.DataFrame(summary_data)
        summary_df.to_excel(writer, sheet_name='Totais Gerais', index=False)
        
        # Format the sheet
        worksheet = writer.sheets['Totais Gerais']
        format_worksheet(worksheet, summary_df, currency_columns=['Valor'])
        
        # Sheet 4: Parameters and Ranges Used
        params_data = create_parameters_sheet(valor_venal_choice, ufm_value, diferencia_estacionamentos_flag, diferencia_predios_flag, all_parameters)
        params_data.to_excel(writer, sheet_name='Parâmetros Utilizados', index=False)
        
        # Format the parameters sheet
        worksheet = writer.sheets['Parâmetros Utilizados']
        format_worksheet(worksheet, params_data, currency_columns=[])
    
    output.seek(0)
    return output

# --- Main processing function ---
def process_iptu_data(
    valor_venal_choice, ufm_value_input, 
    diferencia_estacionamentos_flag, diferencia_predios_flag,
    # Inputs for Faixas e Alíquotas
    pg_lim1, pg_alq1, pg_lim2, pg_alq2, pg_lim3, pg_alq3, pg_lim4, pg_alq4, pg_lim5, pg_alq5, pg_lim6, pg_alq6, pg_lim7, pg_alq7, pg_alq8,
    pr_lim1, pr_alq1, pr_lim2, pr_alq2, pr_lim3, pr_alq3, pr_lim4, pr_alq4, pr_lim5, pr_alq5, pr_lim6, pr_alq6, pr_lim7, pr_alq7, pr_alq8,
    pnr_lim1, pnr_alq1, pnr_lim2, pnr_alq2, pnr_lim3, pnr_alq3, pnr_lim4, pnr_alq4, pnr_lim5, pnr_alq5, pnr_lim6, pnr_alq6, pnr_lim7, pnr_alq7, pnr_alq8,
    eg_lim1, eg_alq1, eg_lim2, eg_alq2, eg_lim3, eg_alq3, eg_lim4, eg_alq4, eg_lim5, eg_alq5, eg_lim6, eg_alq6, eg_lim7, eg_alq7, eg_alq8,
    er_lim1, er_alq1, er_lim2, er_alq2, er_lim3, er_alq3, er_lim4, er_alq4, er_lim5, er_alq5, er_lim6, er_alq6, er_lim7, er_alq7, er_alq8,
    enr_lim1, enr_alq1, enr_lim2, enr_alq2, enr_lim3, enr_alq3, enr_lim4, enr_alq4, enr_lim5, enr_alq5, enr_lim6, enr_alq6, enr_lim7, enr_alq7, enr_alq8,
    t1df_lim1, t1df_alq1, t1df_alq2,
    t2df_lim1, t2df_alq1, t2df_alq2,
    t3df_lim1, t3df_alq1, t3df_alq2,
    tae_alq1,
    taf_alq1
    ):
    
    # === CSV LOADING AND VALIDATION ===
    if not os.path.exists(CSV_FILE_PATH):
        return f"Erro: Arquivo '{CSV_FILE_PATH}' não encontrado no servidor.", None, None, "", "", "", gr.Textbox(visible=False), gr.DownloadButton(visible=False)

    try:
        the_merge = pd.read_csv(CSV_FILE_PATH)
    except Exception as e:
        return f"Erro ao ler o arquivo CSV '{CSV_FILE_PATH}': {str(e)}", None, None, "", "", "", gr.Textbox(visible=False), gr.DownloadButton(visible=False)
    
    valor_venal_utilizado = valor_venal_choice
    UFM_VALUE = ufm_value_input
    
    required_cols = ["TIPO_LANCAMENTO", "DES_TIPO_ISENCAO_MULTI", "VLR_IMPOSTO_iptu", 
                     "DES_FINALIDADE_unidade", "DES_USO_unidade", "IDF_TIPO_BENEFICIO",
                     "NUM_DIVISAO_FISCAL_iptu", valor_venal_utilizado, 
                     "VLR_IMPOSTO_CALCULADO_iptu"] 
    missing_cols = [col for col in required_cols if col not in the_merge.columns]
    if missing_cols:
        return f"Colunas ausentes no CSV: {', '.join(missing_cols)}", None, None, "", "", "", gr.Textbox(visible=False), gr.DownloadButton(visible=False)

    for col_str in ["TIPO_LANCAMENTO", "DES_TIPO_ISENCAO_MULTI", "DES_FINALIDADE_unidade", "DES_USO_unidade"]:
        if col_str in the_merge.columns:
            the_merge[col_str] = the_merge[col_str].astype(str).fillna('')

    # === PARAMETER ASSIGNMENT ===
    # [All parameter assignments remain exactly the same as before]
    PG_lim_1, PG_aliq_1 = pg_lim1, pg_alq1; PG_lim_2, PG_aliq_2 = pg_lim2, pg_alq2; PG_lim_3, PG_aliq_3 = pg_lim3, pg_alq3; PG_lim_4, PG_aliq_4 = pg_lim4, pg_alq4; PG_lim_5, PG_aliq_5 = pg_lim5, pg_alq5; PG_lim_6, PG_aliq_6 = pg_lim6, pg_alq6; PG_lim_7, PG_aliq_7 = pg_lim7, pg_alq7; PG_aliq_8 = pg_alq8
    PR_lim_1, PR_aliq_1 = pr_lim1, pr_alq1; PR_lim_2, PR_aliq_2 = pr_lim2, pr_alq2; PR_lim_3, PR_aliq_3 = pr_lim3, pr_alq3; PR_lim_4, PR_aliq_4 = pr_lim4, pr_alq4; PR_lim_5, PR_aliq_5 = pr_lim5, pr_alq5; PR_lim_6, PR_aliq_6 = pr_lim6, pr_alq6; PR_lim_7, PR_aliq_7 = pr_lim7, pr_alq7; PR_aliq_8 = pr_alq8
    PNR_lim_1, PNR_aliq_1 = pnr_lim1, pnr_alq1; PNR_lim_2, PNR_aliq_2 = pnr_lim2, pnr_alq2; PNR_lim_3, PNR_aliq_3 = pnr_lim3, pnr_alq3; PNR_lim_4, PNR_aliq_4 = pnr_lim4, pnr_alq4; PNR_lim_5, PNR_aliq_5 = pnr_lim5, pnr_alq5; PNR_lim_6, PNR_aliq_6 = pnr_lim6, pnr_alq6; PNR_lim_7, PNR_aliq_7 = pnr_lim7, pnr_alq7; PNR_aliq_8 = pnr_alq8
    EG_lim_1, EG_aliq_1 = eg_lim1, eg_alq1; EG_lim_2, EG_aliq_2 = eg_lim2, eg_alq2; EG_lim_3, EG_aliq_3 = eg_lim3, eg_alq3; EG_lim_4, EG_aliq_4 = eg_lim4, eg_alq4; EG_lim_5, EG_aliq_5 = eg_lim5, eg_alq5; EG_lim_6, EG_aliq_6 = eg_lim6, eg_alq6; EG_lim_7, EG_aliq_7 = eg_lim7, eg_alq7; EG_aliq_8 = eg_alq8
    ER_lim_1, ER_aliq_1 = er_lim1, er_alq1; ER_lim_2, ER_aliq_2 = er_lim2, er_alq2; ER_lim_3, ER_aliq_3 = er_lim3, er_alq3; ER_lim_4, ER_aliq_4 = er_lim4, er_alq4; ER_lim_5, ER_aliq_5 = er_lim5, er_alq5; ER_lim_6, ER_aliq_6 = er_lim6, er_alq6; ER_lim_7, ER_aliq_7 = er_lim7, er_alq7; ER_aliq_8 = er_alq8
    ENR_lim_1, ENR_aliq_1 = enr_lim1, enr_alq1; ENR_lim_2, ENR_aliq_2 = enr_lim2, enr_alq2; ENR_lim_3, ENR_aliq_3 = enr_lim3, enr_alq3; ENR_lim_4, ENR_aliq_4 = enr_lim4, enr_alq4; ENR_lim_5, ENR_aliq_5 = enr_lim5, enr_alq5; ENR_lim_6, ENR_aliq_6 = enr_lim6, enr_alq6; ENR_lim_7, ENR_aliq_7 = enr_lim7, enr_alq7; ENR_aliq_8 = enr_alq8
    T1DF_lim_1, T1DF_aliq_1 = t1df_lim1, t1df_alq1; T1DF_aliq_2 = t1df_alq2
    T2DF_lim_1, T2DF_aliq_1 = t2df_lim1, t2df_alq1; T2DF_aliq_2 = t2df_alq2
    T3DF_lim_1, T3DF_aliq_1 = t3df_lim1, t3df_alq1; T3DF_aliq_2 = t3df_alq2
    TAE_aliq_1 = tae_alq1
    TAF_aliq_1 = taf_alq1

    # === DATA FILTERING AND CLASSIFICATION ===
    # [All filtering logic remains exactly the same as before]
    sem_lancamento = (the_merge["TIPO_LANCAMENTO"].isin(['Isenção Total por Benefício Fiscal', 'Imóvel com bloqueio de lançamento de IPTU/TCL', 'Não lançado - Valor total calculado menor que o mínimo', 'Isenção TCL Box e Não Lançado - valor menor que Mínimo', 'Isenção Técnica'])) | ((the_merge["TIPO_LANCAMENTO"]=='Isenção TCL - Box') & (the_merge["VLR_IMPOSTO_iptu"]==0))
    isentos = (the_merge["DES_TIPO_ISENCAO_MULTI"].str.contains("isen", case=False, na=False))
    imunes = (the_merge["DES_TIPO_ISENCAO_MULTI"].str.contains("imun", case=False, na=False)) | (the_merge["DES_TIPO_ISENCAO_MULTI"].str.contains("IMUNIDADES", na=False))
    nao_incidencia = (the_merge["DES_TIPO_ISENCAO_MULTI"].str.contains("NÃO INCIDÊNCIA DE IPTU", case=False, na=False))
    nao_tributados = (isentos) | (imunes) | (sem_lancamento) | (nao_incidencia)

    # Property type classifications [Same as before]
    finalidades_estacionamentos = ['ESPACO DE ESTACIONAMENTO RESIDENCIAL', 'ESPACO DE ESTACIONAMENTO NAO RESIDENCIAL', 'ESPACO ESTACIONAMENTO VINCULADO NAO RESID DESCOBERTO', 'ESPACO ESTACIONAMENTO VINCULADO RESID COBERTO', 'ESPACO ESTACIONAMENTO VINCULADO NAO RESID COBERTO', 'ESPACO DE ESTACIONAMENTO RESIDENCIAL DESCOBERTO', 'ESPACO DE ESTACIONAMENTO NAO RESIDENC DESCOBERTO', 'ESPACO ESTACIONAMENTO VINCULADO RESID DESCOBERTO']
    finalidades_terrenos = ['TERRENO', 'GLEBA', 'TERRENOS CONDOMINIO HORIZ ABERTO SEM AREA USO COMUM', 'TERRENO EM CONDOMINIO HORIZONTAL FECHADO', 'TERRENO EM CONDOMINIO HORIZONTAL ABERTO', 'SOBRA DE AREA', 'AREA A VISTORIAR']
    
    # All property classifications [Same logic as before]
    estacionamentos_residenciais = (the_merge["DES_FINALIDADE_unidade"].isin(finalidades_estacionamentos)) & (the_merge["DES_USO_unidade"]=='Exclusivamente Residencial')
    estacionamentos_residenciais_tributados = (estacionamentos_residenciais) & (~nao_tributados)
    estacionamentos_residenciais_nao_tributados = (estacionamentos_residenciais) & (nao_tributados)
    estacionamentos_nao_residenciais = (the_merge["DES_FINALIDADE_unidade"].isin(finalidades_estacionamentos)) & (the_merge["DES_USO_unidade"]!='Exclusivamente Residencial')
    estacionamentos_nao_residenciais_tributados =  (estacionamentos_nao_residenciais) & (~nao_tributados)
    estacionamentos_nao_residenciais_nao_tributados = (estacionamentos_nao_residenciais) & (nao_tributados)
    estacionamentos_geral = the_merge["DES_FINALIDADE_unidade"].isin(finalidades_estacionamentos)
    estacionamentos_geral_tributados = (estacionamentos_geral) & (~nao_tributados)
    estacionamentos_geral_nao_tributados = (estacionamentos_geral) & (nao_tributados)

    terrenos_aliqesp = (the_merge["DES_FINALIDADE_unidade"].isin(finalidades_terrenos)) & (pd.to_numeric(the_merge["IDF_TIPO_BENEFICIO"], errors="coerce").fillna(0).astype(int) == 301) & (~nao_tributados)
    terrenos_aliqfix = (the_merge["DES_FINALIDADE_unidade"].isin(finalidades_terrenos)) & (pd.to_numeric(the_merge["IDF_TIPO_BENEFICIO"], errors="coerce").fillna(0).astype(int) == 95) & (~nao_tributados)
    terrenos_1df = (the_merge["DES_FINALIDADE_unidade"].isin(finalidades_terrenos)) & (the_merge["NUM_DIVISAO_FISCAL_iptu"]==1) & (~terrenos_aliqesp) & (~terrenos_aliqfix)
    terrenos_1df_tributados = (terrenos_1df) & (~nao_tributados)
    terrenos_1df_nao_tributados = (terrenos_1df) & (nao_tributados)
    terrenos_2df = (the_merge["DES_FINALIDADE_unidade"].isin(finalidades_terrenos)) & (the_merge["NUM_DIVISAO_FISCAL_iptu"]==2) & (~terrenos_aliqesp) & (~terrenos_aliqfix)
    terrenos_2df_tributados =  (terrenos_2df) & (~nao_tributados)
    terrenos_2df_nao_tributados = (terrenos_2df) & (nao_tributados)
    terrenos_3df = (the_merge["DES_FINALIDADE_unidade"].isin(finalidades_terrenos)) & (the_merge["NUM_DIVISAO_FISCAL_iptu"]==3) & (~terrenos_aliqesp) & (~terrenos_aliqfix)
    terrenos_3df_tributados = (terrenos_3df)  & (~nao_tributados)
    terrenos_3df_nao_tributados = (terrenos_3df) & (nao_tributados)

    isen_prop_loc = ((the_merge["DES_TIPO_ISENCAO_MULTI"] == 'ISENÇÃO - PROPRIETARIO/USUFRUTUARIO APOSENTADO, INATIVO, PENSIONISTA') | (the_merge["DES_TIPO_ISENCAO_MULTI"] == 'ISENÇÃO - LOCATÁRIO/COMODATARIO/ARRENDATÁRIO  APOSENTADO, INATIVO, PENSIONISTA')| (the_merge["DES_TIPO_ISENCAO_MULTI"] == 'ISENÇÃO - PROPRIETARIO/USUFRUTUARIO DEFICIENTE'))
    isen_hab_pop = ((the_merge["DES_TIPO_ISENCAO_MULTI"] == 'ISENÇÃO - HABITAÇÕES POPULARES DE EMPREENDIMENTOS HABITACIONAIS DESTINADOS PARA HABITAÇÃO DE INTERESSE SOCIAL') | (the_merge["DES_TIPO_ISENCAO_MULTI"] == 'ISENÇÃO - HABITAÇÕES POPULARES ORIUNDAS DE REGULARIZAÇÕES FUNDIÁRIAS PROMOVIDAS POR ÓRGÃOS PÚBLICOS'))
    
    prediais_residenciais = (~the_merge["DES_FINALIDADE_unidade"].isin(finalidades_estacionamentos + finalidades_terrenos)) & (the_merge["DES_USO_unidade"] == 'Exclusivamente Residencial')
    prediais_residenciais_tributados = (prediais_residenciais) & (~nao_tributados) & (~isen_prop_loc) & (~isen_hab_pop)
    prediais_residenciais_nao_tributados = (prediais_residenciais) & (nao_tributados) & (~isen_prop_loc) & (~isen_hab_pop)
    prediais_nao_residenciais = (~the_merge["DES_FINALIDADE_unidade"].isin(finalidades_estacionamentos + finalidades_terrenos)) & (the_merge["DES_USO_unidade"] != 'Exclusivamente Residencial') & (~isen_prop_loc) & (~isen_hab_pop)
    prediais_nao_residenciais_tributados = (prediais_nao_residenciais) & (~nao_tributados) & (~isen_prop_loc) & (~isen_hab_pop)
    prediais_nao_residenciais_nao_tributados = (prediais_nao_residenciais) & (nao_tributados) & (~isen_prop_loc) & (~isen_hab_pop)
    prediais_geral = (~the_merge["DES_FINALIDADE_unidade"].isin(finalidades_estacionamentos + finalidades_terrenos)) & (~isen_prop_loc) & (~isen_hab_pop)
    prediais_geral_tributados = (prediais_geral) & (~nao_tributados) & (~isen_prop_loc) & (~isen_hab_pop)
    prediais_geral_nao_tributados = (prediais_geral) & (nao_tributados) & (~isen_prop_loc) & (~isen_hab_pop)
    
    # === IPTU RULES DEFINITION ===
    IPTU_RULES = {
        'PGI': { 'name': "Predial Sem Dif. por Uso Isentos", 'rule': prediais_geral_nao_tributados, 'ranges': [[np.inf, 0.0]]},
        'PG': { 'name': "Predial Sem Dif. por Uso", 'rule': prediais_geral_tributados, 'ranges': [[PG_lim_1*UFM_VALUE, PG_aliq_1],[PG_lim_2*UFM_VALUE, PG_aliq_2],[PG_lim_3*UFM_VALUE, PG_aliq_3],[PG_lim_4*UFM_VALUE, PG_aliq_4],[PG_lim_5*UFM_VALUE, PG_aliq_5],[PG_lim_6*UFM_VALUE, PG_aliq_6],[PG_lim_7*UFM_VALUE, PG_aliq_7],[np.inf, PG_aliq_8]]},
        'PRI': { 'name': "Predial Residencial Isentos", 'rule': prediais_residenciais_nao_tributados, 'ranges': [[np.inf, 0.0]]},
        'PR': { 'name': "Predial Residencial", 'rule': prediais_residenciais_tributados, 'ranges': [[PR_lim_1*UFM_VALUE, PR_aliq_1],[PR_lim_2*UFM_VALUE, PR_aliq_2],[PR_lim_3*UFM_VALUE, PR_aliq_3],[PR_lim_4*UFM_VALUE, PR_aliq_4],[PR_lim_5*UFM_VALUE, PR_aliq_5],[PR_lim_6*UFM_VALUE, PR_aliq_6],[PR_lim_7*UFM_VALUE, PR_aliq_7],[np.inf, PR_aliq_8]]},
        'PNRI': { 'name': "Predial Não Residencial Isentos", 'rule': prediais_nao_residenciais_nao_tributados, 'ranges': [[np.inf, 0.0]]},
        'PNR': { 'name': "Predial Não Residencial", 'rule': prediais_nao_residenciais_tributados, 'ranges': [[PNR_lim_1*UFM_VALUE, PNR_aliq_1],[PNR_lim_2*UFM_VALUE, PNR_aliq_2],[PNR_lim_3*UFM_VALUE, PNR_aliq_3],[PNR_lim_4*UFM_VALUE, PNR_aliq_4],[PNR_lim_5*UFM_VALUE, PNR_aliq_5],[PNR_lim_6*UFM_VALUE, PNR_aliq_6],[PNR_lim_7*UFM_VALUE, PNR_aliq_7],[np.inf, PNR_aliq_8]]},
        'EGI': { 'name':'Estacionamentos Sem Dif. por Uso Isentos', 'rule': estacionamentos_geral_nao_tributados, 'ranges': [[np.inf, 0.0]]},
        'EG': { 'name': "Estacionamentos Sem Dif. por Uso", 'rule': estacionamentos_geral_tributados, 'ranges': [[EG_lim_1*UFM_VALUE, EG_aliq_1],[EG_lim_2*UFM_VALUE, EG_aliq_2],[EG_lim_3*UFM_VALUE, EG_aliq_3],[EG_lim_4*UFM_VALUE, EG_aliq_4],[EG_lim_5*UFM_VALUE, EG_aliq_5],[EG_lim_6*UFM_VALUE, EG_aliq_6],[EG_lim_7*UFM_VALUE, EG_aliq_7],[np.inf, EG_aliq_8]]},
        'ERI': { 'name':'Estacionamentos Residenciais Isentos', 'rule': estacionamentos_residenciais_nao_tributados, 'ranges': [[np.inf, 0.0]]},
        'ER': { 'name':'Estacionamentos Residenciais', 'rule': estacionamentos_residenciais_tributados, 'ranges': [[ER_lim_1*UFM_VALUE, ER_aliq_1],[ER_lim_2*UFM_VALUE, ER_aliq_2],[ER_lim_3*UFM_VALUE, ER_aliq_3],[ER_lim_4*UFM_VALUE, ER_aliq_4],[ER_lim_5*UFM_VALUE, ER_aliq_5],[ER_lim_6*UFM_VALUE, ER_aliq_6],[ER_lim_7*UFM_VALUE, ER_aliq_7],[np.inf, ER_aliq_8]]},
        'ENRI': { 'name':'Estacionamentos Não Residenciais Isentos', 'rule': estacionamentos_nao_residenciais_nao_tributados, 'ranges': [[np.inf, 0.0]]},
        'ENR': { 'name':'Estacionamentos Não Residenciais', 'rule': estacionamentos_nao_residenciais_tributados, 'ranges': [[ENR_lim_1*UFM_VALUE, ENR_aliq_1],[ENR_lim_2*UFM_VALUE, ENR_aliq_2],[ENR_lim_3*UFM_VALUE, ENR_aliq_3],[ENR_lim_4*UFM_VALUE, ENR_aliq_4],[ENR_lim_5*UFM_VALUE, ENR_aliq_5],[ENR_lim_6*UFM_VALUE, ENR_aliq_6],[ENR_lim_7*UFM_VALUE, ENR_aliq_7],[np.inf, ENR_aliq_8]]},
        'T1DFI': { 'name':'Terrenos na 1a DF Isentos', 'rule': terrenos_1df_nao_tributados, 'ranges': [[np.inf, 0.0]]},
        'T1DF': { 'name': 'Terrenos na 1a DF', 'rule': terrenos_1df_tributados, 'ranges': [[T1DF_lim_1*UFM_VALUE, T1DF_aliq_1],[np.inf, T1DF_aliq_2]]},
        'T2DFI': { 'name':'Terrenos na 2a DF Isentos', 'rule': terrenos_2df_nao_tributados, 'ranges': [[np.inf, 0.0]]},
        'T2DF': { 'name': 'Terrenos na 2a DF', 'rule': terrenos_2df_tributados, 'ranges': [[T2DF_lim_1*UFM_VALUE, T2DF_aliq_1],[np.inf, T2DF_aliq_2]]},
        'T3DFI': { 'name':'Terrenos na 3a DF Isentos', 'rule': terrenos_3df_nao_tributados, 'ranges': [[np.inf, 0.0]]},
        'T3DF': { 'name': 'Terrenos na 3a DF', 'rule': terrenos_3df_tributados, 'ranges': [[T3DF_lim_1*UFM_VALUE, T3DF_aliq_1],[np.inf, T3DF_aliq_2]]},
        'TAE': { 'name': 'Terrenos Aliq. Esp.', 'rule': terrenos_aliqesp, 'ranges': [[np.inf, TAE_aliq_1]]},
        'TAF': { 'name': 'Terrenos Aliq. Fix.', 'rule': terrenos_aliqfix, 'ranges': [[np.inf, TAF_aliq_1]]},
    }

    # Rule filtering based on differentiation flags [Same logic as before]
    if diferencia_estacionamentos_flag:
        if 'EG' in IPTU_RULES: del IPTU_RULES['EG']
        if 'EGI' in IPTU_RULES: del IPTU_RULES['EGI']
    else:
        if 'ER' in IPTU_RULES: del IPTU_RULES['ER']
        if 'ERI' in IPTU_RULES: del IPTU_RULES['ERI']
        if 'ENR' in IPTU_RULES: del IPTU_RULES['ENR']
        if 'ENRI' in IPTU_RULES: del IPTU_RULES['ENRI']

    if diferencia_predios_flag:
        if 'PG' in IPTU_RULES: del IPTU_RULES['PG']
        if 'PGI' in IPTU_RULES: del IPTU_RULES['PGI']
    else:
        if 'PR' in IPTU_RULES: del IPTU_RULES['PR']
        if 'PRI' in IPTU_RULES: del IPTU_RULES['PRI']
        if 'PNR' in IPTU_RULES: del IPTU_RULES['PNR']
        if 'PNRI' in IPTU_RULES: del IPTU_RULES['PNRI']

    reference_rule_key = 'PR' if diferencia_predios_flag else 'PG'
    if reference_rule_key not in IPTU_RULES:
         if 'PG' in IPTU_RULES: reference_rule_key = 'PG'
         elif 'PR' in IPTU_RULES: reference_rule_key = 'PR'
         else: return f"Erro: Nenhuma regra de referência Predial (PG/PR) disponível.", None, None, "", "", "", gr.Textbox(visible=False), gr.DownloadButton(visible=False)
    reference_rule = IPTU_RULES[reference_rule_key]

    # Special rules for exemptions [Same logic as before]
    prpl_ranges = [[100000 * UFM_VALUE, 0.0]]
    if reference_rule['ranges'][0][0] >= 100000 * UFM_VALUE: prpl_ranges = reference_rule['ranges'].copy()
    else:
        for threshold, rate in reference_rule['ranges']:
            if threshold > 100000 * UFM_VALUE: prpl_ranges.append([threshold, rate])
    IPTU_RULES['PRPL'] = {'name': "Predial Residencial - Aposentado, Inativo, Pensionista, Deficiente", 'rule': isen_prop_loc, 'ranges': prpl_ranges}

    prph_ranges = [[55000 * UFM_VALUE, 0.0]]
    if reference_rule['ranges'][0][0] >= 55000 * UFM_VALUE: prph_ranges = reference_rule['ranges'].copy()
    else:
        for threshold, rate in reference_rule['ranges']:
            if threshold > 55000 * UFM_VALUE: prph_ranges.append([threshold, rate])
    IPTU_RULES['PRHP'] = {'name': "Predial Residencial - Habitações Populares", 'rule': isen_hab_pop, 'ranges': prph_ranges}
    
    # === TAX CALCULATION ENGINE ===
    # [All calculation logic remains exactly the same as before]
    the_merge[valor_venal_utilizado] = pd.to_numeric(the_merge[valor_venal_utilizado], errors='coerce')

    for regra_nome, regra in IPTU_RULES.items():
        filtro = regra["rule"]
        faixas = regra["ranges"]
        current_vv_values = the_merge.loc[filtro, valor_venal_utilizado] 
        limites = [0] + [lim[0] for lim in faixas]
        aliquotas = [lim[1] for lim in faixas]

        for i in range(len(aliquotas)):
            limite_inferior = limites[i]
            limite_superior = limites[i + 1] if i + 1 < len(limites) else float('inf')
            aliquota = aliquotas[i]
            nome_coluna = f"IPTU_{regra_nome}_F{i+1}"
            valor_na_banda = np.maximum(0, np.minimum(current_vv_values, limite_superior) - limite_inferior)
            if limite_superior == float('inf'):
                valor_na_banda = np.maximum(0, current_vv_values - limite_inferior)
            imposto_na_banda = valor_na_banda * aliquota
            the_merge.loc[filtro, nome_coluna] = imposto_na_banda

    new_total_columns = {}
    for chave, regra in IPTU_RULES.items():
        colunas_faixas = [f"IPTU_{chave}_F{i+1}" for i in range(len(regra["ranges"]))]
        for col_f in colunas_faixas:
            if col_f not in the_merge.columns: the_merge[col_f] = 0
        if not colunas_faixas: new_total_columns[f"IPTU_{chave}_TOTAL"] = pd.Series(0, index=the_merge.index)
        else: new_total_columns[f"IPTU_{chave}_TOTAL"] = the_merge[colunas_faixas].fillna(0).sum(axis=1)
    the_merge = pd.concat([the_merge, pd.DataFrame(new_total_columns, index=the_merge.index)], axis=1)

    # === RESULTS GENERATION ===
    # [All results generation logic remains exactly the same as before]
    resumo_total = []
    for regra_nome, regra in IPTU_RULES.items():
        nome_legivel = regra["name"]; filtro_rule = regra["rule"]; faixas = regra["ranges"]
        df_filtrado = the_merge[filtro_rule].copy()
        vv_perc = df_filtrado[valor_venal_utilizado]
        limites_faixas = [lim[0] for lim in faixas]; limites_com_zero = [0] + limites_faixas; aliquotas_faixas = [lim[1] for lim in faixas]

        for i, (limite_superior_raw, aliquota) in enumerate(faixas):
            limite_superior_display = limite_superior_raw if limite_superior_raw != np.inf else float('inf')
            faixa_col = f"IPTU_{regra_nome}_F{i+1}"
            if faixa_col not in df_filtrado.columns: df_filtrado[faixa_col] = 0
            faixa_nome_val_inf = limite_superior_display/UFM_VALUE if UFM_VALUE != 0 else float('inf')
            faixa_nome = f"{limites_com_zero[i]/UFM_VALUE if UFM_VALUE !=0 else 0:,.0f} a {faixa_nome_val_inf:,.0f} UFM ({aliquota*100:.2f}%)"
            if limite_superior_display == float('inf'): faixa_nome = f"{limites_com_zero[i]/UFM_VALUE if UFM_VALUE != 0 else 0:,.0f} a inf UFM ({aliquota*100:.2f}%)"
            total_faixa = df_filtrado[faixa_col].fillna(0).sum()
            cond_exclusiva = pd.Series(False, index=vv_perc.index)
            if not vv_perc.empty:
                if i == 0: cond_exclusiva = vv_perc <= limite_superior_raw
                else: cond_exclusiva = (vv_perc > limites_com_zero[i]) & (vv_perc <= limite_superior_raw)
            qnt_exclusiva = cond_exclusiva.sum()
            cond_atinge = pd.Series(False, index=vv_perc.index)
            if not vv_perc.empty: cond_atinge = vv_perc > limites_com_zero[i]
            qnt_atinge = cond_atinge.sum()
            resumo_total.append([nome_legivel, faixa_nome, qnt_exclusiva, qnt_atinge, total_faixa])
    
    df_resumo_iptu = pd.DataFrame(resumo_total, columns=["Categoria", "Faixa (VV em UFM)", "Inscrições apenas nesta faixa", "Inscrições que atingem esta faixa", "Total arrecadado na faixa"])
    df_resumo_iptu.reset_index(drop=True, inplace=True)

    # Aggregation and normalization logic [Same as before]
    df = df_resumo_iptu.copy()
    temp_cat_col = df["Categoria"].astype(str)
    if diferencia_predios_flag:
        temp_cat_col = temp_cat_col.str.replace(r" - Aposentado, Inativo, Pensionista, Deficiente$", "", regex=True)
        temp_cat_col = temp_cat_col.str.replace(r" - Habitações Populares$", "", regex=True)
    else:
        predial_pattern = r"Predial (Residencial|Não Residencial|Sem Dif\. por Uso)( - Aposentado, Inativo, Pensionista, Deficiente| - Habitações Populares| Isentos)?$"
        temp_cat_col = temp_cat_col.str.replace(predial_pattern, "Predial Sem Dif. por Uso", regex=True)
    temp_cat_col = temp_cat_col.str.replace(r" Isentos$", "", regex=True)
    df["CategoriaNormalizada"] = temp_cat_col
    df["Total arrecadado na faixa"] = pd.to_numeric(df["Total arrecadado na faixa"], errors="coerce").fillna(0)
    result_agg = df.groupby("CategoriaNormalizada", as_index=False).agg({"Inscrições apenas nesta faixa": "sum", "Total arrecadado na faixa": "sum"}).rename(columns={"CategoriaNormalizada": "Categoria", "Inscrições apenas nesta faixa": "Inscrições", "Total arrecadado na faixa": "Total IPTU Novo"})

    # Current tax totals calculation [Same as before]
    total_imposto_atual, total_imposto_calculado, inscricoes_com_iptu = {}, {}, {}
    for regra_nome, regra in IPTU_RULES.items():
        nome_legivel = regra["name"]
        nome_normalizado = str(nome_legivel)
        if diferencia_predios_flag:
            nome_normalizado = nome_normalizado.replace(" - Aposentado, Inativo, Pensionista, Deficiente", "")
            nome_normalizado = nome_normalizado.replace(" - Habitações Populares", "")
        else:
            if "Predial Residencial" in nome_normalizado or "Predial Não Residencial" in nome_normalizado or "Predial Sem Dif. por Uso" in nome_normalizado :
                 nome_normalizado = "Predial Sem Dif. por Uso"
        nome_normalizado = nome_normalizado.replace(" Isentos", "")
        filtro_rule = regra["rule"]
        total_imposto_atual[nome_normalizado] = total_imposto_atual.get(nome_normalizado, 0) + the_merge.loc[filtro_rule, "VLR_IMPOSTO_iptu"].fillna(0).sum()
        total_imposto_calculado[nome_normalizado] = total_imposto_calculado.get(nome_normalizado, 0) + the_merge.loc[filtro_rule, "VLR_IMPOSTO_CALCULADO_iptu"].fillna(0).sum()
        inscricoes_com_iptu[nome_normalizado] = inscricoes_com_iptu.get(nome_normalizado, 0) + (the_merge.loc[filtro_rule, "VLR_IMPOSTO_iptu"].fillna(0) > 0).sum()
        
    result_agg["Total IPTU Atual Tributado"] = result_agg["Categoria"].map(total_imposto_atual).fillna(0)
    result_agg["Total IPTU Atual Calculado"] = result_agg["Categoria"].map(total_imposto_calculado).fillna(0)
    result_agg["Inscrições com IPTU > 0"] = result_agg["Categoria"].map(inscricoes_com_iptu).fillna(0)

    # Final filtering [Same as before]
    if diferencia_estacionamentos_flag: result_agg = result_agg[result_agg["Categoria"] != "Estacionamentos Sem Dif. por Uso"]
    else: result_agg = result_agg[~result_agg["Categoria"].isin(["Estacionamentos Não Residenciais", "Estacionamentos Residenciais"])]
    if diferencia_predios_flag: result_agg = result_agg[result_agg["Categoria"] != "Predial Sem Dif. por Uso"]
    else: result_agg = result_agg[~result_agg["Categoria"].isin(["Predial Não Residencial", "Predial Residencial"])]
    cols_order = ["Categoria", "Inscrições", "Inscrições com IPTU > 0", "Total IPTU Novo", "Total IPTU Atual Tributado", "Total IPTU Atual Calculado"]
    current_cols = [col for col in cols_order if col in result_agg.columns]
    result_agg = result_agg[current_cols]

    # === FORMATTING FOR DISPLAY ===
    if 'Total arrecadado na faixa' in df_resumo_iptu.columns:
        df_resumo_iptu['Total arrecadado na faixa'] = df_resumo_iptu['Total arrecadado na faixa'].apply(lambda x: f"{x:,.2f}" if pd.notnull(x) else x)

    total_cols_to_format = [col for col in result_agg.columns if col.startswith("Total")]
    for col_name in total_cols_to_format:
        if result_agg[col_name].dtype == float or result_agg[col_name].dtype == np.float64:
             result_agg[col_name] = result_agg[col_name].apply(lambda x: f"{x:,.2f}" if pd.notnull(x) else x)

    # Calculate summary totals
    total_novo_sum = pd.to_numeric(result_agg['Total IPTU Novo'].str.replace(',', ''), errors='coerce').sum()
    total_atual_trib_sum = pd.to_numeric(result_agg['Total IPTU Atual Tributado'].str.replace(',', ''), errors='coerce').sum()
    total_atual_calc_sum = pd.to_numeric(result_agg['Total IPTU Atual Calculado'].str.replace(',', ''), errors='coerce').sum()

    total_novo_str = f"Total IPTU Novo: {total_novo_sum:,.2f}"
    total_atual_trib_str = f"Total IPTU Atual Tributado: {total_atual_trib_sum:,.2f}"
    total_atual_calc_str = f"Total IPTU Atual Calculado: {total_atual_calc_sum:,.2f}"

    # === EXCEL FILE GENERATION ===
    filename_text = ""
    download_button_result = gr.DownloadButton(visible=False)
    
    try:
        # Collect all parameters for the Excel export
        all_parameters = [
            pg_lim1, pg_alq1, pg_lim2, pg_alq2, pg_lim3, pg_alq3, pg_lim4, pg_alq4, pg_lim5, pg_alq5, pg_lim6, pg_alq6, pg_lim7, pg_alq7, pg_alq8,
            pr_lim1, pr_alq1, pr_lim2, pr_alq2, pr_lim3, pr_alq3, pr_lim4, pr_alq4, pr_lim5, pr_alq5, pr_lim6, pr_alq6, pr_lim7, pr_alq7, pr_alq8,
            pnr_lim1, pnr_alq1, pnr_lim2, pnr_alq2, pnr_lim3, pnr_alq3, pnr_lim4, pnr_alq4, pnr_lim5, pnr_alq5, pnr_lim6, pnr_alq6, pnr_lim7, pnr_alq7, pnr_alq8,
            eg_lim1, eg_alq1, eg_lim2, eg_alq2, eg_lim3, eg_alq3, eg_lim4, eg_alq4, eg_lim5, eg_alq5, eg_lim6, eg_alq6, eg_lim7, eg_alq7, eg_alq8,
            er_lim1, er_alq1, er_lim2, er_alq2, er_lim3, er_alq3, er_lim4, er_alq4, er_lim5, er_alq5, er_lim6, er_alq6, er_lim7, er_alq7, er_alq8,
            enr_lim1, enr_alq1, enr_lim2, enr_alq2, enr_lim3, enr_alq3, enr_lim4, enr_alq4, enr_lim5, enr_alq5, enr_lim6, enr_alq6, enr_lim7, enr_alq7, enr_alq8,
            t1df_lim1, t1df_alq1, t1df_alq2,
            t2df_lim1, t2df_alq1, t2df_alq2,
            t3df_lim1, t3df_alq1, t3df_alq2,
            tae_alq1,
            taf_alq1
        ]
        
        excel_file_buffer = create_excel_download(
            df_resumo_iptu, result_agg, total_novo_str, total_atual_trib_str, total_atual_calc_str,
            valor_venal_choice, ufm_value_input, diferencia_estacionamentos_flag, diferencia_predios_flag, all_parameters
        )
        
        # Calculate file size
        file_size_bytes = len(excel_file_buffer.getvalue())
        if file_size_bytes < 1024 * 1024:  # Less than 1MB
            size_str = f"{file_size_bytes / 1024:.1f} KB"
        else:
            size_str = f"{file_size_bytes / (1024 * 1024):.1f} MB"
        
        # Create timestamp in YYYYMMDD_HHMM format
        # Define the São Paulo timezone
        sao_paulo_tz = pytz.timezone("America/Sao_Paulo")
        now_sao_paulo = datetime.now(sao_paulo_tz)
        timestamp = now_sao_paulo.strftime("%Y%m%d_%H%M")
        filename = f"resultados_iptu_{timestamp}.xlsx"
        
        # Save to temporary file
        try:
            # First try the standard temp directory
            temp_dir = tempfile.gettempdir()
            temp_file_path = os.path.join(temp_dir, filename)
            
            with open(temp_file_path, 'wb') as f:
                f.write(excel_file_buffer.getvalue())
            
            # Success - update UI components
            filename_text = filename
            download_button_result = gr.DownloadButton(
                label=f"Download ({size_str})", 
                value=temp_file_path, 
                visible=True
            )
            
        except (PermissionError, OSError):
            # If that fails, try current directory (for HF Spaces)
            with open(filename, 'wb') as f:
                f.write(excel_file_buffer.getvalue())
            
            # Success - update UI components  
            filename_text = filename
            download_button_result = gr.DownloadButton(
                label=f"Download ({size_str})", 
                value=filename, 
                visible=True
            )
            
    except Exception as e:
        print(f"Erro ao criar arquivo Excel: {str(e)}")
        filename_text = ""
        download_button_result = gr.DownloadButton(visible=False)
    
    return ("Processamento concluído.", df_resumo_iptu, result_agg, total_novo_str, total_atual_trib_str, total_atual_calc_str, 
            gr.Textbox(value=filename_text, visible=bool(filename_text)), download_button_result)

# Functions to handle field visibility
def update_parking_visibility(diferencia_estacionamentos):
    """Update visibility of parking fields based on differentiation checkbox"""
    if diferencia_estacionamentos:
        # Hide EG, show ER and ENR
        return [
            gr.Accordion(visible=False),  # EG
            gr.Accordion(visible=True),   # ER
            gr.Accordion(visible=True)    # ENR
        ]
    else:
        # Show EG, hide ER and ENR
        return [
            gr.Accordion(visible=True),   # EG
            gr.Accordion(visible=False),  # ER
            gr.Accordion(visible=False)   # ENR
        ]

def update_building_visibility(diferencia_predios):
    """Update visibility of building fields based on differentiation checkbox"""
    if diferencia_predios:
        # Hide PG, show PR and PNR
        return [
            gr.Accordion(visible=False),  # PG
            gr.Accordion(visible=True),   # PR
            gr.Accordion(visible=True)    # PNR
        ]
    else:
        # Show PG, hide PR and PNR
        return [
            gr.Accordion(visible=True),   # PG
            gr.Accordion(visible=False),  # PR
            gr.Accordion(visible=False)   # PNR
        ]

# --- Gradio Interface ---
with gr.Blocks(theme=gr.themes.Soft()) as demo:
    gr.Markdown("# Simulador de Cálculo de IPTU")
    gr.Markdown(f"Ajuste os parâmetros abaixo.")

    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("### Parâmetros Gerais")
            valor_venal_dropdown = gr.Dropdown(choices=["VV_90", "VV_85", "VV_80", "VV_90_RED", "VV_85_RED", "VV_80_RED"], value="VV_90", label="Valor Venal Utilizado")
            ufm_input = gr.Number(value=5.771, label="Valor da UFM (2025)")
            diferencia_estacionamentos_check = gr.Checkbox(value=False, label="Diferenciar Estacionamentos por Uso?")
            diferencia_predios_check = gr.Checkbox(value=False, label="Diferenciar Prédios por Uso?")
            
            # Import functionality
            gr.Markdown("### 📥 Importar Configurações")
            gr.Markdown("*Faça upload de um arquivo Excel gerado anteriormente para restaurar todas as configurações*")
            
            with gr.Group():
                with gr.Row():
                    import_file = gr.File(
                        label="Selecionar arquivo Excel", 
                        file_types=[".xlsx"], 
                        file_count="single",
                        height=200
                    )
                with gr.Row():
                    import_button = gr.Button("🔄 Importar Parâmetros", variant="secondary", size="lg", scale=2)
                    clear_button = gr.Button("🗑️ Limpar", variant="outline", size="lg", scale=1)
                
                import_status = gr.Textbox(
                    label="Status da Importação", 
                    interactive=False, 
                    visible=False,
                    lines=2
                )
            
            gr.Markdown("### Faixas e Alíquotas Configuráveis")
            all_rate_inputs = []

            pg_defaults_lim = [25000, 60000, 100000, 140000, 200000, 300000, 600000]
            pg_defaults_aliq = [0.0, 0.004, 0.0047, 0.0055, 0.0062, 0.007, 0.0077, 0.0085]
            
            # Create accordions with visibility control
            with gr.Accordion("Predial Geral (PG)", open=False, visible=True) as pg_accordion:
                pg_inputs = create_8_band_inputs("PG", pg_defaults_lim, pg_defaults_aliq)
                all_rate_inputs.extend(pg_inputs)
            
            with gr.Accordion("Predial Residencial (PR)", open=False, visible=False) as pr_accordion:
                pr_inputs = create_8_band_inputs("PR", pg_defaults_lim, pg_defaults_aliq)
                all_rate_inputs.extend(pr_inputs)

            with gr.Accordion("Predial Não Residencial (PNR)", open=False, visible=False) as pnr_accordion:
                pnr_inputs = create_8_band_inputs("PNR", pg_defaults_lim, pg_defaults_aliq)
                all_rate_inputs.extend(pnr_inputs)

            with gr.Accordion("Estacionamentos Geral (EG)", open=False, visible=True) as eg_accordion:
                eg_inputs = create_8_band_inputs("EG", pg_defaults_lim, pg_defaults_aliq)
                all_rate_inputs.extend(eg_inputs)

            with gr.Accordion("Estacionamentos Residenciais (ER)", open=False, visible=False) as er_accordion:
                er_inputs = create_8_band_inputs("ER", pg_defaults_lim, pg_defaults_aliq)
                all_rate_inputs.extend(er_inputs)

            with gr.Accordion("Estacionamentos Não Residenciais (ENR)", open=False, visible=False) as enr_accordion:
                enr_inputs = create_8_band_inputs("ENR", pg_defaults_lim, pg_defaults_aliq)
                all_rate_inputs.extend(enr_inputs)
            
            t_df_defaults_lim = 15000
            with gr.Accordion("Terrenos 1a DF (T1DF)", open=False) as t1df_accordion:
                t1df_inputs = create_2_band_inputs("T1DF", t_df_defaults_lim, [0.0, 0.03])
                all_rate_inputs.extend(t1df_inputs)
            
            with gr.Accordion("Terrenos 2a DF (T2DF)", open=False) as t2df_accordion:
                t2df_inputs = create_2_band_inputs("T2DF", t_df_defaults_lim, [0.0, 0.02])
                all_rate_inputs.extend(t2df_inputs)

            with gr.Accordion("Terrenos 3a DF (T3DF)", open=False) as t3df_accordion:
                t3df_inputs = create_2_band_inputs("T3DF", t_df_defaults_lim, [0.0, 0.01])
                all_rate_inputs.extend(t3df_inputs)

            # TAE and TAF are always hidden as requested
            with gr.Accordion("Terrenos Alíquota Especial (TAE)", open=False, visible=False) as tae_accordion:
                tae_alq1_input = gr.Number(label="TAE Alíquota 1 (ex: 0.009)", value=0.009)
                all_rate_inputs.append(tae_alq1_input)

            with gr.Accordion("Terrenos Alíquota Fixa (TAF)", open=False, visible=False) as taf_accordion:
                taf_alq1_input = gr.Number(label="TAF Alíquota 1 (ex: 0.0095)", value=0.0095)
                all_rate_inputs.append(taf_alq1_input)

            process_button = gr.Button("Processar Dados", variant="primary")

        with gr.Column(scale=2):
            status_message = gr.Textbox(label="Status", interactive=False)
            gr.Markdown("### Resumo Detalhado por Faixa e Categoria")
            output_df_resumo = gr.DataFrame(label="Resumo por Faixa", wrap=True)
            gr.Markdown("### Resumo Agregado por Categoria")
            output_df_result = gr.DataFrame(label="Resumo Agregado", wrap=True)
            
            gr.Markdown("### Totais Gerais Calculados")
            total_novo_text = gr.Textbox(interactive=False)
            total_atual_trib_text = gr.Textbox(interactive=False)
            total_atual_calc_text = gr.Textbox(interactive=False)
            
            # Add download section
            gr.Markdown("### Download Resultados")
            filename_display = gr.Textbox(label="Arquivo gerado", interactive=False, visible=False)
            download_btn = gr.DownloadButton(label="Download", visible=False)

    # Set up visibility change handlers
    diferencia_estacionamentos_check.change(
        fn=update_parking_visibility,
        inputs=[diferencia_estacionamentos_check],
        outputs=[eg_accordion, er_accordion, enr_accordion]
    )
    
    diferencia_predios_check.change(
        fn=update_building_visibility,
        inputs=[diferencia_predios_check],
        outputs=[pg_accordion, pr_accordion, pnr_accordion]
    )

    click_inputs = [
        valor_venal_dropdown, ufm_input, 
        diferencia_estacionamentos_check, diferencia_predios_check
    ] + all_rate_inputs

    # Import function with improved feedback
    def import_parameters(file_path):
        """Import parameters from Excel file with better feedback"""
        if not file_path:
            return [gr.update() for _ in range(len(all_rate_inputs) + 5)]  # +5 for new status field
        
        try:
            # Read the parameters sheet
            df_params = pd.read_excel(file_path, sheet_name='Parâmetros Utilizados')
            
            # Extract general parameters
            valor_venal = df_params[df_params['Parâmetro'] == 'Valor Venal Utilizado']['Valor'].iloc[0]
            ufm_value = float(df_params[df_params['Parâmetro'] == 'Valor da UFM']['Valor'].iloc[0])
            diferencia_est = df_params[df_params['Parâmetro'] == 'Diferenciar Estacionamentos por Uso']['Valor'].iloc[0] == 'Sim'
            diferencia_pred = df_params[df_params['Parâmetro'] == 'Diferenciar Prédios por Uso']['Valor'].iloc[0] == 'Sim'
            
            # Extract all parameter values in order
            param_patterns = [
                # PG (15 params)
                ['PG Limite 1 (UFM)', 'PG Alíquota 1', 'PG Limite 2 (UFM)', 'PG Alíquota 2', 'PG Limite 3 (UFM)', 'PG Alíquota 3',
                 'PG Limite 4 (UFM)', 'PG Alíquota 4', 'PG Limite 5 (UFM)', 'PG Alíquota 5', 'PG Limite 6 (UFM)', 'PG Alíquota 6',
                 'PG Limite 7 (UFM)', 'PG Alíquota 7', 'PG Alíquota 8'],
                # PR (15 params)
                ['PR Limite 1 (UFM)', 'PR Alíquota 1', 'PR Limite 2 (UFM)', 'PR Alíquota 2', 'PR Limite 3 (UFM)', 'PR Alíquota 3',
                 'PR Limite 4 (UFM)', 'PR Alíquota 4', 'PR Limite 5 (UFM)', 'PR Alíquota 5', 'PR Limite 6 (UFM)', 'PR Alíquota 6',
                 'PR Limite 7 (UFM)', 'PR Alíquota 7', 'PR Alíquota 8'],
                # PNR (15 params)
                ['PNR Limite 1 (UFM)', 'PNR Alíquota 1', 'PNR Limite 2 (UFM)', 'PNR Alíquota 2', 'PNR Limite 3 (UFM)', 'PNR Alíquota 3',
                 'PNR Limite 4 (UFM)', 'PNR Alíquota 4', 'PNR Limite 5 (UFM)', 'PNR Alíquota 5', 'PNR Limite 6 (UFM)', 'PNR Alíquota 6',
                 'PNR Limite 7 (UFM)', 'PNR Alíquota 7', 'PNR Alíquota 8'],
                # EG (15 params)
                ['EG Limite 1 (UFM)', 'EG Alíquota 1', 'EG Limite 2 (UFM)', 'EG Alíquota 2', 'EG Limite 3 (UFM)', 'EG Alíquota 3',
                 'EG Limite 4 (UFM)', 'EG Alíquota 4', 'EG Limite 5 (UFM)', 'EG Alíquota 5', 'EG Limite 6 (UFM)', 'EG Alíquota 6',
                 'EG Limite 7 (UFM)', 'EG Alíquota 7', 'EG Alíquota 8'],
                # ER (15 params)
                ['ER Limite 1 (UFM)', 'ER Alíquota 1', 'ER Limite 2 (UFM)', 'ER Alíquota 2', 'ER Limite 3 (UFM)', 'ER Alíquota 3',
                 'ER Limite 4 (UFM)', 'ER Alíquota 4', 'ER Limite 5 (UFM)', 'ER Alíquota 5', 'ER Limite 6 (UFM)', 'ER Alíquota 6',
                 'ER Limite 7 (UFM)', 'ER Alíquota 7', 'ER Alíquota 8'],
                # ENR (15 params)
                ['EN Limite 1 (UFM)', 'EN Alíquota 1', 'EN Limite 2 (UFM)', 'EN Alíquota 2', 'EN Limite 3 (UFM)', 'EN Alíquota 3',
                 'EN Limite 4 (UFM)', 'EN Alíquota 4', 'EN Limite 5 (UFM)', 'EN Alíquota 5', 'EN Limite 6 (UFM)', 'EN Alíquota 6',
                 'EN Limite 7 (UFM)', 'EN Alíquota 7', 'EN Alíquota 8'],
                # T1DF (3 params)
                ['T1DF Limite 1 (UFM)', 'T1DF Alíquota 1', 'T1DF Alíquota 2'],
                # T2DF (3 params)
                ['T2DF Limite 1 (UFM)', 'T2DF Alíquota 1', 'T2DF Alíquota 2'],
                # T3DF (3 params)
                ['T3DF Limite 1 (UFM)', 'T3DF Alíquota 1', 'T3DF Alíquota 2'],
                # TAE (1 param)
                ['TAE Alíquota 1'],
                # TAF (1 param)
                ['TAF Alíquota 1']
            ]
            
            # Flatten the patterns list
            all_param_names = []
            for group in param_patterns:
                all_param_names.extend(group)
            
            # Extract values for each parameter
            param_values = []
            missing_params = []
            for param_name in all_param_names:
                try:
                    value = df_params[df_params['Parâmetro'] == param_name]['Valor'].iloc[0]
                    param_values.append(float(value) if pd.notnull(value) else 0.0)
                except (IndexError, ValueError):
                    param_values.append(0.0)  # Default value if not found
                    missing_params.append(param_name)
            
            # Create success message
            if missing_params:
                status_msg = f"✅ Importação concluída com avisos!\n⚠️ {len(missing_params)} parâmetros não encontrados (valores padrão aplicados)"
            else:
                status_msg = f"✅ Importação concluída com sucesso!\n📊 {len(param_values)} parâmetros importados"
            
            # Return updates for all components
            updates = [
                gr.update(value=valor_venal),      # valor_venal_dropdown
                gr.update(value=ufm_value),        # ufm_input
                gr.update(value=diferencia_est),   # diferencia_estacionamentos_check
                gr.update(value=diferencia_pred),  # diferencia_predios_check
                gr.update(value=status_msg, visible=True)  # import_status
            ]
            
            # Add updates for all rate inputs
            for i, value in enumerate(param_values):
                if i < len(all_rate_inputs):
                    updates.append(gr.update(value=value))
                else:
                    break
            
            # Pad with no-change updates if needed
            while len(updates) < len(all_rate_inputs) + 5:
                updates.append(gr.update())
            
            return updates
            
        except Exception as e:
            error_msg = f"❌ Erro na importação:\n{str(e)}"
            updates = [
                gr.update(),  # valor_venal_dropdown - no change
                gr.update(),  # ufm_input - no change
                gr.update(),  # diferencia_estacionamentos_check - no change
                gr.update(),  # diferencia_predios_check - no change
                gr.update(value=error_msg, visible=True)  # import_status
            ]
            # Add no-change updates for all rate inputs
            updates.extend([gr.update() for _ in range(len(all_rate_inputs))])
            return updates

    # Clear function
    def clear_all_parameters():
        """Reset all parameters to default values"""
        pg_defaults_lim = [25000, 60000, 100000, 140000, 200000, 300000, 600000]
        pg_defaults_aliq = [0.0, 0.004, 0.0047, 0.0055, 0.0062, 0.007, 0.0077, 0.0085]
        t_df_defaults_lim = 15000
        
        # Default values for all parameters
        default_values = []
        # PG (15 params)
        for i in range(7):
            default_values.extend([pg_defaults_lim[i], pg_defaults_aliq[i]])
        default_values.append(pg_defaults_aliq[7])
        # PR (15 params) - same as PG
        for i in range(7):
            default_values.extend([pg_defaults_lim[i], pg_defaults_aliq[i]])
        default_values.append(pg_defaults_aliq[7])
        # PNR (15 params) - same as PG
        for i in range(7):
            default_values.extend([pg_defaults_lim[i], pg_defaults_aliq[i]])
        default_values.append(pg_defaults_aliq[7])
        # EG (15 params) - same as PG
        for i in range(7):
            default_values.extend([pg_defaults_lim[i], pg_defaults_aliq[i]])
        default_values.append(pg_defaults_aliq[7])
        # ER (15 params) - same as PG
        for i in range(7):
            default_values.extend([pg_defaults_lim[i], pg_defaults_aliq[i]])
        default_values.append(pg_defaults_aliq[7])
        # ENR (15 params) - same as PG
        for i in range(7):
            default_values.extend([pg_defaults_lim[i], pg_defaults_aliq[i]])
        default_values.append(pg_defaults_aliq[7])
        # T1DF (3 params)
        default_values.extend([t_df_defaults_lim, 0.0, 0.03])
        # T2DF (3 params)
        default_values.extend([t_df_defaults_lim, 0.0, 0.02])
        # T3DF (3 params)
        default_values.extend([t_df_defaults_lim, 0.0, 0.01])
        # TAE (1 param)
        default_values.append(0.009)
        # TAF (1 param)
        default_values.append(0.0095)
        
        updates = [
            gr.update(value="VV_90"),      # valor_venal_dropdown
            gr.update(value=5.771),        # ufm_input
            gr.update(value=False),        # diferencia_estacionamentos_check
            gr.update(value=False),        # diferencia_predios_check
            gr.update(value="🔄 Parâmetros resetados para valores padrão", visible=True)  # import_status
        ]
        
        # Add updates for all rate inputs
        for i, value in enumerate(default_values):
            if i < len(all_rate_inputs):
                updates.append(gr.update(value=value))
            else:
                break
        
        # Pad with no-change updates if needed
        while len(updates) < len(all_rate_inputs) + 5:
            updates.append(gr.update())
        
        return updates

    # Set up import and clear button clicks
    import_button.click(
        fn=import_parameters,
        inputs=[import_file],
        outputs=[valor_venal_dropdown, ufm_input, diferencia_estacionamentos_check, diferencia_predios_check, import_status] + all_rate_inputs
    )
    
    clear_button.click(
        fn=clear_all_parameters,
        inputs=[],
        outputs=[valor_venal_dropdown, ufm_input, diferencia_estacionamentos_check, diferencia_predios_check, import_status] + all_rate_inputs
    )

    process_button.click(
        fn=process_iptu_data,
        inputs=click_inputs,
        outputs=[status_message, output_df_resumo, output_df_result, 
                 total_novo_text, total_atual_trib_text, total_atual_calc_text, filename_display, download_btn]
    )
    
    gr.Markdown(f"""
    ## 📋 Instruções:
    
    ### 🎯 Fluxo Básico:
    1. **⚙️ Parâmetros Gerais**: Configure valor venal, UFM e flags de diferenciação
    2. **📊 Faixas e Alíquotas**: Ajuste limites (em UFM) e alíquotas (ex: 0.004 = 0.4%)
    3. **▶️ Processar**: Clique em "Processar Dados" para calcular
    4. **💾 Download**: Baixe os resultados completos em Excel
    
    ### 🔄 Import/Export de Configurações:
    - **📥 Importar**: Faça upload de arquivo Excel gerado anteriormente
    - **🗑️ Limpar**: Reset todos os parâmetros para valores padrão  
    
    ### 📊 Conteúdo do Excel:
    - **📈 Resumo Detalhado**: Dados por faixa e categoria
    - **📋 Resumo Agregado**: Totais por categoria principal  
    - **💰 Totais Gerais**: Sumário dos valores calculados
    - **⚙️ Parâmetros Utilizados**: Configurações completas (reimportáveis)
    
    ### 🎛️ Controles de Visibilidade:
    - **Estacionamentos**: Marque "Diferenciar por Uso" para mostrar campos ER/ENR em vez de EG
    - **Prédios**: Marque "Diferenciar por Uso" para mostrar campos PR/PNR em vez de PG
    - **TAE/TAF**: Campos sempre ocultos (configurados internamente)
    """)

if __name__ == "__main__":
    demo.launch()