#!/bin/bash

# DramaLing 架構健康檢查腳本

echo "🏛️ DramaLing 架構健康檢查"
echo "=================================="
echo "檢查時間: $(date)"
echo ""

# 變數定義
BACKEND_PATH="backend/DramaLing.Api"
SERVICES_PATH="$BACKEND_PATH/Services"
CONTROLLERS_PATH="$BACKEND_PATH/Controllers"

# 計數器
ISSUES=0
WARNINGS=0

# 顏色輔助
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

# 檢查函數
check_service_size() {
    echo "📏 檢查服務大小..."

    LARGE_SERVICES=$(find "$SERVICES_PATH" -name "*Service.cs" -exec wc -l {} + | awk '$1 > 300 {print $2 " (" $1 " lines)"}')

    if [ ! -z "$LARGE_SERVICES" ]; then
        echo -e "${YELLOW}⚠️ 發現過大的服務文件:${NC}"
        echo "$LARGE_SERVICES"
        echo "   建議: 考慮拆分為多個更小的服務"
        ((WARNINGS++))
    else
        echo -e "${GREEN}✅ 所有服務大小適中 (< 300行)${NC}"
    fi
    echo ""
}

check_interface_coverage() {
    echo "🎯 檢查介面覆蓋率..."

    SERVICE_COUNT=$(find "$SERVICES_PATH" -name "*Service.cs" -not -name "I*Service.cs" | wc -l)
    INTERFACE_COUNT=$(find "$SERVICES_PATH" -name "I*Service.cs" | wc -l)

    if [ $SERVICE_COUNT -gt 0 ]; then
        COVERAGE=$((INTERFACE_COUNT * 100 / SERVICE_COUNT))

        if [ $COVERAGE -lt 80 ]; then
            echo -e "${YELLOW}⚠️ 介面覆蓋率較低: $COVERAGE% ($INTERFACE_COUNT/$SERVICE_COUNT)${NC}"
            echo "   建議: 為服務添加介面定義"
            ((WARNINGS++))
        else
            echo -e "${GREEN}✅ 介面覆蓋率良好: $COVERAGE% ($INTERFACE_COUNT/$SERVICE_COUNT)${NC}"
        fi
    fi
    echo ""
}

check_naming_convention() {
    echo "🏷️ 檢查命名規範..."

    BAD_NAMES=$(find "$SERVICES_PATH" -name "*Helper.cs" -o -name "*Utils.cs" -o -name "*Manager.cs" | grep -v Interface)

    if [ ! -z "$BAD_NAMES" ]; then
        echo -e "${YELLOW}⚠️ 發現不符規範的命名:${NC}"
        echo "$BAD_NAMES"
        echo "   建議: 使用 Service 後綴"
        ((WARNINGS++))
    else
        echo -e "${GREEN}✅ 命名規範符合標準${NC}"
    fi
    echo ""
}

check_dependency_patterns() {
    echo "🔗 檢查依賴模式..."

    # 檢查 Controller 是否直接依賴 Repository
    CONTROLLER_REPO_DEPS=$(grep -r "IRepository\|Repository" "$CONTROLLERS_PATH" 2>/dev/null || true)

    if [ ! -z "$CONTROLLER_REPO_DEPS" ]; then
        echo -e "${RED}❌ 發現 Controller 直接依賴 Repository:${NC}"
        echo "$CONTROLLER_REPO_DEPS" | head -3
        echo "   建議: Controller 應該通過 Service 層訪問數據"
        ((ISSUES++))
    else
        echo -e "${GREEN}✅ Controller 依賴關係正確${NC}"
    fi
    echo ""
}

check_todo_items() {
    echo "📝 檢查 TODO 項目..."

    TODO_COUNT=$(find "$BACKEND_PATH" -name "*.cs" -exec grep -l "TODO\|FIXME\|HACK" {} \; | wc -l)

    if [ $TODO_COUNT -gt 0 ]; then
        echo -e "${YELLOW}⚠️ 發現 $TODO_COUNT 個文件包含 TODO 項目${NC}"
        echo "   最近的 TODO:"
        find "$BACKEND_PATH" -name "*.cs" -exec grep -n "TODO\|FIXME\|HACK" {} \; | head -3
        ((WARNINGS++))
    else
        echo -e "${GREEN}✅ 沒有未完成的 TODO 項目${NC}"
    fi
    echo ""
}

check_cache_performance() {
    echo "⚡ 檢查快取性能..."

    if curl -s http://localhost:5008/api/ai/stats > /dev/null 2>&1; then
        CACHE_STATS=$(curl -s http://localhost:5008/api/ai/stats)
        HIT_RATE=$(echo "$CACHE_STATS" | grep -o '"cacheHitRate":[0-9.]*' | cut -d: -f2)

        if [ ! -z "$HIT_RATE" ]; then
            HIT_PERCENTAGE=$(echo "$HIT_RATE * 100" | bc -l | cut -d. -f1)

            if [ "$HIT_PERCENTAGE" -lt 50 ]; then
                echo -e "${YELLOW}⚠️ 快取命中率較低: $HIT_PERCENTAGE%${NC}"
                ((WARNINGS++))
            else
                echo -e "${GREEN}✅ 快取命中率良好: $HIT_PERCENTAGE%${NC}"
            fi
        fi
    else
        echo -e "${YELLOW}⚠️ 無法連接到後端服務檢查快取狀態${NC}"
        ((WARNINGS++))
    fi
    echo ""
}

# 主要檢查流程
main() {
    check_service_size
    check_interface_coverage
    check_naming_convention
    check_dependency_patterns
    check_todo_items
    check_cache_performance

    # 總結
    echo "=================================="
    echo "🏛️ 架構檢查總結:"

    if [ $ISSUES -eq 0 ] && [ $WARNINGS -eq 0 ]; then
        echo -e "${GREEN}🎉 架構健康度: 優秀${NC}"
        echo "✅ 沒有發現架構問題"
        exit 0
    elif [ $ISSUES -eq 0 ]; then
        echo -e "${YELLOW}😊 架構健康度: 良好${NC}"
        echo "⚠️  發現 $WARNINGS 個警告項目"
        exit 0
    else
        echo -e "${RED}😟 架構健康度: 需要改善${NC}"
        echo "❌ 發現 $ISSUES 個問題"
        echo "⚠️  發現 $WARNINGS 個警告"
        exit 1
    fi
}

# 檢查是否在正確目錄
if [ ! -d "$BACKEND_PATH" ]; then
    echo -e "${RED}❌ 請在專案根目錄執行此腳本${NC}"
    exit 1
fi

# 執行檢查
main