File size: 41,822 Bytes
12bee28
 
0d8c70b
 
 
 
12bee28
 
 
 
 
 
 
 
0d8c70b
12bee28
c2627ee
 
 
 
 
12bee28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d8c70b
12bee28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efb09de
12bee28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d8c70b
12bee28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efb09de
12bee28
 
 
 
0d8c70b
 
 
 
 
 
 
 
 
12bee28
 
 
 
 
 
 
0d8c70b
 
 
12bee28
0d8c70b
 
12bee28
0d8c70b
 
12bee28
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12bee28
0d8c70b
c2627ee
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2627ee
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2627ee
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2627ee
b2d3316
c2627ee
b2d3316
efb09de
 
 
b2d3316
efb09de
 
 
 
 
 
 
 
b2d3316
 
efb09de
 
 
 
 
 
 
b2d3316
 
efb09de
 
 
 
 
b2d3316
 
 
efb09de
 
b2d3316
 
efb09de
 
 
b2d3316
 
efb09de
 
 
b2d3316
efb09de
b2d3316
efb09de
 
 
b2d3316
 
 
efb09de
 
 
b2d3316
efb09de
 
 
 
 
b2d3316
 
 
 
efb09de
 
 
 
 
 
 
b2d3316
 
efb09de
b2d3316
 
efb09de
 
 
 
b2d3316
efb09de
 
 
 
 
 
b2d3316
 
efb09de
b2d3316
efb09de
 
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efb09de
 
 
 
 
 
b2d3316
 
 
efb09de
 
 
 
b2d3316
efb09de
 
 
 
 
 
 
 
 
 
 
 
 
 
b2d3316
 
 
 
efb09de
 
 
 
 
b2d3316
 
 
efb09de
 
 
 
b2d3316
efb09de
b2d3316
 
 
 
 
 
 
efb09de
 
 
 
 
b2d3316
 
 
 
 
 
 
 
 
 
 
 
efb09de
 
 
 
 
 
b2d3316
 
efb09de
b2d3316
 
efb09de
 
 
 
b2d3316
efb09de
 
32556ed
efb09de
b2d3316
efb09de
b2d3316
 
efb09de
b2d3316
 
32556ed
 
 
 
 
 
 
 
 
efb09de
 
 
 
 
 
b2d3316
 
efb09de
b2d3316
 
efb09de
 
 
 
b2d3316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efb09de
 
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efb09de
 
 
 
 
 
b2d3316
efb09de
 
 
 
b2d3316
efb09de
 
 
b2d3316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efb09de
 
 
b2d3316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2627ee
 
 
0d8c70b
 
 
 
b2d3316
 
 
0d8c70b
b2d3316
 
 
 
 
 
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
 
 
b2d3316
0d8c70b
 
 
 
 
b2d3316
 
0d8c70b
 
 
b2d3316
 
 
0d8c70b
 
 
b2d3316
 
 
0d8c70b
b2d3316
0d8c70b
 
 
b2d3316
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d8c70b
b2d3316
0d8c70b
c2627ee
0d8c70b
 
efb09de
 
0d8c70b
efb09de
 
 
 
0d8c70b
efb09de
0d8c70b
 
efb09de
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2627ee
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efb09de
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
c617332
0d8c70b
 
 
b2d3316
 
 
0d8c70b
 
 
c2627ee
efb09de
 
 
 
0d8c70b
 
efb09de
0d8c70b
efb09de
 
 
 
b2d3316
efb09de
 
 
 
0d8c70b
 
c2627ee
0d8c70b
 
 
 
 
 
 
 
 
 
 
c2627ee
0d8c70b
 
efb09de
 
0d8c70b
 
c2627ee
0d8c70b
 
 
 
 
 
 
 
efb09de
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efb09de
c2627ee
0d8c70b
 
c2627ee
 
0d8c70b
 
c2627ee
0d8c70b
 
 
efb09de
 
0d8c70b
efb09de
 
 
 
 
 
c617332
efb09de
 
 
0d8c70b
c2627ee
efb09de
0d8c70b
efb09de
0d8c70b
 
 
c2627ee
24d01fd
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c617332
0d8c70b
 
 
 
 
 
 
efb09de
 
24d01fd
efb09de
b2d3316
efb09de
 
 
0d8c70b
c2627ee
24d01fd
efb09de
b2d3316
efb09de
 
0d8c70b
 
efb09de
c2627ee
0d8c70b
efb09de
 
 
 
 
 
0d8c70b
efb09de
c2627ee
0d8c70b
b2d3316
 
 
 
 
 
0d8c70b
b2d3316
 
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efb09de
0d8c70b
 
 
 
 
 
 
 
 
efb09de
0d8c70b
 
 
 
 
 
 
 
 
 
efb09de
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efb09de
0d8c70b
 
 
efb09de
c2627ee
0d8c70b
 
 
 
 
 
 
 
 
 
 
efb09de
0d8c70b
efb09de
0d8c70b
 
 
 
 
 
 
b2d3316
0d8c70b
 
 
 
 
12bee28
c2627ee
0d8c70b
 
 
 
 
 
 
 
 
 
 
efb09de
c2627ee
0d8c70b
 
 
 
c617332
0d8c70b
 
 
 
c617332
0d8c70b
c617332
0d8c70b
 
 
 
c617332
0d8c70b
 
efb09de
c2627ee
 
