#!/usr/bin/env bash
# deploy-bezalel.sh — One-command Bezalel deployment
#
# Usage:
#   ./deploy-bezalel.sh          # Full deploy
#   ./deploy-bezalel.sh --check  # Dry run
#   ./deploy-bezalel.sh --config # Config only
#
# Requires: ansible-playbook, SSH access to 159.203.146.185

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
INVENTORY="$SCRIPT_DIR/../inventory/hosts.yml"
PLAYBOOK="$SCRIPT_DIR/../playbooks/site.yml"
WIZARD="bezalel"
VPS="159.203.146.185"

log() { echo "[deploy-bezalel] $*"; }

# Pre-flight checks
if ! command -v ansible-playbook &>/dev/null; then
    echo "ERROR: ansible-playbook not found" >&2
    exit 1
fi

if [ ! -f "$INVENTORY" ]; then
    echo "ERROR: Inventory not found at $INVENTORY" >&2
    exit 1
fi

# Test SSH connectivity
log "Testing SSH connectivity to $VPS..."
if ! ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=accept-new "root@$VPS" "echo 'SSH OK'" 2>/dev/null; then
    echo "ERROR: Cannot reach $VPS via SSH" >&2
    exit 1
fi

# Parse args
EXTRA_ARGS="--limit $WIZARD"
if [ "${1:-}" = "--check" ]; then
    EXTRA_ARGS="$EXTRA_ARGS --check --diff"
    log "DRY RUN mode"
elif [ "${1:-}" = "--config" ]; then
    EXTRA_ARGS="$EXTRA_ARGS --tags golden,config"
    log "CONFIG ONLY mode"
fi

log "Deploying $WIZARD to $VPS..."
ansible-playbook -i "$INVENTORY" "$PLAYBOOK" $EXTRA_ARGS

# Post-deploy validation
log "Validating deployment..."
ssh "root@$VPS" bash <<'REMOTE'
echo "=== Systemd status ==="
systemctl is-active hermes-bezalel 2>/dev/null || echo "hermes-bezalel service not active (may need manual start)"

echo "=== Directory structure ==="
ls -la /root/wizards/bezalel/ 2>/dev/null || echo "wizard dir missing"

echo "=== Config check ==="
if [ -f /root/wizards/bezalel/config.yaml ]; then
    echo "config.yaml exists ($(wc -c < /root/wizards/bezalel/config.yaml) bytes)"
else
    echo "config.yaml MISSING"
fi

echo "=== Banned provider scan ==="
grep -ri 'anthropic\|claude-sonnet\|claude-opus\|claude-haiku' /root/wizards/bezalel/config.yaml 2>/dev/null && echo "BANNED PROVIDER FOUND" || echo "Clean"
REMOTE

log "Deployment complete."
