#!/usr/bin/env bash
# Cleanup Documentation on ml110
# Performs the same cleanup as local: deletes obsolete docs and marks historical ones

set -euo pipefail

REMOTE_HOST="192.168.11.10"
REMOTE_USER="root"
REMOTE_PASS="L@kers2010"
REMOTE_BASE="/opt"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

DRY_RUN="${DRY_RUN:-true}"

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --execute)
            DRY_RUN=false
            shift
            ;;
        --help)
            cat << EOF
Usage: $0 [OPTIONS]

Cleanup documentation on ml110 (same as local cleanup).

Options:
  --execute        Actually delete files (default: dry-run)
  --help           Show this help

EOF
            exit 0
            ;;
        *)
            log_error "Unknown option: $1"
            exit 1
            ;;
    esac
done

log_info "========================================="
log_info "Cleanup Documentation on ml110"
log_info "========================================="
log_info "Remote: ${REMOTE_USER}@${REMOTE_HOST}"
log_info "Mode: $([ "$DRY_RUN" == "true" ] && echo "DRY-RUN" || echo "EXECUTE")"
log_info ""

# Test connection
if ! sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 \
    "${REMOTE_USER}@${REMOTE_HOST}" "echo 'Connected'" 2>/dev/null; then
    log_error "Cannot connect to ${REMOTE_HOST}"
    exit 1
fi

log_success "Connected to ${REMOTE_HOST}"

# Obsolete files to delete
OBSOLETE_FILES=(
    "smom-dbis-138-proxmox/docs/DEPLOYMENT_STATUS.md"
    "smom-dbis-138-proxmox/docs/DEPLOYMENT_REVIEW_COMPLETE.md"
    "smom-dbis-138-proxmox/docs/DEPLOYMENT_REVIEW.md"
    "smom-dbis-138-proxmox/docs/DEPLOYMENT_TIME_ESTIMATE.md"
    "smom-dbis-138-proxmox/docs/DEPLOYMENT_TIME_ESTIMATE_BESU_ONLY.md"
    "smom-dbis-138-proxmox/docs/DEPLOYMENT_VALIDATION_REPORT.md"
    "smom-dbis-138-proxmox/docs/DEPLOYED_VMIDS_LIST.md"
    "smom-dbis-138-proxmox/docs/DEPLOYMENT_OPTIMIZATION_COMPLETE.md"
    "smom-dbis-138-proxmox/docs/DEPLOYMENT_OPTIMIZATION_RECOMMENDATIONS.md"
    "smom-dbis-138-proxmox/docs/DEPLOYMENT_RECOMMENDATIONS_STATUS.md"
    "smom-dbis-138-proxmox/docs/DEPLOYMENT_CONFIGURATION_VERIFICATION.md"
    "smom-dbis-138-proxmox/docs/NEXT_STEPS_COMPREHENSIVE.md"
    "smom-dbis-138-proxmox/docs/NEXT_STEPS_COMPLETE.md"
    "smom-dbis-138-proxmox/docs/NEXT_STEPS_SUMMARY.md"
    "smom-dbis-138-proxmox/docs/COMPLETION_REPORT.md"
    "smom-dbis-138-proxmox/docs/FIXES_APPLIED.md"
    "smom-dbis-138-proxmox/docs/REVIEW_FIXES_APPLIED.md"
    "smom-dbis-138-proxmox/docs/MINOR_OBSERVATIONS_FIXED.md"
    "smom-dbis-138-proxmox/docs/NON_CRITICAL_FIXES_COMPLETE.md"
    "smom-dbis-138-proxmox/docs/QUICK_WINS_COMPLETED.md"
    "smom-dbis-138-proxmox/docs/TASK_COMPLETION_SUMMARY.md"
    "smom-dbis-138-proxmox/docs/IMPLEMENTATION_COMPLETE.md"
    "smom-dbis-138-proxmox/docs/PREREQUISITES_COMPLETE.md"
    "smom-dbis-138-proxmox/docs/SETUP_COMPLETE.md"
    "smom-dbis-138-proxmox/docs/SETUP_COMPLETE_FINAL.md"
    "smom-dbis-138-proxmox/docs/SETUP_STATUS.md"
    "smom-dbis-138-proxmox/docs/VALIDATION_STATUS.md"
    "smom-dbis-138-proxmox/docs/CONFIGURATION_ALIGNMENT.md"
    "smom-dbis-138-proxmox/docs/REVIEW_INCONSISTENCIES_GAPS.md"
    "smom-dbis-138-proxmox/docs/REVIEW_SUMMARY.md"
    "smom-dbis-138-proxmox/docs/COMPREHENSIVE_REVIEW.md"
    "smom-dbis-138-proxmox/docs/FINAL_REVIEW.md"
    "smom-dbis-138-proxmox/docs/DETAILED_ISSUES_REVIEW.md"
    "smom-dbis-138-proxmox/docs/RECOMMENDATIONS_OVERVIEW.md"
    "smom-dbis-138-proxmox/docs/OS_TEMPLATE_CHANGE.md"
    "smom-dbis-138-proxmox/docs/UBUNTU_DEBIAN_ANALYSIS.md"
    "smom-dbis-138-proxmox/docs/OS_TEMPLATE_ANALYSIS.md"
    "smom-dbis-138-proxmox/docs/DHCP_IP_ADDRESSES.md"
    "smom-dbis-138-proxmox/docs/VMID_CONSISTENCY_REPORT.md"
    "smom-dbis-138-proxmox/docs/ACTIVE_DOCS_UPDATE_SUMMARY.md"
    "smom-dbis-138-proxmox/docs/PROJECT_UPDATE_COMPLETE.md"
)