b2d3316
 
 
 
 
0d8c70b
12bee28
c2627ee
b2d3316
c2627ee
 
b2d3316
 
 
 
 
0d8c70b
b2d3316
 
 
 
 
 
 
 
 
 
0d8c70b
12bee28
efb09de
0d8c70b
 
 
b2d3316
0d8c70b
 
 
b2d3316
 
12bee28
c2627ee
0d8c70b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12bee28
0d8c70b
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
import requests
import yaml
import json
import zipfile
import io
import tempfile
from identityNow import handle_identitynow_call
from okta import handle_okta_call
from iiq import handle_iiq_call
from utils import extract_path_params, extract_query_params
import gradio as gr
import os
from dotenv import load_dotenv
from pathlib import Path
from api_schema_generatorV5 import ApiSchemaGeneratorV5

# Load environment variables
script_dir = Path(__file__).resolve().parent
env_path = script_dir / '.env'
load_dotenv(dotenv_path=env_path)

def fetch_api_endpoints_yaml(spec_url):
    try:
        response = requests.get(spec_url)
        response.raise_for_status()
        content = response.text
        api_spec = yaml.safe_load(content)
    except Exception as e:
        print(f"Error fetching/parsing YAML spec from {spec_url}: {e}")
        return {}
    
    endpoints = {}
    if "paths" not in api_spec:
        print("No endpoints found in the specification.")
        return {}
    
    valid_methods = ['get', 'post']  # Only process GET and POST endpoints
    for path, methods in api_spec["paths"].items():
        endpoints[path] = {}
        if not methods or not isinstance(methods, dict):
            continue
        
        common_params = methods.get("parameters", [])
        for method, details in methods.items():
            if method.lower() not in valid_methods:
                continue
            
            method_params = details.get("parameters", [])
            all_params = common_params + method_params
            endpoint_info = {
                "summary": details.get("summary", ""),
                "description": details.get("description", ""),
                "parameters": all_params
            }
            endpoints[path][method.lower()] = endpoint_info
    return endpoints

def fetch_api_endpoints_json(spec_url):
    try:
        response = requests.get(spec_url)
        response.raise_for_status()
        api_spec = response.json()
    except Exception as e:
        print(f"Error fetching/parsing JSON spec from {spec_url}: {e}")
        return {}
    
    endpoints = {}
    if "paths" not in api_spec:
        print("No endpoints found in the specification.")
        return {}
    
    valid_methods = ['get', 'post']  # Only process GET and POST endpoints
    for path, methods in api_spec["paths"].items():
        endpoints[path] = {}
        if not methods or not isinstance(methods, dict):
            continue
        
        common_params = methods.get("parameters", [])
        for method, details in methods.items():
            if method.lower() not in valid_methods:
                continue
            
            method_params = details.get("parameters", [])
            all_params = common_params + method_params
            endpoint_info = {
                "summary": details.get("summary", ""),
                "description": details.get("description", ""),
                "parameters": all_params
            }
            endpoints[path][method.lower()] = endpoint_info
    return endpoints

def get_endpoints(spec_choice, base_url=None):
    # If base_url is provided, use it directly
    if base_url:
        spec_url = base_url
        if "JSON" in spec_choice:
            return fetch_api_endpoints_json(spec_url), spec_url
        return fetch_api_endpoints_yaml(spec_url), spec_url
    
    # Otherwise, try to use environment variables as fallback
    api_spec_options = {
        "Okta (JSON)": os.getenv("OKTA_API_SPEC"),
        "SailPoint IdentityNow (YAML)": os.getenv("IDENTITY_NOW_API_SPEC"),
        "Sailpoint IIQ (YAML)": os.getenv("IIQ_API_SPEC")
    }
    spec_url = api_spec_options.get(spec_choice)
    if not spec_url:
        print(f"No API specification URL found for {spec_choice}")
        return {}, None
    
    if "JSON" in spec_choice:
        return fetch_api_endpoints_json(spec_url), spec_url
    return fetch_api_endpoints_yaml(spec_url), spec_url

def group_endpoints(endpoints, spec_choice, endpoint_type='get'):
    """Group endpoints by their first path segment, filtering by endpoint type"""
    groups = {}
    if endpoint_type == 'all':
        # For 'all' type, include all endpoints regardless of method
        if spec_choice == "Okta (JSON)":
            for path, methods in endpoints.items():
                clean_path = path.replace('/api/v1/', '')
                segments = clean_path.strip("/").split("/")
                group_key = segments[0] if segments else "other"
                if group_key not in groups:
                    groups[group_key] = {}
                groups[group_key][path] = methods
        else:
            for path, methods in endpoints.items():
                segments = path.strip("/").split("/")
                group_key = segments[0] if segments[0] != "" else "other"
                if group_key not in groups:
                    groups[group_key] = {}
                groups[group_key][path] = methods
    else:
        # For specific method types (get, post)
        if spec_choice == "Okta (JSON)":
            for path, methods in endpoints.items():
                if endpoint_type not in methods:
                    continue
                    
                clean_path = path.replace('/api/v1/', '')
                segments = clean_path.strip("/").split("/")
                group_key = segments[0] if segments else "other"
                if group_key not in groups:
                    groups[group_key] = {}
                groups[group_key][path] = methods
        else:
            for path, methods in endpoints.items():
                if endpoint_type not in methods:
                    continue
                    
                segments = path.strip("/").split("/")
                group_key = segments[0] if segments[0] != "" else "other"
                if group_key not in groups:
                    groups[group_key] = {}
                groups[group_key][path] = methods
    return groups

