#!/bin/bash

# UTC Timestamp Validation Script
# Checks for timestamp compliance and provides fix 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
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 check UTC timestamp compliance
check_utc_timestamps() {
    local file="$1"
    local issues=()
    local line_numbers=()
    
    if [[ ! -f "$file" ]]; then
        return 0
    fi
    
    # Check for naive datetime usage with line numbers
    while IFS= read -r line_num; do
        if [[ -n "$line_num" ]]; then
            issues+=("Line $line_num: naive datetime.now() - should use datetime.now(timezone.utc)")
            line_numbers+=("$line_num")
        fi
    done < <(grep -n "datetime\.now()" "$file" | cut -d: -f1)
    
    # Check for deprecated utcnow with line numbers
    while IFS= read -r line_num; do
        if [[ -n "$line_num" ]]; then
            issues+=("Line $line_num: deprecated datetime.utcnow() - should use datetime.now(timezone.utc)")
            line_numbers+=("$line_num")
        fi
    done < <(grep -n "datetime\.utcnow()" "$file" | cut -d: -f1)
    
    # Check for time.time() usage in timing contexts
    while IFS= read -r line_num; do
        if [[ -n "$line_num" ]]; then
            issues+=("Line $line_num: time.time() usage - consider using datetime for consistency")
            line_numbers+=("$line_num")
        fi
    done < <(grep -n "time\.time()" "$file" | cut -d: -f1)
    
    # Check for inconsistent filename formats
    if grep -q "strftime.*%Y.*%m.*%d.*%H.*%M.*%S" "$file"; then
        if ! grep -q "strftime.*%Y%m%d_%H%M%S" "$file"; then
            issues+=("Inconsistent filename timestamp format - should use YYYYMMDD_HHMMSS")
        fi
    fi
    
    if [[ ${#issues[@]} -gt 0 ]]; then
        echo -e "${RED}❌ UTC Timestamp Issues in $file:${NC}"
        for issue in "${issues[@]}"; do
            echo -e "  ${RED}• $issue${NC}"
        done
        
        # Show context for each issue
        echo -e "${BLUE}📝 Context for issues:${NC}"
        for line_num in "${line_numbers[@]}"; do
            if [[ -n "$line_num" ]]; then
                local context=$(sed -n "${line_num}p" "$file" | sed 's/^[[:space:]]*//')
                echo -e "  ${BLUE}Line $line_num:${NC} $context"
            fi
        done
        
        # Provide fix recommendations
        echo -e "${YELLOW}🔧 Fix Recommendations:${NC}"
        echo -e "  ${YELLOW}• Replace datetime.now() with datetime.now(timezone.utc)${NC}"
        echo -e "  ${YELLOW}• Replace datetime.utcnow() with datetime.now(timezone.utc)${NC}"
        echo -e "  ${YELLOW}• Use datetime for timing instead of time.time()${NC}"
        echo -e "  ${YELLOW}• Standardize filename formats to YYYYMMDD_HHMMSS${NC}"
        
        return 1
    fi
    
    return 0
}

# Function to provide automated fix suggestions
suggest_fixes() {
    local file="$1"
    
    echo -e "${BLUE}🤖 Automated Fix Suggestions:${NC}"
    
    # Check if file has issues that can be auto-fixed
    if grep -q "datetime\.now()" "$file"; then
        echo -e "  ${BLUE}• Replace naive datetime:${NC}"
        echo -e "    sed -i 's/datetime\.now()/datetime.now(timezone.utc)/g' $file"
    fi
    
    if grep -q "datetime\.utcnow()" "$file"; then
        echo -e "  ${BLUE}• Replace deprecated utcnow:${NC}"
        echo -e "    sed -i 's/datetime\.utcnow()/datetime.now(timezone.utc)/g' $file"
    fi
    
    if grep -q "time\.time()" "$file"; then
        echo -e "  ${BLUE}• Consider replacing time.time() with datetime:${NC}"
        echo -e "    # Before: start_time = time.time()"
        echo -e "    # After:  start_time = datetime.now(timezone.utc)"
    fi
    
    # Check for missing timezone import
    if grep -q "datetime\.now(timezone\.utc)" "$file" && ! grep -q "from datetime import.*timezone" "$file"; then
        echo -e "  ${BLUE}• Add timezone import:${NC}"
        echo -e "    from datetime import datetime, timezone"
    fi
}

# Main function
main() {
    local exit_code=0
    local total_files=0
    local violation_files=0
    
    echo -e "${BLUE}⏰ UTC Timestamp Validation for Project${NC}"
    echo -e "${BLUE}Target: All timestamps use datetime.now(timezone.utc)${NC}"
    echo ""
    
    # Check UTC timestamp 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_utc_timestamps "$file"; then
                violation_files=$((violation_files + 1))
                exit_code=1
                
                # Provide fix suggestions
                suggest_fixes "$file"
                echo ""
            else
                echo -e "${GREEN}✅ UTC Timestamps OK: $file${NC}"
            fi
        fi
    done < <(find "$PROJECT_ROOT/src" -name "*.py" -print0)
    
    echo ""
    echo -e "${BLUE}📋 UTC Timestamp Validation Summary:${NC}"
    echo -e "  ${BLUE}• Total Python files:${NC} $total_files"
    echo -e "  ${GREEN}• Files compliant:${NC} $((total_files - violation_files))"
    echo -e "  ${RED}• Files with violations:${NC} $violation_files"
    
    if [[ $violation_files -gt 0 ]]; then
        echo ""
        echo -e "${RED}🚫 UTC timestamp violations detected - must be fixed before task completion${NC}"
        echo -e "${YELLOW}  Use the fix suggestions above to resolve issues${NC}"
        echo ""
        echo -e "${BLUE}🔧 Quick Fix Commands:${NC}"
        echo -e "  ${BLUE}• Fix all naive datetime:${NC} find src/ -name '*.py' -exec sed -i 's/datetime\.now()/datetime.now(timezone.utc)/g' {} \\;"
        echo -e "  ${BLUE}• Fix all utcnow:${NC} find src/ -name '*.py' -exec sed -i 's/datetime\.utcnow()/datetime.now(timezone.utc)/g' {} \\;"
        echo -e "  ${BLUE}• Re-validate:${NC} $0"
    else
        echo ""
        echo -e "${GREEN}🎉 All files use proper UTC timestamps!${NC}"
    fi
    
    exit $exit_code
}

# Run main function
main "$@"
