#!/bin/bash
set -e

SERVICE_DIR="/usr/lib/activeblue-ai"
VENV_DIR="$SERVICE_DIR/venv"
CONFIG_DIR="/etc/activeblue-ai"
LOG_DIR="/var/log/activeblue-ai"
DATA_DIR="/var/lib/activeblue-ai"
SERVICE_USER="activeblue-ai"

# Create service user
if ! id "$SERVICE_USER" &>/dev/null; then
    adduser --system --no-create-home --group --disabled-login \
        --home "$DATA_DIR" "$SERVICE_USER"
    echo "Created service user: $SERVICE_USER"
fi

# Create directories
install -d -m 755 -o "$SERVICE_USER" -g "$SERVICE_USER" "$LOG_DIR"
install -d -m 755 -o "$SERVICE_USER" -g "$SERVICE_USER" "$DATA_DIR"
install -d -m 750 -o "$SERVICE_USER" -g "$SERVICE_USER" "$CONFIG_DIR"

# Create .env if it doesn't exist
if [ ! -f "$CONFIG_DIR/.env" ]; then
    cp "$CONFIG_DIR/.env.example" "$CONFIG_DIR/.env" 2>/dev/null || true
    chmod 640 "$CONFIG_DIR/.env"
    chown "$SERVICE_USER:$SERVICE_USER" "$CONFIG_DIR/.env"
    echo "NOTE: Edit $CONFIG_DIR/.env before starting the service."
fi

# Create and populate virtualenv
if [ ! -d "$VENV_DIR" ]; then
    python3 -m venv "$VENV_DIR"
fi
"$VENV_DIR/bin/pip" install --quiet --upgrade pip
"$VENV_DIR/bin/pip" install --quiet -r "$SERVICE_DIR/requirements.txt"

# Enable and reload systemd
if command -v systemctl &>/dev/null && systemctl is-system-running --quiet 2>/dev/null; then
    systemctl daemon-reload
    systemctl enable activeblue-ai.service
    echo "Service enabled. Run: systemctl start activeblue-ai"
fi

echo "ActiveBlue AI installed successfully."
echo "Configure: $CONFIG_DIR/.env"
echo "Run migrations: activeblue-ai migrate"
