#!/bin/bash

# KiviCare API Code Quality Checker
# Runs PHPCS, PHPCBF and other quality checks

set -e

PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$PROJECT_ROOT"

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

echo -e "${BLUE}🔍 KiviCare API Code Quality Checker${NC}"
echo "======================================="

# Parse command line arguments
FIX=false
FULL_REPORT=false
TARGET_DIR="src"

while [[ $# -gt 0 ]]; do
    case $1 in
        -f|--fix)
            FIX=true
            shift
            ;;
        -v|--verbose)
            FULL_REPORT=true
            shift
            ;;
        -t|--target)
            TARGET_DIR="$2"
            shift 2
            ;;
        -h|--help)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  -f, --fix         Auto-fix code style issues using PHPCBF"
            echo "  -v, --verbose     Show detailed reports"
            echo "  -t, --target DIR  Target directory to analyze (default: src)"
            echo "  -h, --help        Show this help message"
            echo ""
            echo "Examples:"
            echo "  $0                    # Check code style in src/"
            echo "  $0 --fix              # Check and auto-fix issues"
            echo "  $0 --target tests     # Check tests directory"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use -h for help"
            exit 1
            ;;
    esac
done

# Function to run PHPCS check
run_phpcs() {
    local target=$1
    local report_type="summary"
    
    if [ "$FULL_REPORT" = true ]; then
        report_type="full"
    fi
    
    echo -e "\n${YELLOW}📋 Running PHPCS on $target...${NC}"
    
    if php vendor/bin/phpcs --standard=phpcs.xml "$target" --report="$report_type"; then
        echo -e "${GREEN}✅ PHPCS: No coding standards violations found!${NC}"
        return 0
    else
        echo -e "${RED}❌ PHPCS: Found coding standards violations${NC}"
        return 1
    fi
}

# Function to run PHPCBF auto-fix
run_phpcbf() {
    local target=$1
    
    echo -e "\n${BLUE}🔧 Running PHPCBF auto-fix on $target...${NC}"
    
    if php vendor/bin/phpcbf --standard=phpcs.xml "$target"; then
        echo -e "${GREEN}✅ PHPCBF: Auto-fixed coding standards issues${NC}"
        return 0
    else
        echo -e "${YELLOW}⚠️  PHPCBF: Some issues could not be auto-fixed${NC}"
        return 1
    fi
}

# Function to run PHP syntax check
run_php_syntax_check() {
    local target=$1
    
    echo -e "\n${YELLOW}🔍 Checking PHP syntax in $target...${NC}"
    
    if find "$target" -name "*.php" -exec php -l {} \; | grep -v "No syntax errors detected"; then
        echo -e "${RED}❌ PHP Syntax: Found syntax errors${NC}"
        return 1
    else
        echo -e "${GREEN}✅ PHP Syntax: No syntax errors found${NC}"
        return 0
    fi
}

# Function to check for WordPress functions
check_wordpress_functions() {
    local target=$1
    
    echo -e "\n${YELLOW}🔍 Checking WordPress function usage in $target...${NC}"
    
    # Check for potential issues
    local issues=0
    
    # Check for direct database queries without preparation
    if grep -r "SELECT.*\$" "$target" --include="*.php" | grep -v "prepare\|wpdb"; then
        echo -e "${RED}⚠️  Found potential unprepared SQL queries${NC}"
        issues=$((issues+1))
    fi
    
    # Check for missing text domains
    if grep -r "__(\|_e(\|_x(\|_n(" "$target" --include="*.php" | grep -v "kivicare-api"; then
        echo -e "${YELLOW}⚠️  Found strings that may need text domains${NC}"
        issues=$((issues+1))
    fi
    
    if [ $issues -eq 0 ]; then
        echo -e "${GREEN}✅ WordPress Functions: No obvious issues found${NC}"
        return 0
    else
        echo -e "${YELLOW}⚠️  WordPress Functions: Found $issues potential issues${NC}"
        return 1
    fi
}

# Main execution
echo -e "\n${BLUE}Target directory: $TARGET_DIR${NC}"

if [ ! -d "$TARGET_DIR" ]; then
    echo -e "${RED}❌ Target directory '$TARGET_DIR' does not exist${NC}"
    exit 1
fi

# Overall success tracking
overall_success=true

# Run PHP syntax check first
if ! run_php_syntax_check "$TARGET_DIR"; then
    overall_success=false
fi

# Run auto-fix if requested
if [ "$FIX" = true ]; then
    run_phpcbf "$TARGET_DIR" || true
fi

# Run PHPCS check
if ! run_phpcs "$TARGET_DIR"; then
    overall_success=false
fi

# Run WordPress-specific checks
if ! check_wordpress_functions "$TARGET_DIR"; then
    overall_success=false
fi

# Summary
echo -e "\n${BLUE}📊 Code Quality Summary${NC}"
echo "======================="

if [ "$overall_success" = true ]; then
    echo -e "${GREEN}🎉 All code quality checks passed!${NC}"
    exit 0
else
    echo -e "${RED}❌ Some code quality issues found${NC}"
    echo -e "${YELLOW}💡 Run with --fix to auto-resolve some issues${NC}"
    echo -e "${YELLOW}💡 Run with --verbose for detailed reports${NC}"
    exit 1
fi