#!/bin/bash

# System Overview Script
# Comprehensive system status and health check for Rustelo

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
BOLD='\033[1m'
NC='\033[0m' # No Color

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

# Change to project root
cd "$PROJECT_ROOT"

# Logging functions
log() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

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

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_header() {
    echo
    echo -e "${BLUE}${BOLD}═══════════════════════════════════════════════════════════════${NC}"
    echo -e "${BLUE}${BOLD}$(printf "%*s" $(((50 - ${#1})/2)) '')${1}$(printf "%*s" $(((70 - ${#1})/2)) '') ${NC}"
    echo -e "${BLUE}${BOLD}═══════════════════════════════════════════════════════════════${NC}"
}

print_section() {
    echo
    echo -e "${CYAN}${BOLD}─ $1 ──────────────────────────────────────────${NC}"
}

print_section_end() {
    echo -e "${CYAN}${BOLD}──────────────────────────────────────────────────────────────${NC}"
}

print_item() {
    local status="$1"
    local name="$2"
    local value="$3"

    case $status in
        "ok")
            echo -e "${GREEN}  ✓${NC} $name: $value"
            ;;
        "warn")
            echo -e "${YELLOW}  ⚠${NC} $name: $value"
            ;;
        "error")
            echo -e "${RED}  ✗${NC} $name: $value"
            ;;
        "info")
            echo -e "${BLUE}  ●${NC} $name: $value"
            ;;
        *)
            echo -e "  $name: $value"
            ;;
    esac
}

# Get system information
get_system_info() {
    print_section "System Information"

    # Operating System
    if [[ "$OSTYPE" == "darwin"* ]]; then
        local os_name="macOS $(sw_vers -productVersion)"
    elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
        local os_name="Linux $(lsb_release -d 2>/dev/null | cut -f2 || echo 'Unknown')"
    else
        local os_name="$OSTYPE"
    fi

    print_item "info" "Operating System" "$os_name"
    print_item "info" "Architecture" "$(uname -m)"
    print_item "info" "Hostname" "$(hostname)"
    print_item "info" "Uptime" "$(uptime | sed 's/.*up //' | sed 's/, [0-9]* users.*//')"

    # CPU and Memory
    local cpu_count=$(nproc 2>/dev/null || sysctl -n hw.ncpu 2>/dev/null || echo "Unknown")
    print_item "info" "CPU Cores" "$cpu_count"

    if command -v free >/dev/null 2>&1; then
        local memory_info=$(free -h | grep '^Mem:' | awk '{print $2}')
        print_item "info" "Total Memory" "$memory_info"
    fi

    print_section_end
}

# Check development tools
check_dev_tools() {
    print_section "Development Tools"

    # Rust
    if command -v rustc >/dev/null 2>&1; then
        print_item "ok" "Rust" "$(rustc --version | cut -d' ' -f2)"
    else
        print_item "error" "Rust" "Not installed"
    fi

    # Cargo
    if command -v cargo >/dev/null 2>&1; then
        print_item "ok" "Cargo" "$(cargo --version | cut -d' ' -f2)"
    else
        print_item "error" "Cargo" "Not installed"
    fi

    # Node.js
    if command -v node >/dev/null 2>&1; then
        print_item "ok" "Node.js" "$(node --version)"
    else
        print_item "warn" "Node.js" "Not installed"
    fi

    # npm
    if command -v npm >/dev/null 2>&1; then
        print_item "ok" "npm" "$(npm --version)"
    else
        print_item "warn" "npm" "Not installed"
    fi

    # Docker
    if command -v docker >/dev/null 2>&1; then
        print_item "ok" "Docker" "$(docker --version | cut -d' ' -f3 | sed 's/,//')"
    else
        print_item "warn" "Docker" "Not installed"
    fi

    # Git
    if command -v git >/dev/null 2>&1; then
        print_item "ok" "Git" "$(git --version | cut -d' ' -f3)"
    else
        print_item "error" "Git" "Not installed"
    fi

    # Just
    if command -v just >/dev/null 2>&1; then
        print_item "ok" "Just" "$(just --version | cut -d' ' -f2)"
    else
        print_item "warn" "Just" "Not installed"
    fi

    print_section_end
}

