#!/bin/bash

# AI Commit Scope Helper
# Interactive tool to help developers choose consistent scopes

set -e

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
CONFIG_FILE="$PROJECT_ROOT/config/ai-prompts.conf"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
GRAY='\033[0;37m'
NC='\033[0m' # No Color

# Check if config exists
if [ ! -f "$CONFIG_FILE" ]; then
    echo -e "${RED}❌ AI commit configuration not found${NC}"
    echo -e "${YELLOW}💡 Run 'ai-commit-toolkit setup' first${NC}"
    exit 1
fi

# Source the configuration
source "$CONFIG_FILE"

# Function to parse scope mappings
parse_scopes() {
    local scope_var="$1"
    echo "$scope_var" | tr '|' '\n' | while IFS=':' read -r scope desc; do
        printf "%-25s %s\n" "$scope" "$desc"
    done
}

# Function to show scope categories
show_scopes() {
    echo -e "${BLUE}🏷️  Available Commit Scopes${NC}"
    echo -e "${GRAY}============================${NC}"
    echo ""
    
    if [ -n "$SCOPE_MAP_FEATURES" ]; then
        echo -e "${CYAN}🎯 Feature Areas${NC}"
        echo -e "${GRAY}─────────────────${NC}"
        parse_scopes "$SCOPE_MAP_FEATURES"
        echo ""
    fi
    
    if [ -n "$SCOPE_MAP_TECHNICAL" ]; then
        echo -e "${CYAN}⚙️  Technical Areas${NC}"
        echo -e "${GRAY}────────────────────${NC}"
        parse_scopes "$SCOPE_MAP_TECHNICAL"
        echo ""
    fi
    
    if [ -n "$SCOPE_MAP_CONCERNS" ]; then
        echo -e "${CYAN}🔄 Cross-cutting Concerns${NC}"
        echo -e "${GRAY}──────────────────────────${NC}"
        parse_scopes "$SCOPE_MAP_CONCERNS"
        echo ""
    fi
    
    if [ -n "$SCOPE_MAP_EXAMPLES" ]; then
        echo -e "${CYAN}📝 Sub-scope Examples${NC}"
        echo -e "${GRAY}──────────────────────${NC}"
        parse_scopes "$SCOPE_MAP_EXAMPLES"
        echo ""
    fi
}

# Function to validate scope
validate_scope() {
    local scope="$1"
    
    # If no allowed scopes defined, accept any scope
    if [ -z "$ALLOWED_SCOPES" ]; then
        return 0
    fi
    
    # Check if scope is in allowed list
    echo "$ALLOWED_SCOPES" | tr ',' '\n' | grep -q "^$scope$"
}

