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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
import os
import sys
import plotly.graph_objects as go



# Add project root and src directory to Python path to enable imports from timebench
# Get the directory containing this file (leaderboard_app/src/)
current_dir = os.path.dirname(os.path.abspath(__file__))
# Get leaderboard_app directory
leaderboard_app_dir = os.path.dirname(current_dir)

# Try multiple paths for timebench import:
# 1. Current leaderboard_app directory (if timebench was copied to leaderboard_app/)
# 2. Parent directory's src (for local development: TIME/src/)

# Add current leaderboard_app directory first (for Space deployment)
if leaderboard_app_dir not in sys.path:
    sys.path.insert(0, leaderboard_app_dir)

# Get project root directory (TIME/) - for local development
project_root = os.path.dirname(leaderboard_app_dir)
if project_root not in sys.path:
    sys.path.insert(0, project_root)

src_dir = os.path.join(project_root, "src")
if src_dir not in sys.path and os.path.exists(src_dir):
    sys.path.insert(0, src_dir)

import json
import gradio as gr
from src.about import DATASET_CHOICES, ALL_MODELS, RESULTS_ROOT, FEATURES_DF, FEATURES_BOOL_DF, PATTERN_MAP
from src.leaderboard import (get_overall_leaderboard, get_dataset_multilevel_leaderboard,
                            get_window_leaderboard, get_pattern_leaderboard, resolve_dataset_id)
from src.about import DATASETS_DF, ALL_HORIZONS
from src.hf_config import get_datasets_root, get_config_root
import numpy as np
import pandas as pd
from pathlib import Path
import ast
import matplotlib
matplotlib.use('Agg')  # Use non-interactive backend for Gradio
import yaml
import tempfile

from timebench.evaluation.data import Dataset, get_dataset_settings, load_dataset_config
from src.leaderboard import find_dataset_term_path


def export_dataframe_to_csv(df, filename_prefix="leaderboard"):
    """Export a DataFrame to a temporary CSV file and return the path for download.

    Args:
        df: pandas DataFrame to export
        filename_prefix: prefix for the temporary file name

    Returns:
        str: path to the temporary CSV file, or None if df is empty
    """
    if df is None or (hasattr(df, 'empty') and df.empty):
        return None
    with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False, prefix=f"{filename_prefix}_") as f:
        df.to_csv(f, index=False)
        return f.name


# def update_variate_choices(dataset_name: str, selected_patterns: list[str]):
#     """
#     Dynamically update the variate dropdown choices based on dataset + patterns.
#     """
#     if dataset_name == "All":
#         return gr.Dropdown(choices=["All"], value="All", interactive=False)

#     # Filter features by dataset
#     df = FEATURES_BOOL_DF[FEATURES_BOOL_DF["dataset"] == dataset_name]

#     # Apply pattern filters if provided
#     if selected_patterns:
#         mask = pd.Series(True, index=df.index)
#         for pattern in selected_patterns:
#             if pattern in df.columns:
#                 mask &= df[pattern] == 1
#         df = df[mask]

#     variates = sorted(df["variate_name"].unique().tolist())
#     if not variates:
#         return gr.Dropdown(choices=["All"], value="All", interactive=False)

#     return gr.Dropdown(choices=["All"] + variates, value="All", interactive=True)


# # ๆ›ดๆ–ฐ Variate ้€‰ๆ‹ฉๆก†
# def update_variate_choices_groups(dataset_name, t, s, r, g):
#     selected_patterns = (t or []) + (s or []) + (r or []) + (g or [])
#     return update_variate_choices(dataset_name, selected_patterns)


########################## Dataset Tab ##########################
def update_series_and_variate(display_name):
    """
    ๆ นๆฎ dataset display_name ๆ›ดๆ–ฐ series ๅ’Œ variate ็š„ไธ‹ๆ‹‰้€‰้กน
    ็”จไบŽๅˆๅนถๅŽ็š„ Dataset tab

    Args:
        display_name: Dataset display name from UI dropdown (will be resolved to dataset_id)
    """
    # Use first available model to get data
    model_name = ALL_MODELS[0]
    # Find dataset_term (handles display_name -> dataset_id conversion)
    results_root = str(RESULTS_ROOT)
    dataset_term = find_dataset_term_path(results_root, model_name, display_name)

    if dataset_term is None:
        print(f"Error: dataset_term is None for display_name={display_name}, model_name={model_name}")
        return (
            gr.Dropdown(choices=["---"], value="---", label="Select Series", interactive=True),
            gr.Dropdown(choices=["---"], value="---", label="Select Variate", interactive=True),
        )

    # Load Dataset to get actual series and variate names
    # Use HF config to get dataset root (handles both local and HF Hub)
    hf_dataset_root = str(get_datasets_root())

    # Use HF config to get config root
    config_root = get_config_root()
    config_path = config_root / "datasets.yaml"

    # horizonไธๅฝฑๅ“seriesๅ’Œvariate็š„ๅ€ผ๏ผŒๅ› ๆญค็›ดๆŽฅ็”จshort
    config = load_dataset_config(config_path)
    settings = get_dataset_settings(dataset_term, "short", config)

    prediction_length = settings.get("prediction_length")
    test_length = settings.get("test_length")

    dataset_obj = Dataset(
        name=dataset_term,
        term="short",
        prediction_length=prediction_length,
        test_length=test_length,
        storage_path=hf_dataset_root,  # Pass storage path directly
    )

    # Get series names
    if "item_id" in dataset_obj.hf_dataset.column_names:
        series_names = dataset_obj.hf_dataset["item_id"]
    else:
        series_names = [dataset_obj.hf_dataset[i].get("item_id", f"item_{i}")
                        for i in range(len(dataset_obj.hf_dataset))]

    series_list = ["---"] + [str(name) for name in series_names]

    # Get variate names
    variate_names = dataset_obj.get_variate_names()

    if variate_names is None:
        # UTS mode: variate dropdown should be disabled
        return (
            gr.Dropdown(choices=series_list, value="---", label="Select Series", interactive=True),
            gr.Dropdown(choices=["---"], value="---", label="Select Variate", interactive=False),
        )
    else:
        # MTS mode: both dropdowns are enabled
        variates_list = ["---"] + [str(name) for name in variate_names]
        return (
            gr.Dropdown(choices=series_list, value="---", label="Select Series", interactive=True),
            gr.Dropdown(choices=variates_list, value="---", label="Select Variate", interactive=True),
        )


########################## Window Tab ##########################
def get_available_horizons(display_name):
    """
    ่Žทๅ–ๆ•ฐๆฎ้›†ๅฏ็”จ็š„horizons

    Args:
        display_name: Dataset display name from UI dropdown

    Returns:
        list: ๅฏ็”จ็š„horizonๅˆ—่กจ๏ผŒไพ‹ๅฆ‚ ["short", "medium", "long"] ๆˆ– ["short"]
    """
    if DATASETS_DF.empty:
        return ALL_HORIZONS

    # Resolve display_name to dataset_id
    dataset_id = resolve_dataset_id(display_name)

    # Filter by dataset_id
    df_filtered = DATASETS_DF[DATASETS_DF["dataset_id"] == dataset_id]

    if df_filtered.empty:
        # If not found, return all horizons as fallback
        return ALL_HORIZONS

    # Get unique horizons for this dataset
    available_horizons = df_filtered["horizon"].unique().tolist()

    # Sort to maintain order: short, medium, long
    available_horizons = [h for h in ALL_HORIZONS if h in available_horizons]

    return available_horizons if available_horizons else ["short"]