# Check project structure
check_project_structure() {
    print_section "Project Structure"

    # Core files
    if [ -f "Cargo.toml" ]; then
        print_item "ok" "Cargo.toml" "Present"
    else
        print_item "error" "Cargo.toml" "Missing"
    fi

    if [ -f "package.json" ]; then
        print_item "ok" "package.json" "Present"
    else
        print_item "warn" "package.json" "Missing"
    fi

    if [ -f "justfile" ]; then
        print_item "ok" "justfile" "Present"
    else
        print_item "warn" "justfile" "Missing"
    fi

    if [ -f ".env" ]; then
        print_item "ok" ".env" "Present"
    else
        print_item "warn" ".env" "Missing (run setup)"
    fi

    # Directories
    local dirs=("src" "server" "client" "shared" "scripts" "public")
    for dir in "${dirs[@]}"; do
        if [ -d "$dir" ]; then
            print_item "ok" "$dir/" "Present"
        else
            print_item "warn" "$dir/" "Missing"
        fi
    done

    print_section_end
}

# Check database status
check_database() {
    print_section "Database Status"

    if [ -f ".env" ]; then
        source .env 2>/dev/null || true

        if [ -n "$DATABASE_URL" ]; then
            print_item "info" "Database URL" "${DATABASE_URL:0:30}..."

            # Try to connect to database
            if command -v psql >/dev/null 2>&1; then
                if psql "$DATABASE_URL" -c '\q' 2>/dev/null; then
                    print_item "ok" "Database Connection" "Connected"
                else
                    print_item "error" "Database Connection" "Failed"
                fi
            else
                print_item "warn" "Database Connection" "psql not available"
            fi
        else
            print_item "error" "Database URL" "Not configured"
        fi
    else
        print_item "warn" "Database Configuration" "No .env file"
    fi

    print_section_end
}

# Check application health
check_application() {
    print_section "Application Health"

    local app_url="http://localhost:3030"

    # Check if application is running
    if curl -f -s "${app_url}/health" >/dev/null 2>&1; then
        print_item "ok" "Application" "Running at $app_url"

        # Check specific endpoints
        if curl -f -s "${app_url}/health" >/dev/null 2>&1; then
            print_item "ok" "Health Endpoint" "Responding"
        else
            print_item "warn" "Health Endpoint" "Not responding"
        fi

        if curl -f -s "${app_url}/metrics" >/dev/null 2>&1; then
            print_item "ok" "Metrics Endpoint" "Responding"
        else
            print_item "warn" "Metrics Endpoint" "Not responding"
        fi
    else
        print_item "error" "Application" "Not running"
        print_item "info" "Start Command" "just dev"
    fi

    print_section_end
}

# Check scripts
check_scripts() {
    print_section "Scripts Status"

    local script_count=0
    local executable_count=0

    # Count scripts
    if [ -d "scripts" ]; then
        script_count=$(find scripts -name "*.sh" -type f | wc -l)
        executable_count=$(find scripts -name "*.sh" -type f -executable | wc -l)

        print_item "info" "Total Scripts" "$script_count"
        print_item "info" "Executable Scripts" "$executable_count"

        if [ $script_count -eq $executable_count ]; then
            print_item "ok" "Script Permissions" "All scripts are executable"
        else
            print_item "warn" "Script Permissions" "Some scripts are not executable"
            print_item "info" "Fix Command" "just scripts-executable"
        fi

        # Check key scripts
        local key_scripts=("databases/db.sh" "tools/performance.sh" "tools/security.sh" "tools/ci.sh" "tools/monitoring.sh")
        for script in "${key_scripts[@]}"; do
            if [ -f "scripts/$script" ]; then
                if [ -x "scripts/$script" ]; then
                    print_item "ok" "$script" "Available"
                else
                    print_item "warn" "$script" "Not executable"
                fi
            else
                print_item "error" "$script" "Missing"
            fi
        done
    else
        print_item "error" "Scripts Directory" "Missing"
    fi

    print_section_end
}