# Historical files to mark
HISTORICAL_FILES=(
    "smom-dbis-138-proxmox/docs/EXPECTED_CONTAINERS.md"
    "smom-dbis-138-proxmox/docs/VMID_ALLOCATION.md"
    "smom-dbis-138-proxmox/docs/VMID_REFERENCE_AUDIT.md"
    "smom-dbis-138-proxmox/docs/VMID_UPDATE_COMPLETE.md"
)

log_info "=== Checking Files on ml110 ==="

# Check which obsolete files exist
EXISTING_OBSOLETE=$(sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no \
    "${REMOTE_USER}@${REMOTE_HOST}" "cd ${REMOTE_BASE} && for f in \"${OBSOLETE_FILES[@]}\"; do [ -f \"\$f\" ] && echo \"\$f\"; done" 2>/dev/null)

if [[ -n "$EXISTING_OBSOLETE" ]]; then
    OBSOLETE_COUNT=$(echo "$EXISTING_OBSOLETE" | wc -l)
    log_info "Found $OBSOLETE_COUNT obsolete files to delete"
    if [[ "$DRY_RUN" == "true" ]]; then
        echo "$EXISTING_OBSOLETE" | while read -r file; do
            log_info "Would delete: $file"
        done
    else
        # Delete obsolete files
        echo "$EXISTING_OBSOLETE" | while read -r file; do
            if sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no \
                "${REMOTE_USER}@${REMOTE_HOST}" "cd ${REMOTE_BASE} && rm -f \"$file\" 2>/dev/null && echo 'deleted'" 2>/dev/null | grep -q "deleted"; then
                log_success "Deleted: $file"
            else
                log_warn "Failed to delete: $file"
            fi
        done
    fi
else
    log_info "No obsolete files found to delete"
fi

echo ""

# Mark historical files
log_info "=== Marking Historical Documentation ==="

for file in "${HISTORICAL_FILES[@]}"; do
    # Check if file exists and is not already marked
    EXISTS=$(sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no \
        "${REMOTE_USER}@${REMOTE_HOST}" "cd ${REMOTE_BASE} && [ -f \"$file\" ] && echo 'exists' || echo 'missing'" 2>/dev/null)
    
    if [[ "$EXISTS" == "exists" ]]; then
        ALREADY_MARKED=$(sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no \
            "${REMOTE_USER}@${REMOTE_HOST}" "cd ${REMOTE_BASE} && head -1 \"$file\" 2>/dev/null | grep -q 'HISTORICAL' && echo 'yes' || echo 'no'" 2>/dev/null)
        
        if [[ "$ALREADY_MARKED" == "yes" ]]; then
            log_info "Already marked: $file"
        else
            if [[ "$DRY_RUN" == "true" ]]; then
                log_info "Would mark as historical: $file"
            else
                # Add historical header based on file type
                if [[ "$file" == *"EXPECTED_CONTAINERS"* ]]; then
                    HEADER="<!-- HISTORICAL: This document contains historical VMID ranges (106-117) and is kept for reference only. Current ranges: Validators 1000-1004, Sentries 1500-1503, RPC 2500-2502 -->"
                elif [[ "$file" == *"VMID_ALLOCATION"* ]]; then
                    HEADER="<!-- HISTORICAL: This document contains historical VMID ranges (1100-1122) and is kept for reference only. Current ranges: Validators 1000-1004, Sentries 1500-1503, RPC 2500-2502 -->"
                else
                    HEADER="<!-- HISTORICAL: This document is a historical record and is kept for reference only. -->"
                fi
                
                # Add header to file
                sshpass -p "$REMOTE_PASS" ssh -o StrictHostKeyChecking=no \
                    "${REMOTE_USER}@${REMOTE_HOST}" "cd ${REMOTE_BASE} && sed -i '1i${HEADER}' \"$file\" 2>/dev/null && echo 'marked'" 2>/dev/null | grep -q "marked" && \
                    log_success "Marked: $file" || \
                    log_warn "Failed to mark: $file"
            fi
        fi
    else
        log_warn "File not found: $file"
    fi
done

echo ""

# Summary
log_info "========================================="
log_info "Summary"
log_info "========================================="

if [[ "$DRY_RUN" == "true" ]]; then
    log_warn "DRY-RUN mode: No files were modified"
    log_info "Run with --execute to actually delete/mark files"
else
    log_success "Cleanup completed on ml110"
fi

log_info ""

