#!/bin/bash

# Guaardvark System Manager — discover, health-check and repair installs.
# Location: scripts/system-manager/system-manager

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

# Resolve real path of the script to handle symlinks
REAL_SCRIPT_PATH=$(readlink -f "${BASH_SOURCE[0]}")
MANAGER_DIR="$( cd "$( dirname "$REAL_SCRIPT_PATH" )" && pwd )"
LIB_DIR="$MANAGER_DIR/lib"
PYTHON_CMD="${PYTHON_CMD:-python3}"

# Ensure we can import our libs
export PYTHONPATH="$LIB_DIR:$PYTHONPATH"

show_help() {
    echo -e "${BLUE}Guaardvark System Manager${NC}"
    echo "Usage: $0 [COMMAND] [ARGS]"
    echo ""
    echo "Commands:"
    echo "  list               List all registered environments"
    echo "  discover           Scan for new Guaardvark environments"
    echo "  check [path]       Run a health check on an environment"
    echo "  repair             Repair an environment (interactive if no path)"
    echo "  remove             Remove an environment from registry (interactive)"
    echo "  run [path] -- [cmd] Run a command in an environment's context"
    echo "  isolate [path]     Run a command/shell in a Linux namespace (isolated)"
    echo "  status             Overview of system health"
    echo ""
}