def update_horizon_choices(display_name):
    """
    ๆ นๆฎๆ•ฐๆฎ้›†ๆ›ดๆ–ฐhorizon Radio็ป„ไปถ็š„choicesๅ’Œvalue

    Args:
        display_name: Dataset display name from UI dropdown

    Returns:
        tuple: (choices, value) ็”จไบŽๆ›ดๆ–ฐRadio็ป„ไปถ
    """
    available_horizons = get_available_horizons(display_name)

    # ๅฆ‚ๆžœๅฝ“ๅ‰้€‰ๆ‹ฉ็š„horizonไธๅœจๅฏ็”จๅˆ—่กจไธญ๏ผŒๅˆ™้€‰ๆ‹ฉ็ฌฌไธ€ไธชๅฏ็”จ็š„
    current_value = "short" if "short" in available_horizons else (available_horizons[0] if available_horizons else "short")

    # ๅˆ›ๅปบchoicesๅˆ—่กจ๏ผŒๅชๅŒ…ๅซๅฏ็”จ็š„horizons
    choices = [h for h in ALL_HORIZONS if h in available_horizons]

    return gr.Radio(choices=choices, value=current_value)


def update_horizon_checkbox_choices(display_name):
    """
    ๆ นๆฎๆ•ฐๆฎ้›†ๆ›ดๆ–ฐhorizon CheckboxGroup็ป„ไปถ็š„choicesๅ’Œvalue
    ็”จไบŽ Per Dataset tab

    Args:
        display_name: Dataset display name from UI dropdown

    Returns:
        gr.CheckboxGroup: ๆ›ดๆ–ฐๅŽ็š„CheckboxGroup็ป„ไปถ
    """
    available_horizons = get_available_horizons(display_name)

    # ๅˆ›ๅปบchoicesๅˆ—่กจ๏ผŒๅชๅŒ…ๅซๅฏ็”จ็š„horizons
    choices = [h for h in ALL_HORIZONS if h in available_horizons]

    # ้ป˜่ฎคๅ…จ้ƒจ้€‰ไธญ
    return gr.CheckboxGroup(choices=choices, value=choices)


def update_series_variate_and_window(display_name, horizon):
    """
    ๆ นๆฎ dataset display_name ๅ’Œ horizon ๆ›ดๆ–ฐ series, variate, window ็š„ไธ‹ๆ‹‰้€‰้กน
    ไฝฟ็”จ Dataset ๅŠ ่ฝฝๅฎž้™…็š„ series ๅ’Œ variate ๅ็งฐ

    Args:
        display_name: Dataset display name from UI dropdown (will be resolved to dataset_id)
        horizon: Horizon name (short, medium, long)
    """
    # Use first available model to get data
    model_name = ALL_MODELS[0]

    # Find dataset_term (handles display_name -> dataset_id conversion)
    results_root = str(RESULTS_ROOT)
    dataset_term = find_dataset_term_path(results_root, model_name, display_name)

    if dataset_term is None:
        print(f"Error: dataset_term is None for display_name={display_name}, horizon={horizon}, model_name={model_name}")
        return (
            gr.Dropdown(choices=[], value=None, label="Select Series", interactive=False),
            gr.Dropdown(choices=[], value=None, label="Select Variate", interactive=False),
            gr.Dropdown(choices=[], value=None, label="Select Testing Window", interactive=False),
        )

    # Parse dataset_name and freq from dataset_term (format: "dataset_name/freq")
    dataset_name, freq = dataset_term.split("/", 1)

    # Load Dataset to get actual series and variate names
    # Use HF config to get dataset root (handles both local and HF Hub)
    hf_dataset_root = str(get_datasets_root())

    # Use HF config to get config root
    config_root = get_config_root()
    config_path = config_root / "datasets.yaml"

    config = load_dataset_config(config_path) if config_path.exists() else {}
    settings = get_dataset_settings(dataset_term, horizon, config)

    prediction_length = settings.get("prediction_length")
    test_length = settings.get("test_length")

    # Load dataset
    dataset_obj = Dataset(
        name=dataset_term,
        term=horizon,
        prediction_length=prediction_length,
        test_length=test_length,
        storage_path=hf_dataset_root,  # Pass storage path directly
    )

    # Get series names (item_id) from hf_dataset
    if "item_id" in dataset_obj.hf_dataset.column_names:
        series_names = dataset_obj.hf_dataset["item_id"]
    else:
        # Fallback: get from iterating
        series_names = [dataset_obj.hf_dataset[i].get("item_id", f"item_{i}")
                        for i in range(len(dataset_obj.hf_dataset))]

    # Get variate names
    variate_names = dataset_obj.get_variate_names()

    # Get window count
    num_windows = dataset_obj.windows
    windows = [str(i) for i in range(num_windows)]

    # Convert to lists and maintain order (no sorting)
    series_list = [str(name) for name in series_names]

    # Handle UTS (Univariate Time Series) vs MTS (Multivariate Time Series)
    if variate_names is None:
        # UTS mode: each series is a single variate, so variate is always 0
        return (
            gr.Dropdown(choices=series_list, value=series_list[0], label="Select Series", interactive=True),
            gr.Dropdown(choices=["0"], value="0", label="Select Variate", interactive=False),
            gr.Dropdown(choices=windows, value=windows[0], label="Select Testing Window", interactive=True),
        )
    else:
        # MTS mode: multiple variates per series
        variates_list = [str(name) for name in variate_names]
        return (
            gr.Dropdown(choices=series_list, value=series_list[0], label="Select Series", interactive=True),
            gr.Dropdown(choices=variates_list, value=variates_list[0], label="Select Variate", interactive=True),
            gr.Dropdown(choices=windows, value=windows[0], label="Select Testing Window", interactive=True),
        )