def generate_schema_files(api_choice_val, selected_endpoints, api_spec_url, custom_name=None):
    """Generate JSON and XML schema files for selected endpoints"""
    # Determine API name based on choice
    if api_choice_val == "Others" and custom_name:
        api_name = custom_name.lower().replace(" ", "_")
    else:
        api_name = api_choice_val.split(" (")[0].lower().replace(" ", "_")
    
    # Debug print to verify api_spec_url is not empty
    print(f"API Choice: {api_choice_val}")
    print(f"API Spec URL: {api_spec_url}")
    print(f"Selected endpoints count: {len(selected_endpoints)}")
    print(f"Using API name: {api_name}")
    
    # Create schema generator with path+method pairs
    generator = ApiSchemaGeneratorV5(api_spec_url, api_name=api_name, selected_endpoints=selected_endpoints)
    
    # Generate files in memory
    meta_data = generator.generate_datasource_plugin_meta()
    schema_xml = generator.generate_default_schema()
    
    # Create JSON string
    json_str = json.dumps(meta_data, indent=2)
    
    # Create a zip file in memory
    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
        zip_file.writestr(f"{api_name}_datasource_plugin_meta.json", json_str)
        zip_file.writestr(f"{api_name}_default_schema.orx", schema_xml)
    
    zip_buffer.seek(0)
    
    # Return both the individual files and the zip
    return {
        "json": json_str,
        "xml": schema_xml,
        "zip": zip_buffer
    }

def update_api_url(api_choice_val):
    global current_api_spec_url
    
    if api_choice_val == "Others":
        # For "Others", we don't set a URL yet - user will input it
        current_api_spec_url = ""
        return gr.update(visible=True), gr.update(value=""), gr.update(value="")
    
    # Get URL from environment variables
    api_spec_options = {
        "Okta (JSON)": os.getenv("OKTA_API_SPEC"),
        "SailPoint IdentityNow (YAML)": os.getenv("IDENTITY_NOW_API_SPEC"),
        "Sailpoint IIQ (YAML)": os.getenv("IIQ_API_SPEC")
    }
    
    url = api_spec_options.get(api_choice_val, "")
    print(f"Setting API spec URL to: {url}")  # Debug print
    
    # Update the global variable
    current_api_spec_url = url
    
    return gr.update(visible=False), gr.update(value=url), gr.update(value=url)  # Update both text field and state

