#!/bin/bash

# Enhanced Scope Detection Script
# Reads scope metadata from files and directories

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
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'

# Function to extract scope from file metadata
extract_file_scope() {
    local file="$1"
    local scope=""
    
    if [ ! -f "$file" ]; then
        return 1
    fi
    
    # Try different comment formats
    scope=$(head -20 "$file" | grep -E "(AI-SCOPE|@scope)" | head -1 | sed -E 's/.*[:=]\s*([a-zA-Z0-9.-]+).*/\1/' | tr -d '"' || true)
    
    if [ -n "$scope" ]; then
        echo "$scope"
        return 0
    fi
    
    return 1
}

# Function to extract scope from directory metadata
extract_directory_scope() {
    local file_path="$1"
    local dir=$(dirname "$file_path")
    local filename=$(basename "$file_path")
    
    # Look for .ai-scopes.json in current and parent directories
    while [ "$dir" != "." ] && [ "$dir" != "/" ]; do
        local scope_file="$dir/.ai-scopes.json"
        
        if [ -f "$scope_file" ]; then
            # Try to find specific mapping for this file/directory
            local relative_path="${file_path#$dir/}"
            local scope=$(jq -r --arg path "$relative_path" --arg file "$filename" '
                .[$path] // .[$file] // .default // empty
            ' "$scope_file" 2>/dev/null || true)
            
            if [ -n "$scope" ] && [ "$scope" != "null" ]; then
                echo "$scope"
                return 0
            fi
        fi
        
        dir=$(dirname "$dir")
    done
    
    return 1
}

# Function to suggest scope based on file path patterns
suggest_path_scope() {
    local file="$1"
    
    # Enhanced pattern matching
    case "$file" in
        *mail*allow*block* | *allowblock* | *blocklist*)
            echo "mail.allow-block-lists"
            ;;
        *mail*quarantine*)
            echo "mail.quarantine"
            ;;
        *mail*scan* | *mail*filter*)
            echo "mail.scanning"
            ;;
        *mail*)
            echo "mail"
            ;;
        *dns*polic*)
            echo "dns.policies"
            ;;
        *dns*rule*)
            echo "dns.custom-rules"
            ;;
        *dns*)
            echo "dns"
            ;;
        *report*traffic* | *email*traffic*)
            echo "reports.email-traffic"
            ;;
        *report*threat* | *threat*detect*)
            echo "reports.threat-detection"
            ;;
        *report*)
            echo "reports"
            ;;
        *setting*notification*)
            echo "settings.notifications"
            ;;
        *setting*integration*)
            echo "settings.integrations"
            ;;
        *setting*)
            echo "settings"
            ;;
        *auth*mfa* | *auth*multi*)
            echo "auth.mfa"
            ;;
        *auth*sso* | *auth*single*)
            echo "auth.sso"
            ;;
        *auth*)
            echo "auth"
            ;;
        *api* | *endpoint* | *service*)
            echo "api"
            ;;
        *component* | *ui* | *interface*)
            echo "ui"
            ;;
        *test* | *spec*)
            echo "tests"
            ;;
        *doc* | *readme*)
            echo "docs"
            ;;
        *a11y* | *accessibility*)
            echo "a11y"
            ;;
        *)
            return 1
            ;;
    esac
}