def plot_window_series(display_name, series, variate, window_id, horizon, selected_quantiles, model):
    """
    Plot time series predictions for a specific window using Plotly for interactive visualization.
    Now includes full time series visualization with test window highlighted.
    Accepts series and variate names (strings) and converts them to indices.

    Args:
        display_name: Dataset display name from UI dropdown (will be resolved to dataset_id)
        series: Series name
        variate: Variate name
        window_id: Window index
        horizon: Horizon name
        selected_quantiles: List of quantile strings to plot
        model: Model name

    Returns:
        tuple: (fig, info_message) where fig is Plotly figure and info_message contains prediction details
    """
    print(f"๐Ÿ” plot_window_series called: display_name={display_name}, series={series}, variate={variate}, window_id={window_id}, horizon={horizon}, model={model}")

    if display_name is None or series is None or variate is None or window_id is None:
        print("โŒ Missing parameters")
        fig = go.Figure()
        fig.update_layout(title="Please select all parameters")
        return fig, ""

    results_root = str(RESULTS_ROOT)
    print(f"๐Ÿ“ results_root: {results_root}")
    dataset_term = find_dataset_term_path(results_root, model, display_name)
    print(f"๐Ÿ“ dataset_term: {dataset_term}")
    if dataset_term is None:
        print("โŒ Dataset not found")
        fig = go.Figure()
        fig.update_layout(title="Dataset not found")
        return fig, ""

    predictions_path = os.path.join(results_root, model, dataset_term, horizon, "predictions.npz")
    print(f"๐Ÿ“ predictions_path: {predictions_path}, exists: {os.path.exists(predictions_path)}")

    if not os.path.exists(predictions_path):
        print("โŒ Predictions file not found")
        fig = go.Figure()
        fig.update_layout(title="Predictions file not found")
        return fig, ""


    predictions = np.load(predictions_path)
    # Load pre-computed quantiles (new format only)
    predictions_quantiles = predictions["predictions_quantiles"]  # (num_series, num_windows, 9, num_variates, prediction_length)
    quantile_levels = predictions["quantile_levels"]  # [0.1, 0.2, ..., 0.9]

    # Load prediction scale factor from config.json (for float16 overflow prevention)
    model_config_path = os.path.join(results_root, model, dataset_term, horizon, "config.json")
    prediction_scale_factor = 1.0
    if os.path.exists(model_config_path):
        with open(model_config_path, "r") as f:
            model_config = json.load(f)
            prediction_scale_factor = model_config.get("prediction_scale_factor", 1.0)
    if prediction_scale_factor != 1.0:
        print(f"๐Ÿ“Š Applying inverse scale factor: {prediction_scale_factor}")
        predictions_quantiles = predictions_quantiles.astype(np.float32) * prediction_scale_factor

    # Convert series and variate names to indices
    series_idx = None
    variate_idx = None
    dataset_obj = None

    # Load Dataset to get name-to-index mappings and full time series
    # Use HF config to get dataset root (handles both local and HF Hub)
    hf_dataset_root = str(get_datasets_root())
    print(f"๐Ÿ“ hf_dataset_root: {hf_dataset_root}, exists: {os.path.exists(hf_dataset_root)}")

    # Use HF config to get config root
    config_root = get_config_root()
    config_path_yaml = config_root / "datasets.yaml"
    print(f"๐Ÿ“ config_path_yaml: {config_path_yaml}, exists: {config_path_yaml.exists()}")

    config = load_dataset_config(config_path_yaml) if config_path_yaml.exists() else {}
    settings = get_dataset_settings(dataset_term, horizon, config)
    print(f"โš™๏ธ settings: {settings}")

    prediction_length = settings.get("prediction_length")
    test_length = settings.get("test_length")

    print(f"๐Ÿ“ฅ Loading Dataset: name={dataset_term}, term={horizon}, storage_path={hf_dataset_root}")
    dataset_obj = Dataset(
        name=dataset_term,
        term=horizon,
        prediction_length=prediction_length,
        test_length=test_length,
        storage_path=hf_dataset_root,  # Pass storage path directly
    )
    print(f"โœ… Dataset loaded: {len(dataset_obj.hf_dataset)} series")

    # Get frequency from dataset
    dataset_freq = dataset_obj.freq
    print(f"๐Ÿ“… Dataset frequency: {dataset_freq}")

    # Get series names and create mapping
    if "item_id" in dataset_obj.hf_dataset.column_names:
        series_names = dataset_obj.hf_dataset["item_id"]
    else:
        series_names = [dataset_obj.hf_dataset[i].get("item_id", f"item_{i}")
                        for i in range(len(dataset_obj.hf_dataset))]

    print(f"๐Ÿ“‹ series_names: {list(series_names)}")
    series_name_to_idx = {name: idx for idx, name in enumerate(series_names)}
    if series in series_name_to_idx:
        series_idx = series_name_to_idx[series]
        print(f"โœ… Found series '{series}' at index {series_idx}")
    else:
        series_idx = int(series)
        print(f"โš ๏ธ Series '{series}' not found in names, using int index {series_idx}")

    # Get variate names and create mapping
    variate_names = dataset_obj.get_variate_names()
    print(f"๐Ÿ“‹ variate_names: {variate_names}")
    if variate_names is not None:
        # MTS mode: multiple variates per series
        variate_name_to_idx = {name: idx for idx, name in enumerate(variate_names)}
        if variate in variate_name_to_idx:
            variate_idx = variate_name_to_idx[variate]
            print(f"โœ… Found variate '{variate}' at index {variate_idx}")
        else:
            variate_idx = int(variate)
            print(f"โš ๏ธ Variate '{variate}' not found in names, using int index {variate_idx}")
    else:
        # UTS mode: each series is a single variate, so variate_idx is always 0
        variate_idx = 0
        print(f"โ„น๏ธ UTS mode, variate_idx=0")

    if series_idx is None:
        series_idx = int(series)
    if variate_idx is None:
        # For UTS mode, variate_idx should be 0
        try:
            variate_idx = int(variate) if variate is not None else 0
        except (ValueError, TypeError):
            variate_idx = 0

    window_idx = int(window_id)

    # Get pre-computed quantiles for this specific series, window, and variate
    quantiles_data = predictions_quantiles[series_idx, window_idx, :, variate_idx, :]  # (9, prediction_length)
    prediction_length = quantiles_data.shape[1]
    # Create mapping from quantile level string to index
    quantile_level_to_idx = {f"{q:.1f}": i for i, q in enumerate(quantile_levels)}

    # Load full time series data
    full_series = None
    train_end_idx = None
    test_window_start_idx = None
    test_window_end_idx = None

    # Get full target time series for this series
    print(f"๐Ÿ“Š Getting target for series_idx={series_idx}, variate_idx={variate_idx}")
    full_target = dataset_obj.hf_dataset[series_idx]["target"]
    print(f"๐Ÿ“Š full_target shape: {full_target.shape}, dtype: {full_target.dtype}")
    print(f"๐Ÿ“Š full_target first 10 values (all variates): {full_target[:, :10] if full_target.ndim > 1 else full_target[:10]}")

    # Get start timestamp for this series and create timestamp array
    series_start = dataset_obj.hf_dataset[series_idx]["start"]
    print(f"๐Ÿ“… Series start timestamp: {series_start}, type: {type(series_start)}")

    # Handle numpy array containing datetime64 (common when reading from HF dataset)
    if isinstance(series_start, np.ndarray):
        # Extract scalar from array
        series_start = series_start.item() if series_start.ndim == 0 else series_start[0]
        print(f"๐Ÿ“… Extracted scalar: {series_start}, type: {type(series_start)}")

    # Convert numpy datetime64 to pandas Timestamp
    if isinstance(series_start, (np.datetime64, str)):
        series_start = pd.Timestamp(series_start)

    # Calculate series length for timestamp creation
    if full_target.ndim > 1:
        ts_length = full_target.shape[1]
    else:
        ts_length = len(full_target)

    # Create timestamp array for the entire series
    try:
        timestamps = pd.date_range(start=series_start, periods=ts_length, freq=dataset_freq)
        print(f"๐Ÿ“… Created timestamp array: {timestamps[0]} to {timestamps[-1]}")
    except Exception as e:
        print(f"โš ๏ธ Failed to create timestamps: {e}, falling back to indices")
        timestamps = None

    # Handle multivariate case: extract specific variate
    if full_target.ndim > 1:
        full_series = full_target[variate_idx, :]  # Shape: (series_length,)
    else:
        full_series = full_target  # Shape: (series_length,)
    print(f"๐Ÿ“Š full_series shape: {full_series.shape}, min: {full_series.min()}, max: {full_series.max()}, has_nan: {np.isnan(full_series).any()}")

    # Calculate train/test split point
    # Test data starts at: series_length - test_length
    series_length = len(full_series)
    train_end_idx = series_length - test_length

    # Calculate current test window position
    test_window_start_idx = train_end_idx + window_idx * prediction_length
    test_window_end_idx = test_window_start_idx + prediction_length

    # Create Plotly figure
    fig = go.Figure()

    # Quantile colors - from light to dark
    quantile_colors = {
        "0.1": "#c6dbef", "0.9": "#c6dbef",  # lightest
        "0.2": "#6baed6", "0.8": "#6baed6",  # light
        "0.3": "#4292c6", "0.7": "#4292c6",  # medium
        "0.4": "#2171b5", "0.6": "#2171b5",  # dark
        "0.5": "#08306b",  # darkest (median)
    }

    # Calculate prediction time steps (overlay on the test window)
    if test_window_start_idx is not None:
        pred_time_steps = np.arange(test_window_start_idx, test_window_end_idx)
    else:
        pred_time_steps = np.arange(prediction_length)

    # Plot full time series if available
    time_steps = np.arange(len(full_series))

    # Use timestamps for x-axis if available
    if timestamps is not None:
        x_full = timestamps
        x_pred = timestamps[pred_time_steps] if test_window_start_idx is not None else timestamps[:prediction_length]
        x_window = timestamps[test_window_start_idx:test_window_end_idx] if test_window_start_idx is not None else None
    else:
        x_full = time_steps
        x_pred = pred_time_steps
        x_window = np.arange(test_window_start_idx, test_window_end_idx) if test_window_start_idx is not None else None

    # Plot full series in light gray
    fig.add_trace(go.Scatter(
        x=x_full,
        y=full_series,
        mode='lines',
        name='Full Time Series',
        line=dict(color='gray', width=1),
        opacity=0.6,
        hovertemplate='Time: %{x}<br>Value: %{y:.4f}<extra></extra>'
    ))

    # Add shapes for regions (training, test, current window)
    if train_end_idx is not None:
        # Training region - use timestamps if available
        x0_train = timestamps[0] if timestamps is not None else 0
        x1_train = timestamps[train_end_idx] if timestamps is not None else train_end_idx
        fig.add_shape(
            type="rect",
            x0=x0_train, x1=x1_train,
            y0=0, y1=1, yref="paper",
            fillcolor="blue", opacity=0.1,
            layer="below", line_width=0,
        )
        # Test region
        test_region_end = len(full_series)
        x0_test = timestamps[train_end_idx] if timestamps is not None else train_end_idx
        x1_test = timestamps[test_region_end-1] if timestamps is not None else test_region_end-1
        fig.add_shape(
            type="rect",
            x0=x0_test, x1=x1_test,
            y0=0, y1=1, yref="paper",
            fillcolor="orange", opacity=0.15,
            layer="below", line_width=0,
        )

    # Highlight current test window
    if test_window_start_idx is not None and test_window_end_idx is not None:
        # Use timestamps for window highlight if available
        x0_window = timestamps[test_window_start_idx] if timestamps is not None else test_window_start_idx
        x1_window = timestamps[test_window_end_idx-1] if timestamps is not None else test_window_end_idx-1
        fig.add_shape(
            type="rect",
            x0=x0_window, x1=x1_window,
            y0=0, y1=1, yref="paper",
            fillcolor="red", opacity=0.2,
            layer="below", line_width=0,
        )

        # Plot the test window portion of full series
        window_series = full_series[test_window_start_idx:test_window_end_idx]
        fig.add_trace(go.Scatter(
            x=x_window,
            y=window_series,
            mode='lines',
            name='Ground Truth (Window)',
            line=dict(color='red', width=2),
            opacity=0.8,
            hovertemplate='Time: %{x}<br>Value: %{y:.4f}<extra></extra>'
        ))

    # Quantile pairs mapping: UI selection -> (low, high) quantile values
    quantile_pair_map = {
        "0.1-0.9": ("0.1", "0.9"),
        "0.2-0.8": ("0.2", "0.8"),
        "0.3-0.7": ("0.3", "0.7"),
        "0.4-0.6": ("0.4", "0.6"),
    }

    # Helper function to get pre-computed quantile values
    def get_quantile_values(q_str):
        return quantiles_data[quantile_level_to_idx[q_str], :]

    # Plot quantile pairs with fill (based on paired selection)
    for pair_str, (q_low_str, q_high_str) in quantile_pair_map.items():
        if pair_str in selected_quantiles:
            quantile_low = get_quantile_values(q_low_str)
            quantile_high = get_quantile_values(q_high_str)
            color = quantile_colors.get(q_low_str, "#2171b5")

            # Add filled area between quantiles
            fig.add_trace(go.Scatter(
                x=list(x_pred) + list(x_pred[::-1]),
                y=list(quantile_high) + list(quantile_low[::-1]),
                fill='toself',
                fillcolor=color,
                line=dict(color='rgba(255,255,255,0)'),
                hoverinfo="skip",
                showlegend=True,
                name=f'Q{q_low_str}-Q{q_high_str}',
                opacity=0.3
            ))

            # Add lower quantile line
            fig.add_trace(go.Scatter(
                x=x_pred,
                y=quantile_low,
                mode='lines',
                name=f'Q{q_low_str}',
                line=dict(color=color, width=1),
                opacity=0.7,
                showlegend=False,
                hovertemplate=f'Time: %{{x}}<br>Q{q_low_str}: %{{y:.4f}}<extra></extra>'
            ))

            # Add upper quantile line
            fig.add_trace(go.Scatter(
                x=x_pred,
                y=quantile_high,
                mode='lines',
                name=f'Q{q_high_str}',
                line=dict(color=color, width=1),
                opacity=0.7,
                showlegend=False,
                hovertemplate=f'Time: %{{x}}<br>Q{q_high_str}: %{{y:.4f}}<extra></extra>'
            ))

    # Plot median (0.5) if selected
    if "0.5" in selected_quantiles:
        quantile_values = get_quantile_values("0.5")
        color = quantile_colors.get("0.5", "#08306b")

        fig.add_trace(go.Scatter(
            x=x_pred,
            y=quantile_values,
            mode='lines+markers',
            name='Median (Q0.5)',
            line=dict(color=color, width=3),
            marker=dict(size=5, symbol='circle'),
            opacity=0.8,
            hovertemplate='Time: %{x}<br>Q0.5: %{y:.4f}<extra></extra>'
        ))

    # Update layout - use autosize for responsive width
    x_axis_title = "Timestamp" if timestamps is not None else "Time Step"
    fig.update_layout(
        title=None,
        xaxis_title=x_axis_title,
        yaxis_title="Value",
        hovermode='x unified',
        autosize=True,  # ไฝฟ็”จ่‡ชๅŠจๅฎฝๅบฆ๏ผŒ่ฎฉๅ›พ่กจๅ“ๅบ”ๅฎนๅ™จๅคงๅฐ
        height=400,
        margin=dict(l=60, r=40, t=60, b=60),  # ่ฎพ็ฝฎๅˆ็†็š„่พน่ท
        legend=dict(
            orientation="h",
            yanchor="bottom",
            y=1.02,
            xanchor="right",
            x=1,
            font=dict(size=14)
        ),
        plot_bgcolor='white',
        xaxis=dict(showgrid=True, gridcolor='lightgray', gridwidth=1),
        yaxis=dict(showgrid=True, gridcolor='lightgray', gridwidth=1)
    )


    # Create info message for prediction window
    if timestamps is not None and test_window_start_idx is not None and test_window_end_idx is not None:
        pred_start_ts = timestamps[test_window_start_idx]
        pred_end_ts = timestamps[test_window_end_idx - 1]  # -1 because end index is exclusive
        # Format with weekday name
        start_str = f"{pred_start_ts.strftime('%Y-%m-%d %H:%M:%S')} ({pred_start_ts.day_name()})"
        end_str = f"{pred_end_ts.strftime('%Y-%m-%d %H:%M:%S')} ({pred_end_ts.day_name()})"
        base_info = (
            f"๐Ÿ“Š Prediction Length: {prediction_length}\n"
            f"๐Ÿ“… Prediction Range: {start_str} โ†’ {end_str}\n"
            f"๐Ÿ”„ Dataset Frequency: {dataset_freq}"
        )
    else:
        base_info = (
            f"๐Ÿ“Š Prediction Length: {prediction_length}\n"
            f"๐Ÿ“… Prediction Range: index {test_window_start_idx} โ†’ {test_window_end_idx - 1}\n"
            f"๐Ÿ”„ Dataset Frequency: {dataset_freq if 'dataset_freq' in dir() else 'N/A'}"
        )

    # Get features information for the selected variate
    # Pattern names from init_per_pattern_tab
    pattern_names = [
        "T_strength", "T_linearity",
        "S_strength", "S_corr",
        "R_ACF1",
        "stationarity", "complexity"
    ]

    features_info = ""
    if not FEATURES_DF.empty and not FEATURES_BOOL_DF.empty:
        # Find matching row in features dataframes
        # Try to match by dataset_id, series_name, variate_name
        feature_row_orig = None
        feature_row_bool = None

        # Match by dataset_id first
        features_subset_orig = FEATURES_DF[FEATURES_DF["dataset_id"] == dataset_term]
        features_subset_bool = FEATURES_BOOL_DF[FEATURES_BOOL_DF["dataset_id"] == dataset_term]

        print(f"๐Ÿ” Features lookup: dataset_term={dataset_term}, series={series}, variate={variate}")
        print(f"๐Ÿ” Features subset size: orig={len(features_subset_orig)}, bool={len(features_subset_bool)}")

        # Try matching by series_name and variate_name (for MTS)
        if not features_subset_orig.empty:
            # Check if series_name matches
            if "series_name" in features_subset_orig.columns:
                series_match_orig = features_subset_orig["series_name"] == series
                if series_match_orig.any():
                    series_matched = features_subset_orig[series_match_orig]
                    print(f"๐Ÿ” Found {len(series_matched)} rows with series_name={series}")
                    # Check if variate_name matches
                    if "variate_name" in series_matched.columns:
                        # For UTS, variate might be "0" or 0, try both
                        variate_str = str(variate)
                        variate_match_orig = (series_matched["variate_name"] == variate_str) | (series_matched["variate_name"] == variate)
                        if variate_match_orig.any():
                            feature_row_orig = series_matched[variate_match_orig].iloc[0]
                            print(f"โœ… Found feature row by series_name + variate_name")
                            # Find corresponding row in bool dataframe
                            if not features_subset_bool.empty and "series_name" in features_subset_bool.columns and "variate_name" in features_subset_bool.columns:
                                series_match_bool = features_subset_bool["series_name"] == series
                                variate_match_bool = (features_subset_bool["variate_name"] == variate_str) | (features_subset_bool["variate_name"] == variate)
                                bool_matched = features_subset_bool[series_match_bool & variate_match_bool]
                                if not bool_matched.empty:
                                    feature_row_bool = bool_matched.iloc[0]

        # If not found, try matching by series_name only (for UTS cases where variate_name might not match)
        if feature_row_orig is None and not features_subset_orig.empty:
            if "series_name" in features_subset_orig.columns:
                series_match_orig = features_subset_orig["series_name"] == series
                if series_match_orig.any():
                    # For UTS, there might be only one row per series
                    series_matched = features_subset_orig[series_match_orig]
                    if len(series_matched) == 1:
                        feature_row_orig = series_matched.iloc[0]
                        print(f"โœ… Found feature row by series_name only (UTS)")
                        # Find corresponding row in bool dataframe
                        if not features_subset_bool.empty and "series_name" in features_subset_bool.columns:
                            series_match_bool = features_subset_bool["series_name"] == series
                            bool_matched = features_subset_bool[series_match_bool]
                            if len(bool_matched) == 1:
                                feature_row_bool = bool_matched.iloc[0]

        # If still not found, try matching by variate_name only (for UTS cases where variate_name == series)
        if feature_row_orig is None and not features_subset_orig.empty:
            if "variate_name" in features_subset_orig.columns:
                variate_match_orig = features_subset_orig["variate_name"] == series  # For UTS, series might be the variate_name
                if variate_match_orig.any():
                    feature_row_orig = features_subset_orig[variate_match_orig].iloc[0]
                    print(f"โœ… Found feature row by variate_name (series as variate_name)")
                    # Find corresponding row in bool dataframe
                    if not features_subset_bool.empty and "variate_name" in features_subset_bool.columns:
                        variate_match_bool = features_subset_bool["variate_name"] == series
                        if variate_match_bool.any():
                            feature_row_bool = features_subset_bool[variate_match_bool].iloc[0]

        if feature_row_orig is None:
            print(f"โš ๏ธ Could not find features for dataset_term={dataset_term}, series={series}, variate={variate}")
            if not features_subset_orig.empty:
                print(f"   Available series_names: {features_subset_orig['series_name'].unique()[:10] if 'series_name' in features_subset_orig.columns else 'N/A'}")
                print(f"   Available variate_names: {features_subset_orig['variate_name'].unique()[:10] if 'variate_name' in features_subset_orig.columns else 'N/A'}")

        if feature_row_orig is not None:
            # Build features display
            features_orig_items = []
            features_bool_items = []

            for pattern_name in pattern_names:
                # Map pattern name to feature column name
                feature_col = PATTERN_MAP.get(pattern_name, pattern_name)

                # Get original value (skip stationarity as it's derived from is_random_walk)
                if pattern_name != "stationarity":
                    if feature_col in feature_row_orig.index:
                        orig_value = feature_row_orig[feature_col]
                        if pd.notna(orig_value):
                            features_orig_items.append(f"{pattern_name}: {orig_value:.3f}")

                # Get binary value
                if feature_row_bool is not None and feature_col in feature_row_bool.index:
                    bool_value = feature_row_bool[feature_col]
                    if pd.notna(bool_value):
                        # Special handling for stationarity (it's inverted)
                        if pattern_name == "stationarity":
                            # stationarity = NOT is_random_walk, so display the inverted value
                            display_bool = 1 - int(bool_value)
                        else:
                            display_bool = int(bool_value)
                        features_bool_items.append(f"{pattern_name}: {display_bool}")

            if features_orig_items or features_bool_items:
                features_info = "\n\n ๐Ÿ“ Features of variate:\n"
                if features_orig_items:
                    features_info += "- Original Values: " + ", ".join(features_orig_items) + "\n"
                if features_bool_items:
                    features_info += "- Binary Values (0/1): " + ", ".join(features_bool_items)

    info_message = base_info + features_info

    print(f"๐Ÿ“ Info message: {info_message}")
    return fig, info_message