# ----------------------------- CSS -----------------------------
custom_css = """
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css');

body, .gradio-container {
    font-family: 'Roboto', sans-serif;
    background: #f3f3f3;
    color: #333;
    margin: 0;
    padding: 0;
}

.title {
    text-align: center;
    margin: 40px 0;
    font-size: 2.5em;
    color: #222;
    animation: fadeIn 1s ease-in;
}

.api-cards {
    display: flex;
    justify-content: center;
    gap: 30px;
    margin-bottom: 40px;
    animation: slideUp 0.5s ease-out;
}

.api-card {
    background: white;
    padding: 30px;
    border-radius: 15px;
    box-shadow: 0 6px 12px rgba(0,0,0,0.1);
    text-align: center;
    cursor: pointer;
    transition: transform 0.3s, box-shadow 0.3s;
    width: 220px;
}

.api-card:hover {
    transform: translateY(-10px);
    box-shadow: 0 8px 16px rgba(0,0,0,0.15);
}

.api-card i {
    font-size: 40px;
    color: #007BFF;
    margin-bottom: 15px;
}

.api-card h2 {
    font-size: 20px;
    margin: 15px 0;
    font-weight: 500;
}

.api-card p {
    font-size: 16px;
    color: #666;
}

.cred-section {
    background: white;
    padding: 30px;
    border-radius: 15px;
    box-shadow: 0 6px 12px rgba(0,0,0,0.1);
    margin-bottom: 30px;
    animation: fadeIn 0.5s ease-in;
}

.action-btn {
    background-color: #007BFF;
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 8px;
    cursor: pointer;
    transition: background-color 0.3s, transform 0.2s;
    font-size: 16px;
}

.action-btn:hover {
    background-color: #0056b3;
    transform: translateY(-2px);
}

.loading-spinner {
    border: 4px solid #f3f3f3;
    border-top: 4px solid #3498db;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    animation: spin 1s linear infinite;
    margin: 20px auto;
}

.loading-text {
    color: black;
    font-size: 24px;
    font-weight: bold;
    margin-top: 20px;
    text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.8);
}

.fetch-loading-indicator {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100px;
}

.fetch-loading-indicator .loading-spinner {
    border-width: 6px;
    width: 50px;
    height: 50px;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.success-message, .error-message {
    padding: 15px;
    border-radius: 8px;
    margin-top: 15px;
    display: flex;
    align-items: center;
    gap: 10px;
    animation: slideIn 0.3s ease-out;
    font-size: 16px;
}

.success-message {
    background: #d4edda;
    color: #155724;
}

.error-message {
    background: #f8d7da;
    color: #721c24;
}

.endpoints-section, .param-group, .fetch-section, .results-section {
    background: white;
    padding: 30px;
    border-radius: 15px;
    box-shadow: 0 6px 12px rgba(0,0,0,0.1);
    margin-bottom: 30px;
    animation: fadeIn 0.5s ease-in;
}

.custom-accordion {
    border: 1px solid #ddd;
    border-radius: 8px;
    margin-bottom: 15px;
    transition: all 0.3s ease;
}

.custom-accordion .gr-accordion-header {
    background: #f9f9f9;
    padding: 15px;
    cursor: pointer;
    font-weight: 500;
    font-size: 18px;
    transition: background-color 0.3s;
}

.custom-accordion .gr-accordion-header:hover {
    background-color: #e9ecef;
}

.custom-checkbox .gr-checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 15px;
}

.custom-checkbox .gr-checkbox-group label {
    font-size: 16px;
    color: #333;
    transition: color 0.3s;
}

.custom-checkbox .gr-checkbox-group label:hover {
    color: #007BFF;
}

.reset-btn {
    background-color: #6c757d;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 8px;
    cursor: pointer;
    transition: background-color 0.3s, transform 0.2s;
    font-size: 16px;
}

.reset-btn:hover:enabled {
    background-color: #5a6268;
    transform: translateY(-2px);
}

.gr-code {
    background: #f9f9f9;
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 8px;
    max-height: 500px;
    overflow: auto;
    font-family: 'Courier New', monospace;
    font-size: 14px;
    white-space: pre-wrap;
    word-wrap: break-word;
}

.gr-code pre {
    margin: 0;
    padding: 0;
    white-space: pre-wrap;
    word-wrap: break-word;
}

.download-btn {
    background-color: #28a745;
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 8px;
    cursor: pointer;
    transition: background-color 0.3s, transform 0.2s;
    font-size: 16px;
}

.download-btn:hover {
    background-color: #218838;
    transform: translateY(-2px);
}

.banner {
    background-color: #007BFF;
    color: white;
    padding: 25px;
    text-align: center;
    font-size: 28px;
    font-weight: 500;
    margin-bottom: 30px;
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.param-item {
    background: #f9f9f9;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 15px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.param-group .gr-textbox {
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 10px;
    font-size: 16px;
    transition: border-color 0.3s;
}

.param-group .gr-textbox:focus {
    border-color: #007BFF;
    box-shadow: 0 0 5px rgba(0,123,255,0.5);
}

.fetch-loading-indicator {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100px;
}

.fetch-loading-indicator .loading-spinner {
    border-width: 6px;
    width: 50px;
    height: 50px;
}

.endpoint-type-selector {
    margin-bottom: 20px;
    padding: 15px;
    background: #333333;
    border-radius: 8px;
    border: 1px solid #ddd;
}

.endpoint-type-selector label {
    color: white !important;
    font-weight: bold !important;
    font-size: 18px !important;
}

.endpoint-type-selector > .block > label:first-child {
    color: #000000;
    font-weight: 700;
    font-size: 18px;
}

.endpoint-type-selector .gr-radio-group label {
    color: white;
    font-weight: 500;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes slideUp {
    from { transform: translateY(30px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}

@keyframes slideIn {
    from { transform: translateX(-30px); opacity: 0; }
    to { transform: translateX(0); opacity: 1; }
}

.user-guide-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.6);
    z-index: 9998;
    transition: all 0.5s ease;
}

.user-guide-modal {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #ffffff;
    color: #333333;
    padding: 35px;
    border-radius: 10px;
    box-shadow: 0 10px 25px rgba(0,0,0,0.2);
    width: 80%;
    max-width: 650px;
    max-height: 80vh;
    overflow-y: auto;
    z-index: 9999;
    transition: all 0.5s ease;
    font-family: 'Roboto', sans-serif;
    font-size: 16px;
    line-height: 1.6;
}

.user-guide-modal h2,
.user-guide-modal h3,
.user-guide-modal p,
.user-guide-modal ul,
.user-guide-modal li {
    color: #333333;
}

.user-guide-modal h2 {
    color: #1a1a1a;
    font-size: 24px;
    margin-bottom: 20px;
}

.user-guide-modal h3 {
    color: #0056b3;
    font-size: 20px;
    margin-top: 25px;
}

.user-guide-modal strong {
    color: #1a1a1a;
}

.collapsed {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.9);
}
"""

