#!/usr/bin/env python3
"""
測試 Fuzzy C-means 聚類功能
"""

import os
import sys
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

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

# 導入我們的函數
from Density_Peak_Algorithm import (
    compute_decision_graph,
    fuzzy_c_means,
    determine_optimal_clusters,
    extract_superpixel_features
)

def test_fuzzy_clustering():
    """
    測試 Fuzzy C-means 聚類功能
    """
    print("🧪 開始測試 Fuzzy C-means 聚類功能...")
    
    # 測試圖像路徑
    test_image_path = "example_images/sample_image_1.png"
    
    if not os.path.exists(test_image_path):
        print(f"❌ 測試圖像不存在: {test_image_path}")
        return False
    
    # 創建測試輸出目錄
    test_output_dir = "test_clustering_output"
    os.makedirs(test_output_dir, exist_ok=True)
    
    try:
        print(f"📸 測試圖像: {test_image_path}")
        
        # 執行完整的密度峰值分析 + Fuzzy C-means 聚類
        result = compute_decision_graph(
            test_image_path,
            test_output_dir,
            use_superpixels=True,
            save_regions=True,
            max_regions=30  # 限制區域數量以加快測試
        )
        
        print(f"\n✅ 測試成功完成!")
        print(f"📊 結果摘要:")
        print(f"   - 超像素數量: {result['n_superpixels']}")
        print(f"   - 最佳聚類數: {result['optimal_clusters']}")
        print(f"   - 聚類迭代次數: {result['clustering_iterations']}")
        print(f"   - 目標函數值: {result['clustering_objective']:.4f}")
        print(f"   - 壓縮比例: {result['compression_ratio']:.6f}")
        
        # 驗證結果的完整性
        required_keys = [
            'rho', 'delta', 'gamma', 'n', 'segments', 'superpixel_features',
            'optimal_clusters', 'cluster_centers', 'membership_matrix', 
            'cluster_labels', 'cluster_stats'
        ]
        
        missing_keys = [key for key in required_keys if key not in result]
        if missing_keys:
            print(f"⚠️  警告: 缺少以下結果鍵: {missing_keys}")
        else:
            print(f"✅ 所有必要的結果鍵都存在")
        
        # 驗證聚類結果的合理性
        n_clusters = result['optimal_clusters']
        cluster_labels = result['cluster_labels']
        membership_matrix = result['membership_matrix']
        
        # 檢查聚類標籤範圍
        unique_labels = np.unique(cluster_labels)
        if len(unique_labels) == n_clusters and np.min(unique_labels) >= 0 and np.max(unique_labels) < n_clusters:
            print(f"✅ 聚類標籤範圍正確: {len(unique_labels)} 個聚類")
        else:
            print(f"⚠️  聚類標籤範圍異常: 期望 {n_clusters} 個聚類，實際 {len(unique_labels)} 個")
        
        # 檢查隸屬度矩陣
        membership_sums = np.sum(membership_matrix, axis=1)
        if np.allclose(membership_sums, 1.0, atol=1e-6):
            print(f"✅ 隸屬度矩陣正確: 每行和為 1")
        else:
            print(f"⚠️  隸屬度矩陣異常: 行和範圍 [{np.min(membership_sums):.6f}, {np.max(membership_sums):.6f}]")
        
        print(f"\n📁 測試結果保存在: {test_output_dir}")
        return True
        
    except Exception as e:
        print(f"❌ 測試失敗: {e}")
        import traceback
        traceback.print_exc()
        return False

def test_individual_functions():
    """
    測試個別函數
    """
    print(f"\n🔬 測試個別函數...")
    
    # 創建測試數據
    np.random.seed(42)
    test_data = np.random.rand(50, 5)  # 50個樣本，5個特徵
    
    try:
        # 測試 fuzzy_c_means 函數
        print(f"🧪 測試 fuzzy_c_means 函數...")
        centers, membership, labels, objective, n_iter = fuzzy_c_means(
            test_data, n_clusters=3, m=2.0, max_iter=50, random_state=42
        )
        
        print(f"   - 聚類中心形狀: {centers.shape}")
        print(f"   - 隸屬度矩陣形狀: {membership.shape}")
        print(f"   - 標籤形狀: {labels.shape}")
        print(f"   - 目標函數值: {objective:.4f}")
        print(f"   - 迭代次數: {n_iter}")
        
        # 測試 determine_optimal_clusters 函數
        print(f"🧪 測試 determine_optimal_clusters 函數...")
        gamma_values = np.random.exponential(2, 50)  # 模擬 gamma 值
        optimal_k, scores = determine_optimal_clusters(
            test_data, gamma_values, max_clusters=6, min_clusters=2
        )
        
        print(f"   - 最佳聚類數: {optimal_k}")
        print(f"   - 測試的聚類數: {list(scores.keys())}")
        
        print(f"✅ 個別函數測試成功!")
        return True
        
    except Exception as e:
        print(f"❌ 個別函數測試失敗: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    print("🚀 開始 Fuzzy C-means 聚類功能測試")
    print("="*60)
    
    # 測試個別函數
    individual_test_success = test_individual_functions()
    
    print("\n" + "="*60)
    
    # 測試完整流程
    full_test_success = test_fuzzy_clustering()
    
    print("\n" + "="*60)
    print("📋 測試結果摘要:")
    print(f"   - 個別函數測試: {'✅ 通過' if individual_test_success else '❌ 失敗'}")
    print(f"   - 完整流程測試: {'✅ 通過' if full_test_success else '❌ 失敗'}")
    
    if individual_test_success and full_test_success:
        print(f"\n🎉 所有測試通過! Fuzzy C-means 聚類功能正常工作")
    else:
        print(f"\n⚠️  部分測試失敗，請檢查代碼")