def init_overall_tab():
    gr.Markdown(
        """
        This tab presents each model's overall performance aggregated across all tasks. A **task** is defined as a specific **(dataset, horizon)** pair. For each task, the result is obtained by averaging the metrics across all its variates.
        - **MASE (norm.), CRPS (norm.)**: task-level results are normalized by Seasonal Naive and aggregated by geometric mean.
        - **MASE_rank, CRPS_rank**: for each task, models are ranked by the metric; the average rank across all tasks is then reported.
        """,
        elem_classes="markdown-text"
    )

    overall_table = gr.DataFrame(
        value=get_overall_leaderboard(DATASETS_DF, metric="MASE"),
        elem_classes="custom-table",
        interactive=False
    )

    # CSV Export
    def export_overall_csv():
        df = get_overall_leaderboard(DATASETS_DF, metric="MASE")
        return export_dataframe_to_csv(df, filename_prefix="overall_leaderboard")

    with gr.Row():
        export_btn = gr.Button("๐Ÿ“ฅ Export CSV", size="sm")
        export_file = gr.File(label="Download CSV", visible=False)

    export_btn.click(
        fn=export_overall_csv,
        inputs=[],
        outputs=[export_file]
    ).then(
        fn=lambda: gr.File(visible=True),
        inputs=[],
        outputs=[export_file]
    )