# Check git status
check_git() {
    print_section "Git Status"

    if [ -d ".git" ]; then
        print_item "ok" "Git Repository" "Initialized"

        local branch=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
        print_item "info" "Current Branch" "$branch"

        local commit=$(git rev-parse --short HEAD 2>/dev/null)
        print_item "info" "Latest Commit" "$commit"

        # Check for uncommitted changes
        if git diff --quiet 2>/dev/null; then
            print_item "ok" "Working Directory" "Clean"
        else
            print_item "warn" "Working Directory" "Has uncommitted changes"
        fi

        # Check for untracked files
        if [ -z "$(git ls-files --others --exclude-standard 2>/dev/null)" ]; then
            print_item "ok" "Untracked Files" "None"
        else
            print_item "info" "Untracked Files" "Present"
        fi
    else
        print_item "error" "Git Repository" "Not initialized"
    fi

    print_section_end
}

# Show available commands
show_commands() {
    print_section "Available Commands"

    if command -v just >/dev/null 2>&1; then
        print_item "info" "Task Runner" "just (recommended)"
        echo
        echo -e "${CYAN}  Common Commands:${NC}"
        echo -e "    ${GREEN}just dev${NC}                 - Start development server"
        echo -e "    ${GREEN}just build${NC}               - Build project"
        echo -e "    ${GREEN}just test${NC}                - Run tests"
        echo -e "    ${GREEN}just db-setup${NC}            - Setup database"
        echo -e "    ${GREEN}just security-audit${NC}      - Run security audit"
        echo -e "    ${GREEN}just perf-benchmark${NC}      - Run performance tests"
        echo -e "    ${GREEN}just monitor-health${NC}      - Monitor application health"
        echo -e "    ${GREEN}just ci-pipeline${NC}         - Run CI/CD pipeline"
        echo
        echo -e "${CYAN}  Help Commands:${NC}"
        echo -e "    ${GREEN}just${NC}                     - Show all available commands"
        echo -e "    ${GREEN}just help-all${NC}            - Show comprehensive help"
    else
        print_item "info" "Task Runner" "Direct script execution"
        echo
        echo -e "${CYAN}  Database Commands:${NC}"
        echo -e "    ${GREEN}./scripts/databases/db.sh setup${NC}      - Setup database"
        echo -e "    ${GREEN}./scripts/databases/db.sh status${NC}     - Check database status"
        echo
        echo -e "${CYAN}  Tool Commands:${NC}"
        echo -e "    ${GREEN}./scripts/tools/performance.sh benchmark load${NC}  - Performance test"
        echo -e "    ${GREEN}./scripts/tools/security.sh audit full${NC}        - Security audit"
        echo -e "    ${GREEN}./scripts/tools/monitoring.sh monitor health${NC}   - Health monitoring"
    fi

    print_section_end
}

# Main overview function
main() {
    print_header "🚀 RUSTELO SYSTEM OVERVIEW"

    get_system_info
    check_dev_tools
    check_project_structure
    check_database
    check_application
    check_scripts
    check_git
    show_commands

    echo
    echo -e "${MAGENTA}${BOLD}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${MAGENTA}${BOLD}║                 SUMMARY                                      ║${NC}"
    echo -e "${MAGENTA}${BOLD}╚══════════════════════════════════════════════════════════════╝${NC}"

    echo
    echo -e "${GREEN}✓ System Overview Complete${NC}"
    echo -e "${BLUE}● For development: ${GREEN}just dev${NC}"
    echo -e "${BLUE}● For help: ${GREEN}just help-all${NC}"
    echo -e "${BLUE}● For status updates: ${GREEN} ${0} ${NC}"
    echo
}

# Run main function
main "$@"
