#!/bin/bash

# LOC Validation Script
# Checks file size limits and provides recommendations

set -e

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

# Configuration
MAX_LOC=300
MAX_LOC_JUSTIFIED=350
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

# Function to check if a file is Python code
is_python_file() {
    local file="$1"
    [[ "$file" == *.py ]]
}

# Function to count lines of code (excluding comments and empty lines)
count_loc() {
    local file="$1"
    if [[ ! -f "$file" ]]; then
        echo 0
        return
    fi
    
    # Count non-comment, non-empty lines
    grep -v '^\s*#' "$file" | grep -v '^\s*$' | wc -l
}

# Function to analyze file structure for splitting recommendations
analyze_file_structure() {
    local file="$1"
    local loc="$2"
    
    if [[ $loc -le $MAX_LOC ]]; then
        return
    fi
    
    echo -e "${BLUE}📊 File Structure Analysis for $file:${NC}"
    
    # Count classes, functions, and methods
    local classes=$(grep "^class " "$file" 2>/dev/null | wc -l || echo 0)
    local functions=$(grep "^def " "$file" 2>/dev/null | wc -l || echo 0)
    local imports=$(grep "^import\|^from " "$file" 2>/dev/null | wc -l || echo 0)
    
    echo -e "  ${BLUE}• Classes:${NC} $classes"
    echo -e "  ${BLUE}• Functions/Methods:${NC} $functions"
    echo -e "  ${BLUE}• Import statements:${NC} $imports"
    
    # Provide splitting recommendations
    if [[ $classes -gt 1 ]]; then
        echo -e "  ${YELLOW}💡 Recommendation: Split into separate files per class${NC}"
    fi
    
    if [[ $functions -gt 10 ]]; then
        echo -e "  ${YELLOW}💡 Recommendation: Group related functions into modules${NC}"
    fi
    
    if [[ $imports -gt 5 ]]; then
        echo -e "  ${YELLOW}💡 Recommendation: Consider dependency organization${NC}"
    fi
}

# Function to check LOC compliance
check_loc_compliance() {
    local file="$1"
    local loc
    
    if [[ ! -f "$file" ]]; then
        return 0
    fi
    
    loc=$(count_loc "$file")
    
    if [[ $loc -gt $MAX_LOC_JUSTIFIED ]]; then
        echo -e "${RED}❌ LOC Violation in $file: $loc lines (exceeds $MAX_LOC_JUSTIFIED limit)${NC}"
        analyze_file_structure "$file" "$loc"
        return 1
    elif [[ $loc -gt $MAX_LOC ]]; then
        echo -e "${YELLOW}⚠️  LOC Warning in $file: $loc lines (exceeds $MAX_LOC, but under $MAX_LOC_JUSTIFIED)${NC}"
        echo -e "  ${YELLOW}  Consider splitting this file for better maintainability${NC}"
        analyze_file_structure "$file" "$loc"
        return 0  # Warning, not error
    else
        echo -e "${GREEN}✅ LOC OK: $file ($loc lines)${NC}"
        return 0
    fi
}

# Main function
main() {
    local exit_code=0
    local total_files=0
    local violation_files=0
    local warning_files=0
    
    echo -e "${BLUE}📏 LOC Validation for Project${NC}"
    echo -e "${BLUE}Target: < $MAX_LOC lines (${MAX_LOC_JUSTIFIED} max if justified)${NC}"
    echo ""
    
    # Check LOC compliance for all Python files
    while IFS= read -r -d '' file; do
        if is_python_file "$file"; then
            total_files=$((total_files + 1))
            if ! check_loc_compliance "$file"; then
                if [[ $? -eq 1 ]]; then
                    violation_files=$((violation_files + 1))
                    exit_code=1
                else
                    warning_files=$((warning_files + 1))
                fi
            fi
        fi
    done < <(find "$PROJECT_ROOT/src" -name "*.py" -print0)
    
    echo ""
    echo -e "${BLUE}📋 LOC Validation Summary:${NC}"
    echo -e "  ${BLUE}• Total Python files:${NC} $total_files"
    echo -e "  ${GREEN}• Files within limits:${NC} $((total_files - violation_files - warning_files))"
    echo -e "  ${YELLOW}• Files with warnings:${NC} $warning_files"
    echo -e "  ${RED}• Files with violations:${NC} $violation_files"
    
    if [[ $violation_files -gt 0 ]]; then
        echo ""
        echo -e "${RED}🚫 LOC violations detected - must be fixed before task completion${NC}"
        echo -e "${YELLOW}  Consider splitting large files into focused modules${NC}"
    elif [[ $warning_files -gt 0 ]]; then
        echo ""
        echo -e "${YELLOW}⚠️  LOC warnings detected - consider refactoring for maintainability${NC}"
    else
        echo ""
        echo -e "${GREEN}🎉 All files within LOC limits!${NC}"
    fi
    
    exit $exit_code
}

# Run main function
main "$@"