def init_per_dataset_tab(demo):
    gr.Markdown(
        """
        This tab provides flexible analysis at dataset, series, and variate levels.

        - **Dataset only**: Shows both Seasonal Naive-normalized metrics (task-level) and original non-normalized metrics, plus average ranks
        - **Series/Variate selected**: Shows only original metrics.
        - **Horizons**: Select one or more horizons to aggregate results
        """,
        elem_classes="markdown-text"
    )

    # Initialize horizon choices based on first dataset
    initial_dataset = DATASET_CHOICES[0]
    initial_horizons = get_available_horizons(initial_dataset)

    with gr.Row():
        with gr.Column(scale=1):
            horizons = gr.CheckboxGroup(
                choices=initial_horizons,
                value=initial_horizons,
                label="Horizons"
            )

            dataset_dropdown = gr.Dropdown(
                choices=DATASET_CHOICES,
                value=initial_dataset,
                label="Dataset",
                interactive=True
            )

            # Initialize series and variate dropdowns
            series_dropdown, variate_dropdown = update_series_and_variate(
                initial_dataset
            )

    msg = gr.Textbox(label="Message", interactive=False)
    table = gr.DataFrame(elem_classes="custom-table", interactive=False)

    # Update horizons, series, and variate dropdowns when dataset changes
    dataset_dropdown.change(
        fn=update_horizon_checkbox_choices,
        inputs=[dataset_dropdown],
        outputs=[horizons],
    ).then(
        fn=update_series_and_variate,
        inputs=[dataset_dropdown],
        outputs=[series_dropdown, variate_dropdown],
    ).then(
        fn=get_dataset_multilevel_leaderboard,
        inputs=[dataset_dropdown, series_dropdown, variate_dropdown, horizons],
        outputs=[msg, table]
    )

    # Update leaderboard when series, variate, or horizons change
    for comp in [series_dropdown, variate_dropdown, horizons]:
        comp.change(
            fn=get_dataset_multilevel_leaderboard,
            inputs=[dataset_dropdown, series_dropdown, variate_dropdown, horizons],
            outputs=[msg, table]
        )

    # Load on startup
    demo.load(
        fn=get_dataset_multilevel_leaderboard,
        inputs=[dataset_dropdown, series_dropdown, variate_dropdown, horizons],
        outputs=[msg, table]
    )

    # CSV Export
    def export_dataset_csv(dataset, series, variate, horizons_val):
        _, df = get_dataset_multilevel_leaderboard(dataset, series, variate, horizons_val)
        # Sanitize dataset name for filename (replace / with _)
        safe_dataset_name = dataset.replace("/", "_") if dataset else "unknown"
        return export_dataframe_to_csv(df, filename_prefix=f"dataset_{safe_dataset_name}")

    with gr.Row():
        export_btn = gr.Button("๐Ÿ“ฅ Export CSV", size="sm")
        export_file = gr.File(label="Download CSV", visible=False)

    export_btn.click(
        fn=export_dataset_csv,
        inputs=[dataset_dropdown, series_dropdown, variate_dropdown, horizons],
        outputs=[export_file]
    ).then(
        fn=lambda: gr.File(visible=True),
        inputs=[],
        outputs=[export_file]
    )


