#!/bin/bash
# Organize Root Directory Files
# Moves files from root to appropriate directories based on type

set -euo pipefail

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

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

# Dry-run mode (default: true)
DRY_RUN="${1:---dry-run}"

# Log file
LOG_FILE="ROOT_FILES_ORGANIZATION_$(date +%Y%m%d_%H%M%S).log"
MOVED_COUNT=0
SKIPPED_COUNT=0
ERROR_COUNT=0

log() {
    echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1" | tee -a "$LOG_FILE"
}

success() {
    echo -e "${GREEN}[OK]${NC} $1" | tee -a "$LOG_FILE"
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1" | tee -a "$LOG_FILE"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1" | tee -a "$LOG_FILE"
    ERROR_COUNT=$((ERROR_COUNT + 1))
}

move_file() {
    local source="$1"
    local dest="$2"
    local description="${3:-}"
    
    if [ ! -f "$source" ]; then
        warn "File not found: $source"
        SKIPPED_COUNT=$((SKIPPED_COUNT + 1))
        return
    fi
    
    # Create destination directory if it doesn't exist
    local dest_dir=$(dirname "$dest")
    if [ "$DRY_RUN" != "--dry-run" ]; then
        mkdir -p "$dest_dir"
    fi
    
    # Check if destination already exists
    if [ -f "$dest" ]; then
        warn "Destination already exists: $dest (skipping $source)"
        SKIPPED_COUNT=$((SKIPPED_COUNT + 1))
        return
    fi
    
    if [ "$DRY_RUN" == "--dry-run" ]; then
        log "Would move: $source → $dest $description"
    else
        if mv "$source" "$dest" 2>>"$LOG_FILE"; then
            success "Moved: $source → $dest $description"
            MOVED_COUNT=$((MOVED_COUNT + 1))
        else
            error "Failed to move: $source → $dest"
        fi
    fi
}

# Create necessary directories
create_directories() {
    if [ "$DRY_RUN" != "--dry-run" ]; then
        mkdir -p logs
        mkdir -p reports/inventory
        mkdir -p examples
    fi
}

log "╔══════════════════════════════════════════════════════════╗"
log "║   Root Directory Files Organization                     ║"
log "╚══════════════════════════════════════════════════════════╝"
log ""
log "Mode: $DRY_RUN"
log "Project Root: $PROJECT_ROOT"
log "Log File: $LOG_FILE"
log ""

create_directories

log "=== Moving Log Files to logs/ ==="
for file in *.log; do
    [ -f "$file" ] || continue
    # Skip the log file we're currently writing to
    [ "$file" == "$LOG_FILE" ] && continue
    move_file "$file" "logs/$file" "(log file)"
done

log ""
log "=== Moving CSV Inventory Files to reports/inventory/ ==="
for file in container_inventory_*.csv; do
    [ -f "$file" ] || continue
    move_file "$file" "reports/inventory/$file" "(inventory CSV)"
done

log ""
log "=== Moving Shell Scripts to scripts/ ==="
# List of shell scripts to move (excluding scripts already in scripts/)
for file in *.sh; do
    [ -f "$file" ] || continue
    # Skip if already in scripts/ directory
    if [ -f "scripts/$file" ]; then
        warn "Script already exists in scripts/: $file (skipping)"
        SKIPPED_COUNT=$((SKIPPED_COUNT + 1))
        continue
    fi
    move_file "$file" "scripts/$file" "(shell script)"
done

log ""
log "=== Moving Python Scripts to scripts/ ==="
for file in *.py; do
    [ -f "$file" ] || continue
    # Skip if already in scripts/ directory
    if [ -f "scripts/$file" ]; then
        warn "Script already exists in scripts/: $file (skipping)"
        SKIPPED_COUNT=$((SKIPPED_COUNT + 1))
        continue
    fi
    move_file "$file" "scripts/$file" "(Python script)"
done

log ""
log "=== Moving JavaScript Files to scripts/ ==="
for file in *.js; do
    [ -f "$file" ] || continue
    # Skip if already in scripts/ directory
    if [ -f "scripts/$file" ]; then
        warn "Script already exists in scripts/: $file (skipping)"
        SKIPPED_COUNT=$((SKIPPED_COUNT + 1))
        continue
    fi
    # Skip package.json and lock files (these should stay in root)
    if [[ "$file" == "package.json" ]] || [[ "$file" == "pnpm-lock.yaml" ]] || [[ "$file" == "token-list.json" ]]; then
        continue
    fi
    move_file "$file" "scripts/$file" "(JavaScript script)"
done

log ""
log "=== Moving HTML Files to examples/ ==="
for file in *.html; do
    [ -f "$file" ] || continue
    move_file "$file" "examples/$file" "(HTML example)"
done

log ""
log "=== Moving JSON Reports to reports/ ==="
for file in CONTENT_INCONSISTENCIES.json MARKDOWN_ANALYSIS.json REFERENCE_FIXES_REPORT.json; do
    [ -f "$file" ] || continue
    move_file "$file" "reports/$file" "(JSON report)"
done

log ""
log "=== Moving Text Reports to reports/ ==="
for file in CONVERSION_SUMMARY.txt; do
    [ -f "$file" ] || continue
    move_file "$file" "reports/$file" "(text report)"
done

log ""
log "╔══════════════════════════════════════════════════════════╗"
log "║   Organization Complete                                 ║"
log "╚══════════════════════════════════════════════════════════╝"
log ""
log "Summary:"
log "  Files Moved: $MOVED_COUNT"
log "  Files Skipped: $SKIPPED_COUNT"
log "  Errors: $ERROR_COUNT"
log ""

if [ "$DRY_RUN" == "--dry-run" ]; then
    log "⚠️  DRY RUN MODE - No files were actually moved"
    log ""
    log "To execute the moves, run:"
    log "  $0 --execute"
else
    log "✅ Files have been moved successfully"
    log "Log file: $LOG_FILE"
fi

log ""
exit 0