select_environment() {
    echo -e "${BLUE}Registered Environments:${NC}"
    local envs=()
    local i=1
    
    # Get environments and store in array
    while IFS='|' read -r path name status; do
        if [ -n "$path" ]; then
            envs+=("$path")
            echo -e "  $i) ${YELLOW}$name${NC} ($path)"
            i=$((i+1))
        fi
    done < <($PYTHON_CMD -c 'from registry import list_environments; envs=list_environments(); [print(k + "|" + v.get("name", "Unknown") + "|" + v.get("status", "?")) for k,v in envs.items()]')

    if [ ${#envs[@]} -eq 0 ]; then
        echo "No environments registered. Run 'discover' first."
        return 1
    fi

    echo -ne "Select an environment (1-${#envs[@]}) or 'q' to quit: "
    read -r choice
    if [[ "$choice" == "q" ]]; then return 1; fi
    if ! [[ "$choice" =~ ^[0-9]+$ ]] || [ "$choice" -lt 1 ] || [ "$choice" -gt ${#envs[@]} ]; then
        echo "Invalid selection."
        return 1
    fi
    
    SELECTED_PATH="${envs[$((choice-1))]}"
    return 0
}

case "$1" in
    --help|-h|help)
        show_help
        ;;
    list)
        $PYTHON_CMD -c 'from registry import list_environments; envs=list_environments(); [print(k + " | " + v.get("name", "Unknown") + " | " + v.get("status", "?")) for k,v in envs.items()]' | column -t -s "|"
        ;;
    discover)
        echo "Scanning for environments..."
        $PYTHON_CMD "$LIB_DIR/discovery.py"
        ;;
    check)
        TARGET_PATH="${2:-$(pwd)}"
        TARGET_PATH=$(readlink -f "$TARGET_PATH")
        echo -e "Checking health for: ${YELLOW}$TARGET_PATH${NC}"
        RESULT=$($PYTHON_CMD "$LIB_DIR/health_check.py" "$TARGET_PATH")
        
        HEALTHY=$(echo "$RESULT" | python3 -c "import sys, json; print(json.load(sys.stdin).get('healthy', False))")
        
        if [ "$HEALTHY" = "True" ]; then
            echo -e "${GREEN}✓ Environment is healthy.${NC}"
        else
            echo -e "${RED}✗ Environment issues detected:${NC}"
            echo "$RESULT" | python3 -c "import sys, json; r=json.load(sys.stdin); [print(f'  - {k}: {v[1]}') for k,v in r.get('details', {}).items() if not v[0]]"
            echo ""
            echo "Try running: $0 repair $TARGET_PATH"
            exit 1
        fi
        ;;
    repair)
        TARGET_PATH="$2"
        if [ -z "$TARGET_PATH" ]; then
            if ! select_environment; then exit 0; fi
            TARGET_PATH="$SELECTED_PATH"
        fi
        TARGET_PATH=$(readlink -f "$TARGET_PATH")
        echo -e "Repairing environment: ${YELLOW}$TARGET_PATH${NC}"

        # Honor project .env PYTHON_CMD (start.sh sources .env after this block).
        if [ -f "$TARGET_PATH/.env" ]; then
            _py_cmd=$(grep -E '^PYTHON_CMD=' "$TARGET_PATH/.env" | tail -1 | cut -d= -f2-)
            if [ -n "$_py_cmd" ] && command -v "$_py_cmd" >/dev/null 2>&1; then
                PYTHON_CMD="$_py_cmd"
            fi
        fi
        PYTHON_CMD="${PYTHON_CMD:-python3}"
        
        # Simple repair logic: rebuild venv if it looks broken
        BACKEND_DIR="$TARGET_PATH/backend"
        VENV_DIR="$BACKEND_DIR/venv"
        
        if [ -d "$BACKEND_DIR" ]; then
            echo "Re-installing dependencies..."
            # The backend venv is Python 3.12 only (backend/requirements.txt header).
            # On Ubuntu 26.04 `python3` is 3.14: a venv built from it has no wheels
            # for numpy 1.26 / pandas 2.2, so pip compiled them from source and
            # failed, and start.sh then threw that venv away (client box,
            # 2026-08-31). Never build or fill a venv from anything but 3.12 —
            # start.sh knows how to install one, so refuse and let it.
            _py312_ok() { "$1" -c 'import sys; sys.exit(0 if sys.version_info[:2] == (3, 12) else 1)' >/dev/null 2>&1; }
            if [ ! -d "$VENV_DIR" ]; then
                if ! _py312_ok "$PYTHON_CMD"; then
                    if command -v python3.12 >/dev/null 2>&1 && _py312_ok python3.12; then
                        PYTHON_CMD=python3.12
                    else
                        echo -e "${RED}✗ No Python 3.12 interpreter found ($PYTHON_CMD is $("$PYTHON_CMD" -V 2>&1)).${NC}"
                        echo -e "${RED}  Not creating a venv from it. Run ./start.sh — it installs Python 3.12 first.${NC}"
                        exit 1
                    fi
                fi
                "$PYTHON_CMD" -m venv "$VENV_DIR" || { echo -e "${RED}✗ venv creation failed (install python3-venv for your Python version).${NC}"; exit 1; }
            fi
            if [ ! -x "$VENV_DIR/bin/pip" ]; then
                echo -e "${RED}✗ venv is broken: $VENV_DIR/bin/pip missing.${NC}"
                exit 1
            fi
            if ! _py312_ok "$VENV_DIR/bin/python"; then
                echo -e "${RED}✗ $VENV_DIR is $("$VENV_DIR/bin/python" -V 2>&1), not Python 3.12. Not installing into it — ./start.sh recreates it.${NC}"
                exit 1
            fi
            # Same pip constraints as start.sh/heal: keep numpy/opencv on the
            # ML stack's pins even from this repair path.
            if [ -z "${PIP_CONSTRAINT:-}" ] && [ -f "$BACKEND_DIR/constraints.txt" ]; then
                export PIP_CONSTRAINT="$BACKEND_DIR/constraints.txt"
            fi
            # Use requirements-base.txt to avoid overwriting smart-installed PyTorch
            if [ -f "$BACKEND_DIR/requirements-base.txt" ]; then
                "$VENV_DIR/bin/pip" install -r "$BACKEND_DIR/requirements-base.txt" || { echo -e "${RED}✗ pip install failed.${NC}"; exit 1; }
            else
                "$VENV_DIR/bin/pip" install -r "$BACKEND_DIR/requirements.txt" || { echo -e "${RED}✗ pip install failed.${NC}"; exit 1; }
            fi
            echo -e "${GREEN}✓ Repair complete.${NC}"
        else
            echo -e "${RED}✗ Cannot repair: $BACKEND_DIR not found.${NC}"
            exit 1
        fi
        ;;
    remove)
        if ! select_environment; then exit 0; fi
        echo -ne "Are you sure you want to remove ${YELLOW}$SELECTED_PATH${NC} from registry? (y/N): "
        read -r confirm
        if [[ "$confirm" =~ ^[Yy]$ ]]; then
            $PYTHON_CMD -c "from registry import remove_environment; remove_environment('$SELECTED_PATH')"
            echo -e "${GREEN}Removed from registry.${NC}"
        fi
        ;;
    run)
        TARGET_PATH="$2"
        shift 2
        # Remove -- if it exists
        if [ "$1" = "--" ]; then shift; fi
        
        if [ -z "$TARGET_PATH" ] || [ -z "$1" ]; then
            echo "Usage: $0 run [path] -- [cmd]"
            exit 1
        fi
        
        TARGET_PATH=$(readlink -f "$TARGET_PATH")
        export GUAARDVARK_ROOT="$TARGET_PATH"
        export LLAMAX_ROOT="$TARGET_PATH"   # legacy alias
        cd "$TARGET_PATH" || exit 1
        
        # Activate venv if it exists for the command
        if [ -f "backend/venv/bin/activate" ]; then
            source "backend/venv/bin/activate"
        fi
        
        exec "$@"
        ;;
    isolate)
        TARGET_PATH="${2:-$(pwd)}"
        shift 2
        # Remove -- if it exists
        if [ "$1" = "--" ]; then shift; fi
        
        TARGET_PATH=$(readlink -f "$TARGET_PATH")
        
        if [ ! -d "$TARGET_PATH" ]; then
            echo -e "${RED}Error: Path '$TARGET_PATH' does not exist.${NC}"
            exit 1
        fi

        echo -e "${BLUE}Entering isolated environment for: ${YELLOW}$TARGET_PATH${NC}"
        
        COMMAND="$@"
        if [ -z "$COMMAND" ]; then COMMAND="/bin/bash"; fi
        
        # Check if we are already root (euid 0)
        if [ "$(id -u)" -eq 0 ]; then
            # Already root (via sudo), use simple unshare
            UNSHARE_CMD="unshare -m -p -f --mount-proc"
        else
            # Not root, try unprivileged user namespace mapping
            UNSHARE_CMD="unshare -r -m -p -f --mount-proc"
            
            # Verify if unprivileged unshare works
            if ! unshare -r true 2>/dev/null; then
                echo -e "${YELLOW}Warning: unprivileged unshare failed. Attempting with sudo...${NC}"
                exec sudo "$REAL_SCRIPT_PATH" isolate "$TARGET_PATH" "$@"
            fi
        fi
        
        exec $UNSHARE_CMD bash -c "
            export GUAARDVARK_ROOT='$TARGET_PATH'
            export LLAMAX_ROOT='$TARGET_PATH'
            cd '$TARGET_PATH' || { echo 'Error: Could not cd to $TARGET_PATH'; exit 1; }
            if [ -f 'backend/venv/bin/activate' ]; then
                source 'backend/venv/bin/activate'
            fi
            echo -e '${GREEN}Namespace PID: \$\$ (Isolated)${NC}'
            echo -e '${BLUE}Current Path: \$(pwd)${NC}'
            $COMMAND
        "
        ;;
    status)
        echo -e "${BLUE}System Manager Status:${NC}"
        $PYTHON_CMD -c 'from registry import list_environments; envs=list_environments(); print("Registered Environments: " + str(len(envs)))'
        $PYTHON_CMD -c 'from registry import REGISTRY_PATH; print("Registry File: " + REGISTRY_PATH)'
        ;;
    *)
        show_help
        ;;
esac
