#!/bin/bash
# Show file statistics for a site directory
# Usage: tools/check/file-stats.sh <site-dir>
# Example: tools/check/file-stats.sh sites/example.com-v1
# Exit codes: 0=success, 2=input error

set -e

SITE_DIR="${1:-.}"

if [[ ! -d "$SITE_DIR" ]]; then
    echo "ERROR:directory_not_found:$SITE_DIR"
    exit 2
fi

echo "=== File Statistics: $(basename "$SITE_DIR") ==="
echo ""

# Find web files
HTML_FILES=$(find "$SITE_DIR" -maxdepth 2 -name "*.html" -type f 2>/dev/null || true)
CSS_FILES=$(find "$SITE_DIR" -maxdepth 2 -name "*.css" -type f 2>/dev/null || true)
JS_FILES=$(find "$SITE_DIR" -maxdepth 2 -name "*.js" -type f 2>/dev/null || true)

TOTAL_LINES=0
TOTAL_BYTES=0

print_file_stats() {
    local file="$1"
    if [[ -f "$file" ]]; then
        local lines=$(wc -l < "$file" | tr -d ' ')
        local bytes=$(wc -c < "$file" | tr -d ' ')
        local kb=$(echo "scale=1; $bytes / 1024" | bc)
        printf "  %-20s %6d lines  %6.1f KB\n" "$(basename "$file")" "$lines" "$kb"
        TOTAL_LINES=$((TOTAL_LINES + lines))
        TOTAL_BYTES=$((TOTAL_BYTES + bytes))
    fi
}

if [[ -n "$HTML_FILES" ]]; then
    echo "HTML:"
    for f in $HTML_FILES; do print_file_stats "$f"; done
    echo ""
fi

if [[ -n "$CSS_FILES" ]]; then
    echo "CSS:"
    for f in $CSS_FILES; do print_file_stats "$f"; done
    echo ""
fi

if [[ -n "$JS_FILES" ]]; then
    echo "JavaScript:"
    for f in $JS_FILES; do print_file_stats "$f"; done
    echo ""
fi

TOTAL_KB=$(echo "scale=1; $TOTAL_BYTES / 1024" | bc)
echo "---"
printf "TOTAL: %d lines, %.1f KB\n" "$TOTAL_LINES" "$TOTAL_KB"