def init_per_window_tab(demo):
    gr.Markdown(
        """
        This tab enables detailed analysis of model performance at the level of individual testing windows. By selecting a dataset, variate, horizon, and test window, users can examine window-level metrics (MASE, CRPS, MAE, MSE) at fine granularity and visualize the predicted quantiles of a model along with the ground-truth.
        - **Interactive Visualization**: Zoom, pan, autoscale and download the plot.
        - ๐ŸŸฆ Train Split ๐ŸŸจ Test Split ๐ŸŸฅ Prediction Window
        """
    )

    QUANTILE_PAIR_CHOICES = ["0.1-0.9", "0.2-0.8", "0.3-0.7", "0.4-0.6", "0.5"]
    initial_quantiles = ["0.5"]

    with gr.Row():
        with gr.Column(scale=1):
            # Initialize horizon choices based on first dataset
            initial_dataset = DATASET_CHOICES[0] if DATASET_CHOICES else None
            initial_horizons = get_available_horizons(initial_dataset) if initial_dataset else ALL_HORIZONS
            horizons = gr.Radio(
                choices=initial_horizons,
                value="short" if "short" in initial_horizons else (initial_horizons[0] if initial_horizons else "short"),
                label="Horizons"
            )

            # Dropdown for dataset selection
            dataset_dropdown = gr.Dropdown(
                choices=DATASET_CHOICES,
                value=DATASET_CHOICES[0] if DATASET_CHOICES else None,  # ้ป˜่ฎค้€‰็ฌฌไธ€ไธช
                label="Dataset",
                interactive=True
            )

            # Initialize series, variate, window dropdowns using function
            series_dropdown, variate_dropdown, window_dropdown = update_series_variate_and_window(
                dataset_dropdown.value, horizons.value
            )

        with gr.Column(scale=2):
            with gr.Row():
                with gr.Column(scale=2):
                    quantiles = gr.CheckboxGroup(
                        choices=QUANTILE_PAIR_CHOICES,
                        value=initial_quantiles,
                        label="Select Quantiles for Visualization"
                    )
                with gr.Column(scale=1):
                    model = gr.Dropdown(
                        choices=ALL_MODELS,
                        value=ALL_MODELS[0],
                        label="Select Model for Visualization",
                        interactive=True
                    )
            ts_visualization = gr.Plot()
            # Message box for prediction window info
            prediction_info = gr.Textbox(
                label="Info",
                interactive=False,
                lines=3
            )

    table_window = gr.DataFrame(elem_classes="custom-table", interactive=False)

    # When dataset changes: first update horizon choices, then update dropdowns
    dataset_dropdown.change(
        fn=update_horizon_choices,
        inputs=[dataset_dropdown],
        outputs=[horizons],
    ).then(
        fn=update_series_variate_and_window,
        inputs=[dataset_dropdown, horizons],
        outputs=[series_dropdown, variate_dropdown, window_dropdown],
    ).then(
        # After dropdowns are updated, refresh the visualization and table
        fn=plot_window_series,
        inputs=[dataset_dropdown, series_dropdown, variate_dropdown, window_dropdown, horizons, quantiles, model],
        outputs=[ts_visualization, prediction_info]
    ).then(
        fn=get_window_leaderboard,
        inputs=[dataset_dropdown, series_dropdown, variate_dropdown, window_dropdown, horizons],
        outputs=table_window
    )

    # When horizon changes: update dropdowns, then refresh visualization
    horizons.change(
        fn=update_series_variate_and_window,
        inputs=[dataset_dropdown, horizons],
        outputs=[series_dropdown, variate_dropdown, window_dropdown],
    ).then(
        fn=plot_window_series,
        inputs=[dataset_dropdown, series_dropdown, variate_dropdown, window_dropdown, horizons, quantiles, model],
        outputs=[ts_visualization, prediction_info]
    ).then(
        fn=get_window_leaderboard,
        inputs=[dataset_dropdown, series_dropdown, variate_dropdown, window_dropdown, horizons],
        outputs=table_window
    )

    # For series, variate, window changes - update visualization and table
    for comp in [series_dropdown, variate_dropdown, window_dropdown]:
        comp.change(
            fn=get_window_leaderboard,
            inputs=[dataset_dropdown, series_dropdown, variate_dropdown, window_dropdown, horizons],
            outputs=table_window
        )
        comp.change(
            fn=plot_window_series,
            inputs=[dataset_dropdown, series_dropdown, variate_dropdown, window_dropdown, horizons, quantiles, model],
            outputs=[ts_visualization, prediction_info]
        )

    # For quantiles and model changes - only update visualization (no table change needed)
    for comp in [quantiles, model]:
        comp.change(
            fn=plot_window_series,
            inputs=[dataset_dropdown, series_dropdown, variate_dropdown, window_dropdown, horizons, quantiles, model],
            outputs=[ts_visualization, prediction_info]
        )

    # Load initial visualization and table on page load
    demo.load(
        fn=plot_window_series,
        inputs=[dataset_dropdown, series_dropdown, variate_dropdown, window_dropdown, horizons, quantiles, model],
        outputs=[ts_visualization, prediction_info]
    )
    demo.load(
        fn=get_window_leaderboard,
        inputs=[dataset_dropdown, series_dropdown, variate_dropdown, window_dropdown, horizons],
        outputs=table_window
    )

    # CSV Export
    def export_window_csv(dataset, series, variate, window, horizon):
        df = get_window_leaderboard(dataset, series, variate, window, horizon)
        return export_dataframe_to_csv(df, filename_prefix="window_leaderboard")

    with gr.Row():
        export_btn = gr.Button("๐Ÿ“ฅ Export CSV", size="sm")
        export_file = gr.File(label="Download CSV", visible=False)

    export_btn.click(
        fn=export_window_csv,
        inputs=[dataset_dropdown, series_dropdown, variate_dropdown, window_dropdown, horizons],
        outputs=[export_file]
    ).then(
        fn=lambda: gr.File(visible=True),
        inputs=[],
        outputs=[export_file]
    )


