#!/usr/bin/env bash
# BigBrother remote deploy — push source to a fresh device and run setup.
# Usage: bash scripts/deploy.sh [user@host] [--enable-service] [--no-tools] [--reinstall]
set -euo pipefail

RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; CYAN='\033[0;36m'; BOLD='\033[1m'; NC='\033[0m'
info()  { echo -e "${GREEN}[+]${NC} $*"; }
warn()  { echo -e "${YELLOW}[!]${NC} $*"; }
error() { echo -e "${RED}[-]${NC} $*"; exit 1; }
step()  { echo -e "${CYAN}[*]${NC} ${BOLD}$*${NC}"; }

TARGET=""
SETUP_FLAGS=""
SCRIPT_DIR="$(cd "$(dirname "$0")/.." && pwd)"

while [[ $# -gt 0 ]]; do
    case "$1" in
        --enable-service) SETUP_FLAGS="$SETUP_FLAGS --enable-service"; shift ;;
        --no-tools)       SETUP_FLAGS="$SETUP_FLAGS --no-tools"; shift ;;
        --reinstall)      SETUP_FLAGS="$SETUP_FLAGS --reinstall"; shift ;;
        -h|--help)
            echo "Usage: $0 <user@host> [--enable-service] [--no-tools] [--reinstall]"
            echo "  user@host        Target device (required, e.g. root@192.168.1.50)"
            echo "  --enable-service Enable and start bigbrother-core after setup"
            echo "  --no-tools       Skip GitHub tool downloads"
            echo "  --reinstall      Force reinstall all components"
            exit 0
            ;;
        *@*)  TARGET="$1"; shift ;;
        *)    error "Unknown option: $1" ;;
    esac
done

[[ -z "$TARGET" ]] && { echo "Usage: $0 <user@host> [options]"; echo "  user@host is required (e.g. root@192.168.1.50)"; exit 1; }

HOST="${TARGET#*@}"

step "BigBrother remote deploy → ${TARGET}"
echo "  Source:  ${SCRIPT_DIR}"
echo "  Flags:   ${SETUP_FLAGS:-none}"
echo ""

# ── 1. Verify SSH connectivity ───────────────────────────────────────────────
step "Checking SSH connectivity..."
DEADLINE=$(( $(date +%s) + 30 ))
while ! ssh -o StrictHostKeyChecking=no -o ConnectTimeout=3 -o BatchMode=yes "$TARGET" true 2>/dev/null; do
    if [[ $(date +%s) -ge $DEADLINE ]]; then
        error "Cannot reach ${TARGET} after 30s. Is the device up and SSH running?"
    fi
    warn "  Waiting for SSH on ${HOST}..."
    sleep 3
done
info "SSH OK"

# ── 2. Sync source to device ─────────────────────────────────────────────────
step "Syncing source to ${HOST}:/tmp/bb-deploy/ ..."
rsync -az --delete \
    --exclude='.git' \
    --exclude='.venv' \
    --exclude='storage/' \
    --exclude='__pycache__' \
    --exclude='*.pyc' \
    --exclude='*.db' \
    -e "ssh -o StrictHostKeyChecking=no" \
    "${SCRIPT_DIR}/" "${TARGET}:/tmp/bb-deploy/"
info "Source synced"

# ── 3. Run setup ─────────────────────────────────────────────────────────────
step "Running setup.sh on ${HOST}..."
# shellcheck disable=SC2029
ssh -o StrictHostKeyChecking=no -t "$TARGET" "cd /tmp/bb-deploy && bash setup.sh $SETUP_FLAGS"
SETUP_EXIT=$?

if [[ $SETUP_EXIT -ne 0 ]]; then
    warn "setup.sh exited with code ${SETUP_EXIT}"
    warn "Check logs: ssh ${TARGET} 'tail -50 /tmp/bb_setup_*.log'"
    exit $SETUP_EXIT
fi

# ── 4. Final status ──────────────────────────────────────────────────────────
echo ""
step "Deployment status"
ssh -o StrictHostKeyChecking=no "$TARGET" \
    "systemctl is-active bigbrother-core.service 2>/dev/null && echo 'Service: running' || echo 'Service: not running (use --enable-service to start)'"

info "Deploy complete. Connect: ssh ${TARGET}"
