import sys
import os

# 添加當前目錄到系統路徑
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from Load_process.LoadData import Loding_Data_Root
from utils.Stomach_Config import Loading_Config
from merge_class.merge import merge

def test_mask_loading():
    print("測試掩碼數據加載...")
    
    # 確保Loading_Config中包含必要的配置項
    required_configs = [
        "Label_Image_Labels", "Annotation_Root"
    ]
    
    for config in required_configs:
        if config not in Loading_Config:
            print(f"錯誤：缺少配置項 {config}")
            return
    
    print(f"Label_Image_Labels: {Loading_Config['Label_Image_Labels']}")
    print(f"Annotation_Root: {Loading_Config['Annotation_Root']}")
    
    # 加載掩碼數據
    try:
        print("\n嘗試加載掩碼數據...")
        Mask_load = Loding_Data_Root(Loading_Config["Label_Image_Labels"], Loading_Config['Annotation_Root'], "")
        Mask_Data_Dict_Data = Mask_load.process_main(False)
        
        print("\n掩碼數據加載結果:")
        if not Mask_Data_Dict_Data:
            print("錯誤：Mask_Data_Dict_Data為空")
        else:
            Mask_Keys = list(Mask_Data_Dict_Data.keys())
            print(f"Mask_Keys: {Mask_Keys}")
            
            for key in Mask_Keys:
                print(f"Key: {key}, 數據長度: {len(Mask_Data_Dict_Data[key])}")
            
            # 嘗試合併掩碼數據
            if len(Mask_Keys) >= 2:
                print("\n嘗試合併掩碼數據...")
                Merge = merge()
                Training_Mask_Data = Merge.merge_all_image_data(Mask_Data_Dict_Data[Mask_Keys[0]], Mask_Data_Dict_Data[Mask_Keys[1]])
                print(f"合併後的掩碼數據長度: {len(Training_Mask_Data)}")
            else:
                print("\n無法合併掩碼數據：Mask_Keys長度小於2")
    
    except Exception as e:
        print(f"\n加載掩碼數據時出錯: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    test_mask_loading()