def init_per_pattern_tab(demo):
    gr.Markdown(
        """
        This tab allows you to explore model performance based on **selected patterns**.

        Select patterns to filter variates that exhibit those characteristics, then view aggregated model performance.
        Each pattern is a **boolean indicator** derived from time series features (binarized by **median** threshold for continuous features).

        - **Patterns are intersected**: A variate must exhibit ALL selected patterns to be included.
        - **MASE (norm.), CRPS (norm.)**: variate-level results are normalized by Seasonal Naive and aggregated by geometric mean across all matching variates.
        - **MASE (raw), CRPS (raw)**: arithmetic mean across all matching variates.
        """,
        elem_classes="markdown-text"
    )

    # Define pattern choices for Radio components
    PATTERN_CHOICES = ["N/A", "=1", "=0"]

    with gr.Row():  # TSFeatures
        with gr.Column(scale=1):
            with gr.Group():
                gr.Markdown("### ๐Ÿ“ˆ Trend Features")
                T_strength = gr.Radio(
                    choices=PATTERN_CHOICES, value="N/A", label="T_strength"
                )
                T_linearity = gr.Radio(
                    choices=PATTERN_CHOICES, value="N/A", label="T_linearity"
                )
        with gr.Column(scale=1):
            with gr.Group():
                gr.Markdown("### ๐Ÿ”„ Seasonal Features")
                S_strength = gr.Radio(
                    choices=PATTERN_CHOICES, value="N/A", label="S_strength"
                )
                S_corr = gr.Radio(
                    choices=PATTERN_CHOICES, value="N/A", label="S_corr"
                )
        with gr.Column(scale=1):
            with gr.Group():
                gr.Markdown("### ๐ŸŽฏ Residual Features")
                R_ACF1 = gr.Radio(
                    choices=PATTERN_CHOICES, value="N/A", label="R_ACF1"
                )
        with gr.Column(scale=1):
            with gr.Group():
                gr.Markdown("### โš™๏ธ Global Features")
                stationarity = gr.Radio(
                    choices=PATTERN_CHOICES, value="N/A", label="stationarity"
                )
                complexity = gr.Radio(
                    choices=PATTERN_CHOICES, value="N/A", label="complexity"
                )

    # List of all pattern Radio components and their names
    pattern_radios = [
        T_strength, T_linearity,
        S_strength, S_corr,
        R_ACF1,
        stationarity, complexity
    ]
    pattern_names = [
        "T_strength", "T_linearity",
        "S_strength", "S_corr",
        "R_ACF1",
        "stationarity", "complexity"
    ]

    with gr.Row():
        with gr.Column(scale=1):
            horizons = gr.CheckboxGroup(
                choices=ALL_HORIZONS,
                value=ALL_HORIZONS,
                label="Horizons"
            )
        with gr.Column(scale=2):
            msg_pattern = gr.Textbox(label="Status", interactive=False, lines=4)

    table_variates = gr.DataFrame(elem_classes="custom-table", interactive=False)

    def merge_patterns(*radio_values):
        """Convert Radio values to pattern filter dict.

        Args:
            *radio_values: Values from all Radio components in order of pattern_names

        Returns:
            dict: {feature_name: required_value} where required_value is 0 or 1.
                  Features with "N/A" are not included in the dict.
        """
        result = {}
        for name, value in zip(pattern_names, radio_values):
            if value == "=1":
                result[name] = 1
            elif value == "=0":
                result[name] = 0
            # "N/A" -> don't include in dict (no filter on this feature)
        return result

    def update_leaderboard(*args):
        """Callback to update the pattern leaderboard.

        Args:
            *args: All Radio values followed by horizons (last argument)
        """
        # Last argument is horizons, rest are pattern radio values
        horizons_val = args[-1]
        radio_values = args[:-1]
        pattern_filters = merge_patterns(*radio_values)
        return get_pattern_leaderboard(pattern_filters, horizons_val)

    # Bind change events for all pattern radios and horizons
    all_inputs = pattern_radios + [horizons]
    for comp in all_inputs:
        comp.change(
            fn=update_leaderboard,
            inputs=all_inputs,
            outputs=[msg_pattern, table_variates]
        )

    # Load initial state
    demo.load(
        fn=update_leaderboard,
        inputs=all_inputs,
        outputs=[msg_pattern, table_variates]
    )

    # CSV Export
    def export_pattern_csv(*args):
        # Last argument is horizons, rest are pattern radio values
        horizons_val = args[-1]
        radio_values = args[:-1]
        pattern_filters = merge_patterns(*radio_values)
        _, df = get_pattern_leaderboard(pattern_filters, horizons_val)
        return export_dataframe_to_csv(df, filename_prefix="pattern_leaderboard")

    with gr.Row():
        export_btn = gr.Button("๐Ÿ“ฅ Export CSV", size="sm")
        export_file = gr.File(label="Download CSV", visible=False)

    export_btn.click(
        fn=export_pattern_csv,
        inputs=all_inputs,
        outputs=[export_file]
    ).then(
        fn=lambda: gr.File(visible=True),
        inputs=[],
        outputs=[export_file]
    )