# Function to suggest scope based on file patterns
suggest_scope() {
    echo -e "${YELLOW}🔍 Analyzing changed files for scope suggestions...${NC}"
    
    # Get list of changed files
    if git rev-parse --git-dir > /dev/null 2>&1; then
        local changed_files
        changed_files=$(git diff --cached --name-only 2>/dev/null || git diff --name-only HEAD~1 2>/dev/null || echo "")
        
        if [ -n "$changed_files" ]; then
            echo -e "${GRAY}Changed files:${NC}"
            echo "$changed_files" | sed 's/^/  /'
            echo ""
            
# Function to get enhanced scope suggestion for a single file
get_file_scope() {
    local file="$1"
    
    # Enhanced hierarchical path pattern matching
    case "$file" in
        # Mail features - hierarchical detection
        *mail*allow*block* | *allowblock* | *blocklist* | */mail/allow-block* | */allow-block-list*)
            echo "mail.allow-block-lists"
            ;;
        *mail*quarantine* | */mail/quarantine*)
            echo "mail.quarantine"
            ;;
        *mail*scan* | *mail*filter* | */mail/scanning* | */mail/filter*)
            echo "mail.scanning"
            ;;
        */mail/* | *mail*)
            echo "mail"
            ;;
        
        # DNS features - hierarchical detection
        *dns*polic* | */dns/policies* | */dns-policies*)
            echo "dns.policies"
            ;;
        *dns*rule* | *dns*custom* | */dns/custom-rules* | */dns/rules*)
            echo "dns.custom-rules"
            ;;
        */dns/* | *dns*)
            echo "dns"
            ;;
        
        # Reports features - hierarchical detection
        *report*traffic* | *email*traffic* | */reports/email-traffic* | */reports/traffic*)
            echo "reports.email-traffic"
            ;;
        *report*threat* | *threat*detect* | */reports/threat* | */threat-detection*)
            echo "reports.threat-detection"
            ;;
        */reports/* | *report*)
            echo "reports"
            ;;
        
        # Settings features - hierarchical detection
        *setting*notification* | */settings/notifications* | */notification-settings*)
            echo "settings.notifications"
            ;;
        *setting*integration* | */settings/integrations* | */integration-settings*)
            echo "settings.integrations"
            ;;
        */settings/* | *setting*)
            echo "settings"
            ;;
        
        # Auth features - hierarchical detection
        *auth*mfa* | *auth*multi* | */auth/mfa* | */multi-factor*)
            echo "auth.mfa"
            ;;
        *auth*sso* | *auth*single* | */auth/sso* | */single-sign*)
            echo "auth.sso"
            ;;
        */auth/* | *auth* | *login* | *user-management*)
            echo "auth"
            ;;
        
        # Other feature areas
        */billing/* | *billing* | *payment* | *subscription*)
            echo "billing"
            ;;
        */onboarding/* | *onboarding* | *welcome* | *setup-wizard*)
            echo "onboarding"
            ;;
        */dashboard/* | *dashboard* | *overview* | *main-page*)
            echo "dashboard"
            ;;
        */admin/* | *admin* | *administration*)
            echo "admin"
            ;;
        
        # Technical areas - enhanced detection
        */api/* | *api* | *endpoint* | *service* | */services/* | */controllers/*)
            echo "api"
            ;;
        */components/* | */ui/* | *component* | *interface* | */styles/* | *.css | *.scss | *.vue)
            echo "ui"
            ;;
        */database/* | */db/* | *migration* | *schema* | *.sql)
            echo "db"
            ;;
        */test/* | */tests/* | *test* | *spec* | *.test.* | *.spec.*)
            echo "tests"
            ;;
        */doc/* | */docs/* | *readme* | *documentation* | *.md)
            echo "docs"
            ;;
        */infrastructure/* | */infra/* | */deploy/* | *docker* | *kubernetes* | *.yml | *.yaml)
            echo "infra"
            ;;
        
        # Cross-cutting concerns - enhanced detection
        *a11y* | *accessibility* | */accessibility/* | *aria* | *wcag*)
            echo "a11y"
            ;;
        *i18n* | *internationalization* | */locales/* | */translations/* | *locale*)
            echo "i18n"
            ;;
        *mobile* | */mobile/* | *responsive* | *touch*)
            echo "mobile"
            ;;
        *seo* | */seo/* | *meta* | *sitemap*)
            echo "seo"
            ;;
        *analytics* | */analytics/* | *tracking* | *metrics*)
            echo "analytics"
            ;;
        *monitoring* | */monitoring/* | *health* | *status*)
            echo "monitoring"
            ;;
        *security* | */security/* | *encryption* | *permission*)
            echo "security"
            ;;
        *performance* | *perf* | */performance/* | *optimization*)
            echo "perf"
            ;;
        
        *)
            echo ""
            ;;
    esac
}

# Function to suggest scope based on file patterns
suggest_scope() {
    echo -e "${YELLOW}� Analyzing changed files for scope suggestions...${NC}"
    
    # Get list of changed files
    if git rev-parse --git-dir > /dev/null 2>&1; then
        local changed_files
        changed_files=$(git diff --cached --name-only 2>/dev/null || git diff --name-only HEAD~1 2>/dev/null || echo "")
        
        if [ -n "$changed_files" ]; then
            echo -e "${GRAY}Changed files:${NC}"
            
            local detected_scopes=()
            local primary_scope=""
            local confidence="low"
            
            # Analyze each file individually
            while IFS= read -r file; do
                [ -z "$file" ] && continue
                
                local scope=$(get_file_scope "$file")
                echo -n "  $file"
                
                if [ -n "$scope" ]; then
                    echo -e " ${GREEN}→ $scope${NC}"
                    detected_scopes+=("$scope")
                    
                    # Set primary scope (prefer hierarchical scopes)
                    if [ -z "$primary_scope" ] || [[ "$scope" == *.* ]]; then
                        primary_scope="$scope"
                        if [[ "$scope" == *.* ]]; then
                            confidence="high"
                        else
                            confidence="medium"
                        fi
                    fi
                else
                    echo -e " ${GRAY}→ no scope detected${NC}"
                fi
            done <<< "$changed_files"
            
            echo ""
            
            if [ ${#detected_scopes[@]} -eq 0 ]; then
                echo -e "${GRAY}💡 No specific scope patterns detected${NC}"
                echo -e "${GRAY}💡 Consider using a general scope like 'chore', 'refactor', or 'feat'${NC}"
                return
            fi
            
            # Find most common scope
            local common_scope=$(printf '%s\n' "${detected_scopes[@]}" | sort | uniq -c | sort -nr | head -1 | awk '{print $2}')
            local unique_scopes=$(printf '%s\n' "${detected_scopes[@]}" | sort -u | wc -l)
            
            echo -e "${GREEN}📊 Scope Analysis Results:${NC}"
            echo "  Primary scope: $primary_scope"
            echo "  Most common: $common_scope"
            echo "  Confidence: $confidence"
            echo "  Unique scopes: $unique_scopes"
            echo ""
            
            # Provide specific suggestion
            if [ "$unique_scopes" -eq 1 ]; then
                echo -e "${CYAN}💡 Suggested scope: ${NC}$primary_scope ${GRAY}(all files in same area)${NC}"
            elif [ "$confidence" = "high" ]; then
                echo -e "${CYAN}💡 Suggested scope: ${NC}$primary_scope ${GRAY}(high confidence from file paths)${NC}"
            else
                echo -e "${CYAN}💡 Suggested scope: ${NC}$common_scope ${GRAY}(most common across files)${NC}"
            fi
            
            # Show example commit
            local suggested_scope="$primary_scope"
            [ -z "$suggested_scope" ] && suggested_scope="$common_scope"
            echo -e "${GRAY}Example: feat($suggested_scope): add new functionality${NC}"
            echo ""
        fi
    fi
}
        fi
    fi
}

# Main menu
show_menu() {
    echo -e "${BLUE}🤖 AI Commit Scope Helper${NC}"
    echo -e "${GRAY}===========================${NC}"
    echo ""
    echo "1. Show all available scopes"
    echo "2. Suggest scope based on changed files"
    echo "3. Validate a scope"
    echo "4. Generate example commit message"
    echo "5. Exit"
    echo ""
}

# Interactive mode
if [ "$1" = "--interactive" ] || [ "$1" = "-i" ]; then
    while true; do
        show_menu
        read -p "Choose an option (1-5): " choice
        echo ""
        
        case $choice in
            1)
                show_scopes
                echo ""
                read -p "Press Enter to continue..."
                clear
                ;;
            2)
                suggest_scope
                read -p "Press Enter to continue..."
                clear
                ;;
            3)
                read -p "Enter scope to validate: " scope
                if validate_scope "$scope"; then
                    echo -e "${GREEN}✅ Scope '$scope' is valid${NC}"
                else
                    echo -e "${RED}❌ Scope '$scope' is not in allowed list${NC}"
                    if [ -n "$ALLOWED_SCOPES" ]; then
                        echo -e "${YELLOW}Allowed scopes: $ALLOWED_SCOPES${NC}"
                    fi
                fi
                echo ""
                read -p "Press Enter to continue..."
                clear
                ;;
            4)
                read -p "Enter commit type (feat/fix/chore/etc): " type
                read -p "Enter scope: " scope
                read -p "Enter description: " desc
                echo ""
                echo -e "${GREEN}Example commit message:${NC}"
                echo -e "${CYAN}$type($scope): $desc${NC}"
                echo ""
                read -p "Press Enter to continue..."
                clear
                ;;
            5)
                echo "Goodbye!"
                exit 0
                ;;
            *)
                echo -e "${RED}Invalid option. Please choose 1-5.${NC}"
                echo ""
                read -p "Press Enter to continue..."
                clear
                ;;
        esac
    done
fi

# Command line mode
case "$1" in
    "show"|"list"|"")
        show_scopes
        ;;
    "suggest")
        suggest_scope
        ;;
    "validate")
        if [ -z "$2" ]; then
            echo -e "${RED}❌ Please provide a scope to validate${NC}"
            echo "Usage: $0 validate <scope>"
            exit 1
        fi
        if validate_scope "$2"; then
            echo -e "${GREEN}✅ Scope '$2' is valid${NC}"
        else
            echo -e "${RED}❌ Scope '$2' is not in allowed list${NC}"
            if [ -n "$ALLOWED_SCOPES" ]; then
                echo -e "${YELLOW}Allowed scopes: $ALLOWED_SCOPES${NC}"
            fi
            exit 1
        fi
        ;;
    "help"|"-h"|"--help")
        echo "AI Commit Scope Helper"
        echo ""
        echo "Usage:"
        echo "  $0                    Show all available scopes"
        echo "  $0 show               Show all available scopes"
        echo "  $0 suggest            Suggest scope based on changed files"
        echo "  $0 validate <scope>   Validate a scope"
        echo "  $0 -i                 Interactive mode"
        echo "  $0 --interactive      Interactive mode"
        echo "  $0 help               Show this help message"
        ;;
    *)
        echo -e "${RED}❌ Unknown command: $1${NC}"
        echo "Use '$0 help' for usage information"
        exit 1
        ;;
esac
