#!/bin/bash
# Uni-Wizard v4 Production Setup Script
# Run this on a fresh VPS to deploy the Uni-Wizard architecture

set -e

echo "╔═══════════════════════════════════════════════════════════════╗"
echo "║     Uni-Wizard v4 — Production Setup                          ║"
echo "╚═══════════════════════════════════════════════════════════════╝"
echo ""

# Configuration
TIMMY_HOME="/opt/timmy"
UNI_WIZARD_DIR="$TIMMY_HOME/uni-wizard"
SERVICE_USER="timmy"

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "❌ Please run as root (use sudo)"
    exit 1
fi

echo "📦 Step 1: Installing dependencies..."
apt-get update
apt-get install -y python3 python3-pip python3-venv sqlite3 curl git

echo "👤 Step 2: Creating timmy user..."
if ! id "$SERVICE_USER" &>/dev/null; then
    useradd -m -s /bin/bash "$SERVICE_USER"
    echo "✅ User $SERVICE_USER created"
else
    echo "✅ User $SERVICE_USER already exists"
fi

echo "📁 Step 3: Setting up directories..."
mkdir -p "$TIMMY_HOME"
mkdir -p "$TIMMY_HOME/logs"
mkdir -p "$TIMMY_HOME/config"
mkdir -p "$TIMMY_HOME/data"
chown -R "$SERVICE_USER:$SERVICE_USER" "$TIMMY_HOME"

echo "🐍 Step 4: Creating Python virtual environment..."
python3 -m venv "$TIMMY_HOME/venv"
source "$TIMMY_HOME/venv/bin/activate"
pip install --upgrade pip

echo "📥 Step 5: Cloning timmy-home repository..."
if [ -d "$TIMMY_HOME/repo" ]; then
    echo "✅ Repository already exists, pulling latest..."
    cd "$TIMMY_HOME/repo"
    sudo -u "$SERVICE_USER" git pull
else
    sudo -u "$SERVICE_USER" git clone http://143.198.27.163:3000/Timmy_Foundation/timmy-home.git "$TIMMY_HOME/repo"
fi

echo "🔗 Step 6: Linking Uni-Wizard..."
ln -sf "$TIMMY_HOME/repo/uni-wizard/v4/uni_wizard" "$TIMMY_HOME/uni_wizard"

echo "⚙️  Step 7: Installing Uni-Wizard package..."
cd "$TIMMY_HOME/repo/uni-wizard/v4"
pip install -e .

echo "📝 Step 8: Creating configuration..."
cat > "$TIMMY_HOME/config/uni-wizard.yaml" << 'EOF'
# Uni-Wizard v4 Configuration
house: timmy
mode: intelligent
enable_learning: true

# Database
pattern_db: /opt/timmy/data/patterns.db

# Telemetry
telemetry_enabled: true
telemetry_buffer_size: 1000

# Circuit breaker
circuit_breaker:
  failure_threshold: 5
  recovery_timeout: 60

# Logging
log_level: INFO
log_dir: /opt/timmy/logs

# Gitea integration
gitea:
  url: http://143.198.27.163:3000
  repo: Timmy_Foundation/timmy-home
  poll_interval: 300  # 5 minutes

# Hermes bridge
hermes:
  db_path: /root/.hermes/state.db
  stream_enabled: true
EOF

chown "$SERVICE_USER:$SERVICE_USER" "$TIMMY_HOME/config/uni-wizard.yaml"

echo "🔧 Step 9: Creating systemd services..."

# Uni-Wizard service
cat > /etc/systemd/system/uni-wizard.service << EOF
[Unit]
Description=Uni-Wizard v4 - Self-Improving Intelligence
After=network.target

[Service]
Type=simple
User=$SERVICE_USER
WorkingDirectory=$TIMMY_HOME
Environment=PYTHONPATH=$TIMMY_HOME/venv/lib/python3.12/site-packages
ExecStart=$TIMMY_HOME/venv/bin/python -m uni_wizard daemon
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

# Health daemon
cat > /etc/systemd/system/timmy-health.service << EOF
[Unit]
Description=Timmy Health Check Daemon
After=network.target

[Service]
Type=simple
User=$SERVICE_USER
WorkingDirectory=$TIMMY_HOME
ExecStart=$TIMMY_HOME/venv/bin/python -m uni_wizard health_daemon
Restart=always
RestartSec=30

[Install]
WantedBy=multi-user.target
EOF

# Task router
cat > /etc/systemd/system/timmy-task-router.service << EOF
[Unit]
Description=Timmy Gitea Task Router
After=network.target

[Service]
Type=simple
User=$SERVICE_USER
WorkingDirectory=$TIMMY_HOME
ExecStart=$TIMMY_HOME/venv/bin/python -m uni_wizard task_router
Restart=always
RestartSec=60

[Install]
WantedBy=multi-user.target
EOF

echo "🚀 Step 10: Enabling services..."
systemctl daemon-reload
systemctl enable uni-wizard timmy-health timmy-task-router

echo ""
echo "╔═══════════════════════════════════════════════════════════════╗"
echo "║     Setup Complete!                                           ║"
echo "╠═══════════════════════════════════════════════════════════════╣"
echo "║                                                               ║"
echo "║  Next steps:                                                  ║"
echo "║  1. Configure Gitea API token:                                ║"
echo "║     edit $TIMMY_HOME/config/uni-wizard.yaml                  ║"
echo "║                                                               ║"
echo "║  2. Start services:                                           ║"
echo "║     systemctl start uni-wizard                                ║"
echo "║     systemctl start timmy-health                              ║"
echo "║     systemctl start timmy-task-router                         ║"
echo "║                                                               ║"
echo "║  3. Check status:                                             ║"
echo "║     systemctl status uni-wizard                               ║"
echo "║                                                               ║"
echo "╚═══════════════════════════════════════════════════════════════╝"
echo ""
echo "Installation directory: $TIMMY_HOME"
echo "Logs: $TIMMY_HOME/logs/"
echo "Config: $TIMMY_HOME/config/"
echo ""