# # ToDO: Now the archive is using different features from the ones in per_pattern tab
# def init_archive_tab(demo):
#     gr.Markdown(
#         """
#         This tab provides an interactive archive of the features of time series variates across datasets. You can explore the archive by specifying a dataset, domain, and frequency, and filter variates with the selected structural patterns. Each pattern is a **boolean indicator** showing whether a variate exhibits the pattern, with thresholds derived from the distribution of feature values across the entire dataset. Pattern filters are applied as an **intersection** (a variate must exhibit all selected patterns). Domain and frequency filters are applied as a **union** (a variate may belong to any selected category). The resulting table displays all variates that satisfy the chosen filters, together with their dataset, frequency, domain, and computed feature values. This view makes it possible to identify and group variates that share similar feature profiles.
#         """
#     )

#     with gr.Row():
#         with gr.Column(scale=1):
#             dataset_dropdown = gr.Dropdown(
#                 choices=["All"] + sorted(FEATURES_BOOL_DF["dataset"].unique().tolist()),
#                 value="All",
#                 label="Select Dataset"
#             )

#             variate_dropdown = gr.Dropdown(
#                 choices=["All"],
#                 value="All",
#                 label="Select Variate",
#                 interactive=False
#             )

#             domains = gr.CheckboxGroup(
#                 choices=ALL_DOMAINS,
#                 value=ALL_DOMAINS,  # default all checked
#                 label="Domains"
#             )

#             freqs = gr.CheckboxGroup(
#                 choices=ALL_FREQS,
#                 value=ALL_FREQS,  # ้ป˜่ฎคๅ…จ้€‰
#                 label="Frequencies"
#             )

#         with gr.Column(scale=2):
#             trend_group = gr.CheckboxGroup(
#                 choices=["trend", "trend_stability", "trend_lumpiness", "trend_hurst", "trend_entropy"],
#                 label="Trend Patterns"
#             )

#             season_group = gr.CheckboxGroup(
#                 choices=["seasonal_strength", "seasonality_corr", "seasonal_stability",
#                          "seasonal_lumpiness", "seasonal_hurst", "seasonal_entropy"],
#                 label="Seasonality Patterns"
#             )

#             remainder_group = gr.CheckboxGroup(
#                 choices=["e_acf1", "e_acf10",
#                          "e_entropy", "e_hurst", "e_lumpiness", "e_outlier_ratio"],
#                 label="Remainder Patterns"
#             )

#             global_group = gr.CheckboxGroup(
#                 choices=["x_acf1", "x_acf10", "lumpiness", "stability", "hurst", "entropy"],
#                 label="Global Patterns"
#             )

#             msg_box = gr.Textbox(
#                 label="Message",
#                 interactive=False
#             )

#     archive_leaderboard = gr.DataFrame(
#         elem_classes="custom-table",
#         elem_id="archive-table",
#         max_height=600,
#         interactive=False
#     )

#     # ็ป‘ๅฎšไบ‹ไปถ
#     domains.change(
#         fn=update_dataset_choices,
#         inputs=[domains, freqs],
#         outputs=dataset_dropdown
#     )

#     freqs.change(
#         fn=update_dataset_choices,
#         inputs=[domains, freqs],
#         outputs=dataset_dropdown
#     )

#     # Change DF
#     for comp in [dataset_dropdown, trend_group, season_group, remainder_group, global_group]:
#         comp.change(
#             fn=update_variate_choices_groups,
#             inputs=[dataset_dropdown, trend_group, season_group, remainder_group, global_group],
#             outputs=variate_dropdown
#         )
#         comp.change(
#             fn=collect_patterns,
#             inputs=[dataset_dropdown, trend_group, season_group, remainder_group, global_group,
#                     variate_dropdown, domains, freqs],
#             outputs=[msg_box, archive_leaderboard]
#         )

#     for comp in [variate_dropdown, domains, freqs]:
#         comp.change(
#             fn=collect_patterns,
#             inputs=[dataset_dropdown, trend_group, season_group, remainder_group, global_group,
#                     variate_dropdown, domains, freqs],
#             outputs=[msg_box, archive_leaderboard]
#         )

#     # Initial Load
#     demo.load(
#         fn=collect_patterns,
#         inputs=[dataset_dropdown, trend_group, season_group, remainder_group, global_group,
#                 variate_dropdown, domains, freqs],
#         outputs=[msg_box, archive_leaderboard]
#     )