#!/bin/bash
# Organize Documentation Directory Files
# Moves files from docs/ root to appropriate directories

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="docs/DOCS_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 docs/00-meta
        mkdir -p docs/archive/reports
        mkdir -p docs/archive/issues
        mkdir -p docs/bridge/contracts
        mkdir -p docs/04-configuration/metamask
        mkdir -p docs/scripts
    fi
}

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

create_directories

log "=== Moving Documentation Meta Files to docs/00-meta/ ==="
for file in \
    CONTRIBUTOR_GUIDELINES.md \
    DOCUMENTATION_ENHANCEMENTS_RECOMMENDATIONS.md \
    DOCUMENTATION_FIXES_COMPLETE.md \
    DOCUMENTATION_QUALITY_REVIEW.md \
    DOCUMENTATION_RELATIONSHIP_MAP.md \
    DOCUMENTATION_REORGANIZATION_COMPLETE.md \
    DOCUMENTATION_REVIEW.md \
    DOCUMENTATION_STYLE_GUIDE.md \
    DOCUMENTATION_UPGRADE_SUMMARY.md \
    MARKDOWN_FILE_MAINTENANCE_GUIDE.md; do
    [ -f "docs/$file" ] || continue
    move_file "docs/$file" "docs/00-meta/$file" "(documentation meta)"
done

log ""
log "=== Moving Reports to docs/archive/reports/ ==="
for file in \
    PROXMOX_CLUSTER_STORAGE_STATUS_REPORT.md \
    PROXMOX_SSL_CERTIFICATE_FIX.md \
    PROXMOX_SSL_FIX_VERIFIED.md \
    SSL_CERTIFICATE_ERROR_596_FIX.md \
    SSL_FIX_FOR_EACH_HOST.md; do
    [ -f "docs/$file" ] || continue
    move_file "docs/$file" "docs/archive/reports/$file" "(report)"
done

log ""
log "=== Moving Issue Tracking to docs/archive/issues/ ==="
for file in \
    OUTSTANDING_ISSUES_RESOLUTION_GUIDE.md \
    OUTSTANDING_ISSUES_SUMMARY.md; do
    [ -f "docs/$file" ] || continue
    move_file "docs/$file" "docs/archive/issues/$file" "(issue tracking)"
done

log ""
log "=== Moving Solidity Files to docs/bridge/contracts/ ==="
for file in \
    CCIPWETH9Bridge_flattened.sol \
    CCIPWETH9Bridge_standard_json.json \
    CCIPWETH9Bridge_standard_json_generated.json; do
    [ -f "docs/$file" ] || continue
    move_file "docs/$file" "docs/bridge/contracts/$file" "(Solidity contract)"
done

log ""
log "=== Moving Metamask Config Files to docs/04-configuration/metamask/ ==="
for file in \
    METAMASK_NETWORK_CONFIG.json \
    METAMASK_TOKEN_LIST.json \
    METAMASK_TOKEN_LIST.tokenlist.json; do
    [ -f "docs/$file" ] || continue
    move_file "docs/$file" "docs/04-configuration/metamask/$file" "(Metamask config)"
done

log ""
log "=== Moving Scripts to docs/scripts/ ==="
for file in \
    organize-standalone-files.sh \
    organize_files.py; do
    [ -f "docs/$file" ] || continue
    move_file "docs/$file" "docs/scripts/$file" "(script)"
done

log ""
log "=== Files Staying in Root ==="
log "✅ README.md - Main documentation index"
log "✅ MASTER_INDEX.md - Master index"
log "✅ SEARCH_GUIDE.md - Search guide (useful in root)"

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"
    
    # Move log file to logs directory
    if [ -f "$LOG_FILE" ]; then
        mkdir -p logs
        mv "$LOG_FILE" "logs/"
        log "Log file moved to: logs/$(basename "$LOG_FILE")"
    fi
fi

log ""
exit 0
