import json
import os

def load_annotations(annotations_path,task_key="action", exclude_labels=["", "Challenge"]):
    
    with open(annotations_path, "r") as f:
        data = json.load(f)

    # Excluding some labels
    exclude_labels = set(exclude_labels or ["", "Challenge"])

    # label list for the selected task
    label_list = [
        lbl for lbl in data["labels"][task_key]["labels"]
        if lbl not in exclude_labels
    ]
    label_map = {name: idx for idx, name in enumerate(label_list)}
    print(label_list, label_map)
    samples = []

    for item in data["data"]:
        # read the action label
        action_label = item["labels"][task_key]["label"]

        if action_label in exclude_labels:
            continue
        
        if action_label not in label_map:
            continue

        label_idx = label_map[action_label]

        # Collect all clip paths
        clips = [
            inp["path"]
            for inp in item.get("inputs", [])
            if inp.get("type") == "video" and "path" in inp
        ]
        if not clips:
            continue

        samples.append({
            "video_paths": clips,   # supports multi-view automatically
            "label": label_idx,
        })

    return samples


# def load_annotations(annotations_path, exclude_labels=None):
#     with open(annotations_path, "r") as f:
#         data = json.load(f)

#     exclude_labels = exclude_labels or ["", "Challenge"]
#     # Filter labels
#     label_list = [
#         name for name in data["labels"]["foul_type"]["labels"]
#         if name not in exclude_labels
#     ]
    
#     label_map = {name: idx for idx, name in enumerate(label_list)}
#     samples = []
    
#     for item in data["data"]:
#         foul_label = item["labels"]["foul_type"]["label"]
        
#         # Skip unwanted labels
#         if foul_label in exclude_labels:
#             continue

#         label_idx = label_map.get(foul_label, -1)
#         if label_idx == -1:
#             continue

#         # collect *all* video clips
#         all_clips = [
#             c.get("path", "") for c in item.get("inputs", [])
#             if c.get("type") == "video"
#         ]
#         all_clips = [p.replace("Dataset/Train", "train")
#                      .replace("Dataset/Test", "test")
#                      .replace("Dataset/Valid", "valid") + ".mp4"
#                      for p in all_clips if p]

#         if not all_clips:
#             continue

#         samples.append({
#             "video_paths": all_clips,
#             "label": label_idx
#         })
#     print(label_map)
#     return samples