# Function to analyze changed files and detect scopes
analyze_changed_files() {
    echo -e "${BLUE}🔍 Analyzing changed files for scope detection...${NC}"
    echo ""
    
    # Get changed files
    local changed_files=""
    if git rev-parse --git-dir > /dev/null 2>&1; then
        changed_files=$(git diff --cached --name-only 2>/dev/null || git diff --name-only HEAD~1 2>/dev/null || echo "")
    fi
    
    if [ -z "$changed_files" ]; then
        echo -e "${YELLOW}No changed files detected${NC}"
        return 1
    fi
    
    local detected_scopes=()
    local primary_scope=""
    local scope_confidence="low"
    
    echo -e "${GRAY}Changed files:${NC}"
    
    while IFS= read -r file; do
        [ -z "$file" ] && continue
        
        echo -n "  $file"
        
        local scope=""
        local method=""
        
        # Method 1: File metadata
        if scope=$(extract_file_scope "$file"); then
            method="file-metadata"
            scope_confidence="high"
        # Method 2: Directory metadata
        elif scope=$(extract_directory_scope "$file"); then
            method="directory-metadata"
            scope_confidence="medium"
        # Method 3: Path pattern matching
        elif scope=$(suggest_path_scope "$file"); then
            method="path-pattern"
            scope_confidence="low"
        fi
        
        if [ -n "$scope" ]; then
            echo -e " ${GREEN}→ $scope${NC} ${GRAY}($method)${NC}"
            detected_scopes+=("$scope")
            
            # Use first high-confidence scope as primary
            if [ -z "$primary_scope" ] || [ "$method" = "file-metadata" ]; then
                primary_scope="$scope"
            fi
        else
            echo -e " ${GRAY}→ no scope detected${NC}"
        fi
        
    done <<< "$changed_files"
    
    echo ""
    
    # Analyze detected scopes
    if [ ${#detected_scopes[@]} -eq 0 ]; then
        echo -e "${YELLOW}💡 No scopes detected - consider adding scope metadata to files${NC}"
        return 1
    fi
    
    # Find most common scope
    local common_scope=$(printf '%s\n' "${detected_scopes[@]}" | sort | uniq -c | sort -nr | head -1 | awk '{print $2}')
    
    echo -e "${GREEN}📊 Scope Analysis Results:${NC}"
    echo "  Primary scope: $primary_scope"
    echo "  Most common scope: $common_scope"
    echo "  Confidence: $scope_confidence"
    echo "  Unique scopes: $(printf '%s\n' "${detected_scopes[@]}" | sort -u | wc -l)"
    
    # Suggest commit scope
    echo ""
    echo -e "${CYAN}💡 Suggested commit scope: ${NC}$primary_scope"
    
    # Show example commit message
    echo -e "${GRAY}Example: feat($primary_scope): add new functionality${NC}"
}

# Function to add scope metadata to a file
add_scope_metadata() {
    local file="$1"
    local scope="$2"
    
    if [ ! -f "$file" ]; then
        echo -e "${RED}❌ File not found: $file${NC}"
        return 1
    fi
    
    local ext="${file##*.}"
    local temp_file=$(mktemp)
    
    case "$ext" in
        js|ts|jsx|tsx)
            echo "// AI-SCOPE: $scope" > "$temp_file"
            cat "$file" >> "$temp_file"
            ;;
        vue)
            echo "<!-- AI-SCOPE: $scope -->" > "$temp_file"
            cat "$file" >> "$temp_file"
            ;;
        css|scss|less)
            echo "/* AI-SCOPE: $scope */" > "$temp_file"
            cat "$file" >> "$temp_file"
            ;;
        py)
            echo "# AI-SCOPE: $scope" > "$temp_file"
            cat "$file" >> "$temp_file"
            ;;
        *)
            echo "# AI-SCOPE: $scope" > "$temp_file"
            cat "$file" >> "$temp_file"
            ;;
    esac
    
    mv "$temp_file" "$file"
    echo -e "${GREEN}✅ Added scope metadata to $file${NC}"
}

# Main command handling
case "$1" in
    "analyze"|"detect"|"")
        analyze_changed_files
        ;;
    "add-metadata")
        if [ -z "$2" ] || [ -z "$3" ]; then
            echo -e "${RED}❌ Usage: $0 add-metadata <file> <scope>${NC}"
            exit 1
        fi
        add_scope_metadata "$2" "$3"
        ;;
    "help"|"-h"|"--help")
        echo "Enhanced Scope Detection Tool"
        echo ""
        echo "Usage:"
        echo "  $0                          Analyze changed files for scope detection"
        echo "  $0 analyze                  Analyze changed files for scope detection"
        echo "  $0 add-metadata <file> <scope>  Add scope metadata to a file"
        echo "  $0 help                     Show this help"
        ;;
    *)
        echo -e "${RED}❌ Unknown command: $1${NC}"
        echo "Use '$0 help' for usage information"
        exit 1
        ;;
esac
