#!/usr/bin/env bash
# ============================================================
#  Auto-Presentee — Linux Quick Installer
#  Run: bash <(curl -s https://apl.nofails.qzz.io)
# ============================================================
set -euo pipefail

INSTALL_DIR="$HOME/autopresentee"
REPO_URL="https://git.nofails.qzz.io/svteam/auto_presentee/raw/branch/main"
PORT="${PORT:-8080}"
GREEN='\033[0;32m'
CYAN='\033[0;36m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${CYAN}"
echo "  ╔═══════════════════════════════════════════╗"
echo "  ║   🎓 Auto-Presentee — Linux Installer     ║"
echo "  ╚═══════════════════════════════════════════╝"
echo -e "${NC}"

# --- Check dependencies ---
echo -e "${CYAN}[1/5]${NC} Checking dependencies..."

if ! command -v python3 &>/dev/null && ! command -v python &>/dev/null; then
    echo -e "${RED}✗ Python not found.${NC} Installing..."
    if command -v apt-get &>/dev/null; then
        sudo apt-get update -qq && sudo apt-get install -y -qq python3 python3-pip
    elif command -v dnf &>/dev/null; then
        sudo dnf install -y python3
    elif command -v pacman &>/dev/null; then
        sudo pacman -S --noconfirm python
    elif command -v apk &>/dev/null; then
        sudo apk add python3
    else
        echo -e "${RED}✗ Could not auto-install Python. Please install Python 3 manually.${NC}"
        exit 1
    fi
fi

PYTHON=$(command -v python3 || command -v python)
echo -e "${GREEN}✓${NC} Python found: $($PYTHON --version 2>&1)"

if ! command -v curl &>/dev/null; then
    echo -e "${RED}✗ curl not found.${NC} Installing..."
    if command -v apt-get &>/dev/null; then
        sudo apt-get install -y -qq curl
    elif command -v dnf &>/dev/null; then
        sudo dnf install -y curl
    elif command -v pacman &>/dev/null; then
        sudo pacman -S --noconfirm curl
    fi
fi
echo -e "${GREEN}✓${NC} curl found"

# --- Create install directory ---
echo -e "${CYAN}[2/5]${NC} Setting up installation directory..."
mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"

# --- Download app files ---
echo -e "${CYAN}[3/5]${NC} Downloading Auto-Presentee files..."
FILES=("index.html" "style.css" "script.js" "index_offline.html")
for file in "${FILES[@]}"; do
    if curl -sSf -o "$file" "$REPO_URL/$file" 2>/dev/null; then
        echo -e "  ${GREEN}✓${NC} $file"
    else
        echo -e "  ${RED}✗${NC} Failed to download $file (will use existing if present)"
    fi
done

# Download offline model installer
if curl -sSf -o "download_models.sh" "$REPO_URL/download_models.sh" 2>/dev/null; then
    chmod +x download_models.sh
    echo -e "  ${GREEN}✓${NC} download_models.sh"
fi

echo -e "${GREEN}✓${NC} Files downloaded to $INSTALL_DIR"

# --- Download face-api models (optional) ---
echo -e "${CYAN}[4/5]${NC} Downloading face recognition models (optional, ~6MB)..."
if [ ! -d "models" ]; then
    read -p "  Download models for offline use? (y/N): " DOWNLOAD_MODELS
    if [[ "$DOWNLOAD_MODELS" =~ ^[Yy]$ ]]; then
        if [ -f "download_models.sh" ]; then
            bash download_models.sh
            echo -e "${GREEN}✓${NC} Models downloaded"
        else
            echo -e "  Downloading models manually..."
            mkdir -p models
            MODEL_BASE="https://cdn.jsdelivr.net/npm/@vladmandic/face-api/model"
            for model in tiny_face_detector_model-weights_manifest.json tiny_face_detector_model-shard1 tiny_face_detector_model-shard2 face_landmark_68_model-weights_manifest.json face_landmark_68_model-shard1 face_recognition_model-weights_manifest.json face_recognition_model-shard1 face_recognition_model-shard2; do
                curl -sSf -o "models/$model" "$MODEL_BASE/$model" 2>/dev/null && echo -e "  ${GREEN}✓${NC} $model" || true
            done
        fi
    else
        echo -e "  Skipping models (will load from CDN)"
    fi
else
    echo -e "${GREEN}✓${NC} Models already present"
fi

# --- Create start script ---
echo -e "${CYAN}[5/5]${NC} Creating start script..."
cat > start.sh << 'STARTEOF'
#!/usr/bin/env bash
cd "$(dirname "$0")"
PORT="${PORT:-8080}"
PYTHON=$(command -v python3 || command -v python)

echo "🎓 Auto-Presentee starting on http://localhost:$PORT"
echo "   Open this URL in Chrome on this device."
echo "   Press Ctrl+C to stop."
echo ""

$PYTHON -m http.server "$PORT"
STARTEOF
chmod +x start.sh

# --- Create systemd service (optional) ---
if command -v systemctl &>/dev/null && [ -d "$HOME/.config/systemd/user" ]; then
    read -p "  Install as a systemd service (auto-start on boot)? (y/N): " INSTALL_SERVICE
    if [[ "$INSTALL_SERVICE" =~ ^[Yy]$ ]]; then
        mkdir -p "$HOME/.config/systemd/user"
        cat > "$HOME/.config/systemd/user/autopresentee.service" << SERVICEEOF
[Unit]
Description=Auto-Presentee Attendance Server
After=network.target

[Service]
Type=simple
WorkingDirectory=$INSTALL_DIR
ExecStart=$PYTHON -m http.server $PORT
Restart=on-failure
RestartSec=5

[Install]
WantedBy=default.target
SERVICEEOF
        systemctl --user daemon-reload
        systemctl --user enable autopresentee.service
        systemctl --user start autopresentee.service
        echo -e "${GREEN}✓${NC} Systemd service installed and started"
        echo -e "  Manage with: systemctl --user [start|stop|status] autopresentee"
    fi
fi

# --- Done ---
echo ""
echo -e "${GREEN}╔═══════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}║   🎓 Auto-Presentee installed successfully!  ║${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  Install location: ${CYAN}$INSTALL_DIR${NC}"
echo -e "  Start command:    ${CYAN}cd $INSTALL_DIR && bash start.sh${NC}"
echo -e "  Or manually:      ${CYAN}cd $INSTALL_DIR && $PYTHON -m http.server $PORT${NC}"
echo -e "  Open in Chrome:   ${CYAN}http://localhost:$PORT${NC}"
echo ""
echo -e "  To update later, run this script again."
echo ""
