#!/bin/bash
################################################################################
# ⚠️  AI ENTRYPOINT: READ FIRST
#
# This is a Sovereign Agent Hub (Engram). Before making any changes, review:
# → docs/PROJECT_INTELLIGENCE.md (governance framework)
#
# Core Mandates (Non-Negotiable):
# 1. Stealth-by-Default — No auto-discovery or auto-expansion without toggles
# 2. Self-Healing Entrypoints — All services auto-regenerate missing configs
# 3. Hardening Wizard — Model transitions require explicit user consent
# 4. Hardware Handshake — Initial provisioning via out-of-band (USB/cable)
#
# See docs/PROJECT_INTELLIGENCE.md for complete ruleset.
################################################################################
#
# Engram Fleet Installer — One-Click Setup
# Detects environment, validates prerequisites, and launches the full deployment.
# Handles both Hub (local Docker) and Jetson (mesh provisioning).

set -euo pipefail

# ============================================================================
# Colors & Logging
# ============================================================================

RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

log_header() {
    echo ""
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

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

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

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

# ============================================================================
# Step 1: Detect Docker Command
# ============================================================================

log_header "Step 1: Detecting Docker Setup"

DOCKER_CMD=""

if command -v docker &> /dev/null; then
    # Check if `docker compose` works (v20.10+)
    if docker compose version &> /dev/null; then
        DOCKER_CMD="docker compose"
        log_success "Found: docker compose (modern)"
    elif command -v docker-compose &> /dev/null; then
        DOCKER_CMD="docker-compose"
        log_warn "Using legacy docker-compose (consider upgrading to Docker v20.10+)"
    else
        log_error "Docker found but 'docker compose' command not available. Please upgrade Docker."
    fi
else
    log_error "Docker is not installed. Please install Docker Desktop or Docker Engine."
fi

log_success "Docker command: $DOCKER_CMD"

# ============================================================================
# Step 2: Verify Prerequisites
# ============================================================================

log_header "Step 2: Verifying Prerequisites"

# Check Python version (required for Paperclip orchestrator)
PYTHON_VERSION=$(python3 --version 2>&1 | awk '{print $2}')
log_info "Python version: $PYTHON_VERSION"

# Verify Python 3.10+ (required for PydanticAI, union types)
PYTHON_MAJOR=$(echo $PYTHON_VERSION | cut -d'.' -f1)
PYTHON_MINOR=$(echo $PYTHON_VERSION | cut -d'.' -f2)

if [ "$PYTHON_MAJOR" -lt 3 ] || ([ "$PYTHON_MAJOR" -eq 3 ] && [ "$PYTHON_MINOR" -lt 10 ]); then
    log_error "Python 3.10+ required (found $PYTHON_VERSION). Please upgrade Python."
fi
log_success "Python 3.10+ verified"

# Check Docker version
DOCKER_VERSION=$(docker --version | grep -oP 'Docker version \K[0-9]+\.[0-9]+' || echo "unknown")
log_info "Docker version: $DOCKER_VERSION"

# Check .env file
if [[ ! -f ".env" ]]; then
    log_warn ".env file not found"
    log_info "Creating .env from .env.example..."
    if [[ -f ".env.example" ]]; then
        cp .env.example .env
        log_success ".env created"
    else
        log_error ".env and .env.example not found. Create .env with MATRIX_REGISTRATION_SECRET."
    fi
fi

# Check and auto-generate MATRIX_REGISTRATION_SECRET
if grep -q "^MATRIX_REGISTRATION_SECRET=" .env; then
    log_success "MATRIX_REGISTRATION_SECRET found in .env"
else
    log_info "MATRIX_REGISTRATION_SECRET not found — generating secure secret..."
    GENERATED_SECRET=$(openssl rand -hex 32)
    echo "MATRIX_REGISTRATION_SECRET=$GENERATED_SECRET" >> .env
    log_success "MATRIX_REGISTRATION_SECRET generated and saved to .env"
fi

# Check if git repo is clean (optional warning)
if ! git status --short &> /dev/null; then
    log_warn "Not a git repository (or git not available)"
else
    if [[ -n "$(git status --short)" ]]; then
        log_warn "Working directory has uncommitted changes"
    fi
fi

log_success "Prerequisites verified"

# ============================================================================
# Step 3: Launch Hub Services
# ============================================================================

log_header "Step 3: Starting Engram Hub"

log_info "Stopping any existing services..."
$DOCKER_CMD down --remove-orphans 2>/dev/null || true

log_info "Building and starting Hub services..."
$DOCKER_CMD build --no-cache 2>&1 | grep -E "(Building|Successfully)" || true
$DOCKER_CMD up -d

# Wait for Hub to be healthy
log_info "Waiting for Hub to be healthy..."
RETRIES=30
while [[ $RETRIES -gt 0 ]]; do
    if curl -sf http://localhost:8000/health > /dev/null 2>&1; then
        log_success "Hub is healthy"
        break
    fi
    echo -n "."
    sleep 1
    RETRIES=$((RETRIES - 1))
done

if [[ $RETRIES -le 0 ]]; then
    log_warn "Hub health check timed out (this may be normal on first run)"
fi

log_success "Hub is running at http://localhost:8000"
log_info "Interactive docs: http://localhost:8000/docs"

# ============================================================================
# Step 4: Jetson Deployment (Optional)
# ============================================================================

log_header "Step 4: Jetson Fleet Provisioning (Optional)"

echo ""
echo "Do you have an NVIDIA Jetson device you want to connect to Engram?"
echo "  • If you're just starting: answer 'n' (no)"
echo "  • If you have a Jetson: answer 'y' (yes)"
echo ""

read -p "Connect a Jetson? (y/n) [n]: " PROVISION_JETSON
PROVISION_JETSON="${PROVISION_JETSON:-n}"

if [[ "$PROVISION_JETSON" =~ ^[Yy]$ ]]; then
    log_info "Jetson provisioning requires some setup. This is for advanced users."
    log_info "Starting Jetson provisioning flow..."

    # Check prerequisites
    if ! command -v tailscale &> /dev/null; then
        log_error "Tailscale not found. Please install: https://tailscale.com/download"
    fi

    if ! command -v jq &> /dev/null; then
        log_warn "jq not found. Some validation may be skipped."
    fi

    # Check SSH setup
    log_info "Checking SSH setup..."
    JETSON_IP="${JETSON_IP:-192.168.x.x}"
    read -p "Jetson IP address [$JETSON_IP]: " INPUT_IP
    JETSON_IP="${INPUT_IP:-$JETSON_IP}"

    JETSON_USER="${JETSON_USER:-howsa}"
    read -p "Jetson username [$JETSON_USER]: " INPUT_USER
    JETSON_USER="${INPUT_USER:-$JETSON_USER}"

    if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no "$JETSON_USER@$JETSON_IP" "echo 'SSH OK'" &> /dev/null; then
        log_error "Cannot SSH to $JETSON_USER@$JETSON_IP. Check network and credentials."
    fi
    log_success "SSH connectivity verified"

    # Setup passwordless sudo (if needed)
    log_info "Checking passwordless sudo on Jetson..."
    if ! ssh "$JETSON_USER@$JETSON_IP" "sudo -n ls /root" &> /dev/null; then
        log_warn "Passwordless sudo not configured"
        log_info "Setting up passwordless sudo..."
        ssh -t "$JETSON_USER@$JETSON_IP" \
            "echo '$JETSON_USER ALL=(ALL) NOPASSWD: ALL' | sudo tee /etc/sudoers.d/engram-prep > /dev/null" \
            || log_error "Could not setup passwordless sudo"
        log_success "Passwordless sudo configured"
    else
        log_success "Passwordless sudo already enabled"
    fi

    # Generate mesh auth
    log_info "Generating Tailscale mesh authentication..."
    python3 scripts/get_mesh_auth.py || log_error "Mesh auth generation failed"
    log_success "Manifest and auth key generated"

    # Deploy to Jetson
    log_info "Deploying to Jetson..."
    bash scripts/deploy_to_node.sh || log_error "Deployment script failed"
    log_success "Jetson provisioning complete"

    # Verify node in mesh
    log_info "Verifying node joined mesh..."
    sleep 5
    if tailscale status | grep -q "jetson"; then
        log_success "Jetson is online in Tailscale mesh"
        JETSON_TAILSCALE_IP=$(tailscale status | grep jetson | awk '{print $1}' | head -1)
        log_info "Jetson Tailscale IP: $JETSON_TAILSCALE_IP"
        log_info "Access via: ssh $JETSON_USER@$JETSON_TAILSCALE_IP"
    else
        log_warn "Jetson not yet visible in mesh (may still be provisioning)"
        log_info "Check status manually: tailscale status | grep jetson"
    fi
else
    log_info "Skipping Jetson provisioning (you can run it later)"
fi

# ============================================================================
# Final Status
# ============================================================================

log_header "Setup Complete!"

echo ""
echo -e "${GREEN}Engram is ready for deployment.${NC}"
echo ""
echo "Hub Dashboard:"
echo "  • Web UI: http://localhost:8000"
echo "  • API Docs: http://localhost:8000/docs"
echo "  • Health: curl http://localhost:8000/health"
echo ""

if [[ "$PROVISION_JETSON" =~ ^[Yy]$ ]]; then
    echo "Jetson Node:"
    echo "  • Check status: tailscale status | grep jetson"
    echo "  • SSH access: ssh $JETSON_USER@<tailscale-ip>"
    echo ""
fi

echo "Troubleshooting:"
echo "  • See TROUBLESHOOTING.md for common issues"
echo "  • View logs: $DOCKER_CMD logs -f hub"
echo ""

log_success "Good luck with Engram!"