with gr.Blocks(css=custom_css) as demo:
    gr.HTML("<div class='banner'>Data Connector Demo</div>")
    
    # User Guide Modal
    user_guide_html = gr.HTML("""
<div id="user-guide-overlay" class="user-guide-overlay"></div>
<div id="user-guide-modal" class="user-guide-modal">
  <h2>Data Connector - User Guide</h2>
  <p>Welcome to Data Connector, a tool that helps you easily extract and explore data from any API platform and generate schema files.</p>

  <h3>Getting Started</h3>
  <p><strong>Step 1: Select an API Platform</strong><br/>
  Click on one of the three available platforms:<br/>
  Okta: For Okta Identity Cloud data<br/>
  SailPoint IdentityNow: For cloud-based identity governance data<br/>
  SailPoint IIQ: For on-premise identity governance data<br/>
  Others: For custom API specifications</p>

  <p><strong>Step 2: Enter API Specification URL</strong><br/>
  Enter the URL for the API specification (OpenAPI/Swagger) for your selected platform.</p>

  <p><strong>Step 3: Load API Specification</strong><br/>
  Click the "Load API Specification" button to fetch and parse the API endpoints.</p>

  <p><strong>Step 4: Select Endpoint Type</strong><br/>
  Choose between GET or POST endpoints to display.</p>

  <p><strong>Step 5: Browse and Select Endpoints</strong><br/>
  After loading, you'll see API endpoints grouped by category<br/>
  Click on any category to expand it and see available endpoints<br/>
  Select the checkboxes next to the endpoints you want to include<br/>
  You can select multiple endpoints across different categories</p>

  <p><strong>Step 6: Generate Schema</strong><br/>
  Click the "Generate Schema" button to create schema files based on your selected endpoints.</p>

  <p><strong>Step 7: View and Download Results</strong><br/>
  Results will display in both JSON and XML formats<br/>
  Review the generated schema files<br/>
  Click the download button to save all files as a ZIP file</p>

  <h3>Tips and Troubleshooting</h3>
  <ul>
    <li><strong>API Specification URLs:</strong> Always include the full URL with https:// prefix</li>
    <li><strong>No Endpoints Found:</strong> Check that the API specification is valid and accessible</li>
    <li><strong>Schema Generation:</strong> Make sure to select at least one endpoint before generating schemas</li>
  </ul>

  <h3>Need Help?</h3>
  <p>If you need assistance or encounter issues, refer to the official API documentation for detailed guidance:</p>
  <ul>
    <li><strong>SailPoint IdentityNow:</strong> <a href="https://developer.sailpoint.com/docs/api/v3/identity-security-cloud-v-3-api" target="_blank">Identity Security Cloud V3 API</a></li>
    <li><strong>SailPoint IIQ:</strong> <a href="https://developer.sailpoint.com/docs/api/iiq/identityiq-scim-rest-api/" target="_blank">IdentityIQ SCIM REST API</a></li>
    <li><strong>Okta:</strong> <a href="https://developer.okta.com/docs/reference/core-okta-api/" target="_blank">Core Okta API</a></li>
  </ul>

  <p><strong style="color: #222222; font-style: italic;">You can always access these instructions any time by clicking on the "User Guide" button.</strong></p>

  <button class="action-btn" 
    onclick="
      var modal = document.getElementById('user-guide-modal');
      var overlay = document.getElementById('user-guide-overlay');
      modal.classList.add('collapsed');
      overlay.classList.add('collapsed');
      setTimeout(function(){
          modal.style.display = 'none';
          overlay.style.display = 'none';
          document.getElementById('user-guide-button').style.display = 'block';
      }, 500);
    "
  >
    I Understand, Continue
  </button>
</div>

<button id="user-guide-button" class="action-btn" 
  style="position: fixed; bottom: 20px; right: 20px; display: none; z-index: 9999; box-shadow: 0 4px 10px rgba(0,0,0,0.3);"
  onclick="
    var modal = document.getElementById('user-guide-modal');
    var overlay = document.getElementById('user-guide-overlay');
    modal.style.display = 'block';
    overlay.style.display = 'block';
    setTimeout(function(){
      modal.classList.remove('collapsed');
      overlay.classList.remove('collapsed');
    }, 100);
  "
>
  User Guide
</button>
""", visible=True)

    # State variables
    locked_endpoints_state = gr.State([])
    endpoint_type_state = gr.State("get")  # Default to GET endpoints
    api_spec_url_state = gr.State("")
    required_params_count = gr.State(0)

    # API selection with card-style UI
    api_options = [
        {"icon": "fa-cloud", "title": "Okta", "description": "Identity and Access Management", "value": "Okta (JSON)"},
        {"icon": "fa-user-shield", "title": "SailPoint IdentityNow", "description": "Cloud Identity Governance", "value": "SailPoint IdentityNow (YAML)"},
        {"icon": "fa-network-wired", "title": "Sailpoint IIQ", "description": "On-premise Identity Governance", "value": "Sailpoint IIQ (YAML)"},
        {"icon": "fa-cogs", "title": "Other", "description": "Custom API Specification", "value": "Others"}
    ]
    
    # Create a radio button with custom styling to look like cards
    choices = [(opt["title"], opt["value"]) for opt in api_options]
    api_choice = gr.Radio(choices=choices, label="Select API Platform", type="value", elem_classes="api-cards")
    
    # Custom API inputs (visible when "Others" is selected)
    with gr.Group(visible=False) as custom_api_group:
        custom_api_name = gr.Textbox(label="Custom API Name", placeholder="Enter API name (e.g., 'My API')")
        custom_api_format = gr.Radio(choices=["JSON", "YAML"], label="API Format", value="JSON")
    
    # API Base URL input
    with gr.Row():
        api_base_url = gr.Textbox(label="API Specification URL", placeholder="Enter API specification URL")
    
    # Connect API choice to custom API visibility
    api_choice.change(
        fn=update_api_url,
        inputs=[api_choice],
        outputs=[custom_api_group, api_base_url, api_spec_url_state]
    )

    # Update API spec URL state when the text field changes
    def update_api_spec_url_state(url):
        global current_api_spec_url
        print(f"Updating API spec URL state to: {url}")
        # Also update the global variable
        current_api_spec_url = url
        return gr.update(value=url)
    
    api_base_url.change(
        fn=update_api_spec_url_state,
        inputs=[api_base_url],
        outputs=[api_spec_url_state]
    )
    
    # Load API Specification button
    load_btn = gr.Button("Load API Specification", elem_classes="action-btn")
    loading_indicator = gr.HTML("<div class='loading-spinner'></div>", visible=False)
    message_box = gr.HTML("", visible=False)

    # Endpoints section
    with gr.Group(visible=False, elem_classes="endpoints-section") as endpoints_section:
        # Endpoint type selector (GET, POST, or ALL)
        endpoint_type = gr.Radio(
            choices=["GET", "POST", "ALL"], 
            value="GET", 
            label="Endpoints Type", 
            elem_classes="endpoint-type-selector"
        )
        
        # Deselect All checkbox
        with gr.Row():
            deselect_all_cb = gr.Checkbox(label="Deselect All", value=False)
        
        with gr.Row():
            edit_btn = gr.Button("Edit", interactive=False, elem_classes="reset-btn")
            reset_btn = gr.Button("Reset", interactive=False, elem_classes="reset-btn")
        
        # Accordion for endpoint groups
        max_groups = 100  # Reduced for simplicity
        accordion_placeholders = []
        for i in range(max_groups):
            with gr.Accordion(label="", open=False, visible=False, elem_classes="custom-accordion") as acc:
                cb = gr.CheckboxGroup(label="", choices=[], value=[], elem_classes="custom-checkbox")
            accordion_placeholders.append((acc, cb))
        
        continue_btn = gr.Button("Generate Schema", elem_classes="action-btn")

    # Parameters section
    with gr.Group(elem_classes="param-group", visible=False) as param_group:
        param_header = gr.Markdown("### Parameters Required")
        param_components = []
        for i in range(5):
            with gr.Group(visible=False, elem_classes="param-item") as group:
                param_display = gr.Markdown(visible=False)
                param_input = gr.Textbox(label="Parameter Value", visible=False)
                param_components.append((group, param_display, param_input))

    # Results section
    with gr.Group(visible=False, elem_classes="results-section") as results_section:
        gr.Markdown("### Results")
        with gr.Tabs() as result_tabs:
            with gr.TabItem("JSON Schema"):
                json_output = gr.Code(label="JSON Schema", language="json", elem_classes="gr-code")
            with gr.TabItem("XML Schema"):
                xml_output = gr.Textbox(label="XML Schema", lines=20, elem_classes="gr-code")
        download_out = gr.File(label="Download Schema Files (ZIP)", visible=True, interactive=True)

    # Function to load API specification
    def load_api_spec(api_choice_val, base_url, custom_name=None, custom_format=None):
        global current_api_spec_url
        
        yield (
            gr.update(visible=True),  # Show loading indicator
            gr.update(value="", visible=False),
            gr.update(visible=False),
            gr.update(visible=False),
            *[gr.update(visible=False, label="", value=[]) for _ in range(max_groups * 2)],
            gr.update(value="")
        )
        # Handle custom API
        if api_choice_val == "Others":
            # Create a custom API choice value if name is provided
            if custom_name:
                api_choice_val = f"{custom_name} ({custom_format})"
            # Make sure we use the base_url directly for "Others" option
            spec_url = base_url
            print(f"Using custom API spec URL: {spec_url}")
        else:
            # Get endpoints and API spec URL for predefined platforms
            _, spec_url = get_endpoints(api_choice_val, None)
            if base_url:  # If user provided a URL, use it instead
                spec_url = base_url
                print(f"Using user-provided API spec URL for {api_choice_val}: {spec_url}")
            else:
                print(f"Using default API spec URL for {api_choice_val}: {spec_url}")
        
        # Store the current API spec URL
        current_api_spec_url = spec_url
        print(f"Setting current_api_spec_url to: {current_api_spec_url}")
        
        # Get endpoints using the determined spec_url
        endpoints, _ = get_endpoints(api_choice_val, spec_url)
        
        if not endpoints:
            yield (
                gr.update(visible=True),
                gr.update(value="<div style='color: red;'>No endpoints found</div>", visible=True),
                gr.update(visible=False),
                gr.update(visible=False),
                *[gr.update(visible=False, label="", value=[]) for _ in range(max_groups * 2)],
                gr.update(value=spec_url)
            )
        
        # Group endpoints by GET method (default)
        groups = group_endpoints(endpoints, api_choice_val, 'get')
        group_keys = list(groups.keys())
        updates = []
        
        for i in range(max_groups):
            if i < len(group_keys):
                group = group_keys[i]
                choices = [f"{ep} | GET - {methods['get'].get('summary', 'No summary')}" for ep, methods in groups[group].items() if 'get' in methods]
                updates.extend([
                    gr.update(label=group, visible=bool(choices), open=False),
                    gr.update(choices=choices, value=choices, visible=bool(choices))
                ])
            else:
                updates.extend([gr.update(visible=False, label=""), gr.update(visible=False, choices=[], value=[])])
        
        yield (
            gr.update(visible=False),
            gr.update(value="<div class='success-message'><i class='fas fa-check-circle'></i> API specification loaded successfully</div>", visible=True),
            gr.update(visible=True),
            gr.update(visible=False),
            *updates,
            gr.update(value=spec_url)
        )

    # Function to update endpoints based on selected type (GET, POST, or ALL)
    def update_endpoint_display(api_choice_val, endpoint_type_val, api_spec_url):
        # Convert endpoint type to lowercase
        endpoint_type_val = endpoint_type_val.lower()
        
        # Get endpoints
        endpoints, _ = get_endpoints(api_choice_val, api_spec_url)
        if not endpoints:
            # Even if no endpoints are found, we should still return the endpoint type state
            # and ensure the endpoints section remains visible
            return [gr.update(visible=False, label="", value=[]) for _ in range(max_groups * 2)] + [gr.update(value=endpoint_type_val)]
        
        # Group endpoints by selected type
        groups = group_endpoints(endpoints, api_choice_val, endpoint_type_val)
        group_keys = list(groups.keys())
        updates = []
        
        for i in range(max_groups):
            if i < len(group_keys):
                group = group_keys[i]
                
                if endpoint_type_val == 'all':
                    # For 'all' type, include both GET and POST endpoints
                    choices = []
                    for ep, methods in groups[group].items():
                        for method_type in ['get', 'post']:
                            if method_type in methods:
                                choices.append(f"{ep} | {method_type.upper()} - {methods[method_type].get('summary', 'No summary')}")
                else:
                    # For specific method types
                    choices = [f"{ep} | {endpoint_type_val.upper()} - {methods[endpoint_type_val].get('summary', 'No summary')}" 
                              for ep, methods in groups[group].items() if endpoint_type_val in methods]
                
                updates.extend([
                    gr.update(label=group, visible=bool(choices), open=False),
                    gr.update(choices=choices, value=choices, visible=bool(choices))
                ])
            else:
                updates.extend([gr.update(visible=False, label=""), gr.update(visible=False, choices=[], value=[])])
        
        return updates + [gr.update(value=endpoint_type_val)]

    # Function to lock selected endpoints and generate schema directly
    def lock_selected_endpoints(*checkbox_values):
        all_selected = [sel for group in checkbox_values if isinstance(group, list) for sel in group]
        if not all_selected:
            return [
                [],
                gr.update(interactive=True),
                gr.update(interactive=False),
                gr.update(interactive=False),
                *[gr.update(interactive=True) for _ in range(max_groups)]
            ]
        
        return [
            all_selected,
            gr.update(interactive=False),
            gr.update(interactive=True),
            gr.update(interactive=True),
            *[gr.update(interactive=False) for _ in range(max_groups)]
        ]

    # Function to unlock selected endpoints
    def unlock_selected_endpoints():
        return [
            gr.update(value=[]),
            gr.update(interactive=True),
            gr.update(interactive=False),
            gr.update(interactive=False),
            *[gr.update(interactive=True) for _ in range(max_groups)]
        ]

    # Function to reset selected endpoints
    def reset_selected_endpoints():
        return [
            gr.update(value=[]),
            gr.update(interactive=True),
            gr.update(interactive=False),
            gr.update(interactive=False),
            *[gr.update(interactive=True, value=[]) for _ in range(max_groups)]
        ]

    # Store the current API spec URL in a global variable
    current_api_spec_url = ""

    # Function to generate schema files
    def generate_schemas(api_choice_val, api_spec_url_value, custom_api_name_value, *checkbox_values):
        global current_api_spec_url
        
        print(f"Generate schemas called with api_choice_val: {api_choice_val}")
        print(f"API spec URL value from state: {api_spec_url_value}")
        print(f"Current API spec URL: {current_api_spec_url}")
        print(f"Custom API name from UI: {custom_api_name_value}")
        
        # Get custom API name if "Others" is selected
        custom_name = None
        if api_choice_val == "Others":
            # Use the custom API name passed as a parameter
            custom_name = custom_api_name_value
            
            # If custom_name is None or empty, use a default name
            if not custom_name or custom_name.strip() == "":
                custom_name = "custom_api"
                print(f"Using default custom API name: {custom_name}")
        
        # Extract both path and method from selected endpoints
        all_selected = []
        for group in checkbox_values:
            if isinstance(group, list):
                for sel in group:
                    # Parse both path and method from the selection
                    parts = sel.split(" | ")
                    if len(parts) >= 2:
                        path = parts[0].strip()
                        method = parts[1].split(" - ")[0].strip().lower()  # Extract GET or POST
                        all_selected.append((path, method))
        
        if not all_selected:
            return (
                gr.update(visible=False),
                gr.update(value=""),
                gr.update(value=""),
                gr.update(value=None)
            )
        
        # Use the current API spec URL that was set when loading the API specification
        api_spec_url = current_api_spec_url
        
        # If we still don't have a URL, try to use the one from the state
        if not api_spec_url:
            api_spec_url = api_spec_url_value
            print(f"Using API spec URL from state: {api_spec_url}")
        
        print(f"API Choice: {api_choice_val}")
        print(f"API Spec URL: {api_spec_url}")
        print(f"Selected endpoints count: {len(all_selected)}")
        
        # Check if api_choice_val is None
        if api_choice_val is None:
            print(f"Error: API choice is None")
            return (
                gr.update(visible=True),
                gr.update(value="Error: Please select an API platform first"),
                gr.update(value="Error: Please select an API platform first"),
                gr.update(value=None)
            )
        
        # Check if api_spec_url is empty
        if not api_spec_url:
            print(f"Error: API spec URL is empty")
            return (
                gr.update(visible=True),
                gr.update(value="Error: API specification URL is empty. Please select a valid API platform or enter a URL."),
                gr.update(value="Error: API specification URL is empty. Please select a valid API platform or enter a URL."),
                gr.update(value=None)
            )
        
        # Generate schema files
        try:
            # Pass the custom API name if it's available
            if api_choice_val == "Others" and custom_name:
                result = generate_schema_files(api_choice_val, all_selected, api_spec_url, custom_name)
            else:
                result = generate_schema_files(api_choice_val, all_selected, api_spec_url)
            
            # Create a temporary file with .zip extension
            fd, temp_path = tempfile.mkstemp(suffix='.zip')
            os.close(fd)
            
            # Write the BytesIO content to the temporary file
            with open(temp_path, 'wb') as f:
                f.write(result["zip"].getvalue())
                
            print(f"Temporary zip file created at: {temp_path}")
            
        except Exception as e:
            print(f"Error generating schema files: {e}")
            return (
                gr.update(visible=True),
                gr.update(value=f"Error generating schema files: {str(e)}"),
                gr.update(value=f"Error generating schema files: {str(e)}"),
                gr.update(value=None)
            )
        
        return (
            gr.update(visible=True),
            gr.update(value=result["json"]),
            gr.update(value=result["xml"]),
            gr.update(value=temp_path)  # Use the temporary file path instead of BytesIO
        )

    # Function to handle API choice change - collapses sections when API is changed
    def handle_api_choice_change(api_choice_val):
        global current_api_spec_url
        # Reset the current API spec URL when changing API choice
        current_api_spec_url = ""
        # First, get the outputs from update_api_url
        custom_api_visibility, api_base_url_value, api_spec_url_value = update_api_url(api_choice_val)
        # Then, add the visibility updates for endpoints and results sections
        return custom_api_visibility, api_base_url_value, api_spec_url_value, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
    
    # Update API choice to handle collapsing sections
    api_choice.change(
        fn=handle_api_choice_change,
        inputs=[api_choice],
        outputs=[custom_api_group, api_base_url, api_spec_url_state, endpoints_section, results_section, message_box]
    )
    
    # Connect UI components to functions
    load_btn.click(
        fn=load_api_spec,
        inputs=[api_choice, api_base_url, custom_api_name, custom_api_format],
        outputs=[
            loading_indicator,
            message_box,
            endpoints_section,
            results_section
        ] + [comp for acc, cb in accordion_placeholders for comp in (acc, cb)] + [api_spec_url_state]
    )

    # Function to update endpoints and ensure endpoints section remains visible
    def update_endpoints_and_maintain_visibility(api_choice_val, endpoint_type_val, api_spec_url):
        # Get updates for accordion placeholders and endpoint type state
        updates = update_endpoint_display(api_choice_val, endpoint_type_val, api_spec_url)
        # Return these updates plus an update to keep the endpoints section visible
        return updates + [gr.update(visible=True)]
    
    endpoint_type.change(
        fn=update_endpoints_and_maintain_visibility,
        inputs=[api_choice, endpoint_type, api_spec_url_state],
        outputs=[comp for acc, cb in accordion_placeholders for comp in (acc, cb)] + [endpoint_type_state, endpoints_section]
    )

    
    # Function to handle deselect all checkbox
    def deselect_all_endpoints(deselect_all, *current_values):
        if not deselect_all:
            return [gr.update(value=val) for val in current_values]
        
        # Deselect all checkboxes
        updates = [gr.update(value=[]) for _ in current_values]
        
        return updates
    
    # Connect deselect all checkbox
    
    deselect_all_cb.change(
        fn=deselect_all_endpoints,
        inputs=[deselect_all_cb] + [cb for _, cb in accordion_placeholders],
        outputs=[cb for _, cb in accordion_placeholders]
    )
    
    continue_btn.click(
        fn=lock_selected_endpoints,
        inputs=[cb for _, cb in accordion_placeholders],
        outputs=[
            locked_endpoints_state, 
            continue_btn, 
            edit_btn,
            reset_btn
        ] + [cb for _, cb in accordion_placeholders]
    )

    edit_btn.click(
        fn=unlock_selected_endpoints,
        inputs=[],
        outputs=[
            locked_endpoints_state, 
            continue_btn, 
            edit_btn,
            reset_btn
        ] + [cb for _, cb in accordion_placeholders]
    )

    reset_btn.click(
        fn=reset_selected_endpoints,
        inputs=[],
        outputs=[
            locked_endpoints_state, 
            continue_btn, 
            edit_btn,
            reset_btn
        ] + [cb for _, cb in accordion_placeholders]
    )

    continue_btn.click(
        fn=generate_schemas,
        inputs=[api_choice, api_spec_url_state, custom_api_name] + [cb for _, cb in accordion_placeholders],
        outputs=[
            results_section,
            json_output,
            xml_output,
            download_out
        ]
    )

    # Function to return the zip file for download
    def download_schema_files(json_content, xml_content):
        # Generate schema files in memory
        if not json_content or not xml_content:
            return None
            
        try:
            # Determine API name from JSON content
            meta_data = json.loads(json_content)
            api_name = meta_data.get("name", "schema").lower().replace(" ", "_")
            
            # Create a zip file in memory
            zip_buffer = io.BytesIO()
            with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
                zip_file.writestr(f"{api_name}_datasource_plugin_meta.json", json_content)
                zip_file.writestr(f"{api_name}_default_schema.orx", xml_content)
            
            zip_buffer.seek(0)
            
            # Create a temporary file with .zip extension
            fd, temp_path = tempfile.mkstemp(suffix='.zip')
            os.close(fd)
            
            # Write the BytesIO content to the temporary file
            with open(temp_path, 'wb') as f:
                f.write(zip_buffer.getvalue())
            
            # Return the file path with a filename for download
            return (temp_path, f"{api_name}_schema_files.zip")
            
        except Exception as e:
            print(f"Error creating download file: {e}")
            return None
    

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