#!/bin/bash

# ===============================================================================
# HomeAudit Monitoring Script
# Shows real-time progress of audit deployment
# ===============================================================================

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

print_status() {
    echo -e "${BLUE}[MONITOR]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[COMPLETE]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Get expected hosts from inventory
get_expected_hosts() {
    grep -E '^[a-zA-Z]' inventory.ini | grep -v '^#' | grep -v '^\[.*\]' | awk '{print $1}' | grep -v 'ansible_' | sort
}

# Get completed hosts
get_completed_hosts() {
    if [ -d "audit_results" ]; then
        ls audit_results/ 2>/dev/null | grep -v '\.md$' | grep -v '\.json$' | sort
    else
        echo ""
    fi
}

# Check if Ansible is still running
is_ansible_running() {
    ps aux | grep ansible | grep -v grep | grep -v monitor_audit >/dev/null 2>&1
}

# Show progress
show_progress() {
    local expected_hosts=($(get_expected_hosts))
    local completed_hosts=($(get_completed_hosts))
    local total_expected=${#expected_hosts[@]}
    local total_completed=${#completed_hosts[@]}
    
    echo "========================================"
    echo "HomeAudit Deployment Progress Monitor"
    echo "========================================"
    echo "Total Expected Hosts: $total_expected"
    echo "Completed Hosts: $total_completed"
    echo "Progress: $total_completed/$total_expected ($(($total_completed * 100 / $total_expected))%)"
    echo ""
    
    if [ $total_completed -gt 0 ]; then
        echo "✅ Completed:"
        for host in "${completed_hosts[@]}"; do
            print_success "$host"
        done
        echo ""
    fi
    
    if [ $total_completed -lt $total_expected ]; then
        echo "⏳ Pending:"
        for host in "${expected_hosts[@]}"; do
            if [[ ! " ${completed_hosts[@]} " =~ " ${host} " ]]; then
                print_warning "$host"
            fi
        done
        echo ""
    fi
    
    # Check for final reports
    if [ -f "audit_results/consolidated_report.md" ]; then
        print_success "Final consolidated report generated!"
        echo "📊 Report: audit_results/consolidated_report.md"
    fi
    
    if [ -f "audit_results/dashboard.html" ]; then
        print_success "HTML dashboard generated!"
        echo "🌐 Dashboard: audit_results/dashboard.html"
    fi
}

# Monitor mode
monitor_mode() {
    print_status "Starting real-time monitoring..."
    print_status "Press Ctrl+C to stop monitoring"
    echo ""
    
    while true; do
        clear
        show_progress
        
        if ! is_ansible_running; then
            if [ $(get_completed_hosts | wc -l) -eq $(get_expected_hosts | wc -l) ]; then
                print_success "🎉 AUDIT DEPLOYMENT COMPLETE!"
                echo ""
                echo "Final Results:"
                echo "📁 Results Directory: audit_results/"
                echo "📊 Summary: audit_results/consolidated_report.md"
                echo "🌐 Dashboard: audit_results/dashboard.html"
                break
            else
                print_warning "Ansible finished but some hosts may have failed"
                echo "Check the logs above for details"
                break
            fi
        fi
        
        print_status "Ansible still running... checking again in 10 seconds"
        sleep 10
    done
}

# Single status check
status_check() {
    show_progress
    
    if is_ansible_running; then
        print_status "Ansible is currently running"
    else
        if [ $(get_completed_hosts | wc -l) -eq $(get_expected_hosts | wc -l) ]; then
            print_success "Audit deployment is complete!"
        else
            print_warning "Ansible finished but deployment may be incomplete"
        fi
    fi
}

# Main function
main() {
    case "${1:-status}" in
        "monitor"|"-m")
            monitor_mode
            ;;
        "status"|"-s")
            status_check
            ;;
        "help"|"-h"|"--help")
            echo "Usage: $0 [option]"
            echo ""
            echo "Options:"
            echo "  monitor, -m    Real-time monitoring mode"
            echo "  status, -s     Single status check (default)"
            echo "  help, -h       Show this help"
            echo ""
            echo "Examples:"
            echo "  $0              # Quick status check"
            echo "  $0 monitor      # Real-time monitoring"
            echo "  $0 status       # Single status check"
            ;;
        *)
            status_check
            ;;
    esac
}

# Run main function
main "$@"
