#!/usr/bin/env bash
set -euo pipefail

# HyperAI Installer
# Usage: curl -fsSL https://hyperai.dev/install.sh | bash

BOLD="\033[1m"
DIM="\033[2m"
PURPLE="\033[0;35m"
GREEN="\033[0;32m"
YELLOW="\033[0;33m"
RED="\033[0;31m"
RESET="\033[0m"

INSTALL_DIR="${HYPERAI_DIR:-$HOME/hyperai}"
COMPOSE_URL="https://hyperai.dev/install/docker-compose.yml"

echo ""
echo -e "${PURPLE}${BOLD}  HyperAI Installer${RESET}"
echo -e "${DIM}  AI-powered Proxmox management${RESET}"
echo ""

# --- Checks ---

# Check Docker
if ! command -v docker &> /dev/null; then
    echo -e "${RED}✗ Docker is not installed.${RESET}"
    echo "  Install Docker: https://docs.docker.com/engine/install/"
    exit 1
fi
echo -e "${GREEN}✓${RESET} Docker found: $(docker --version | head -1)"

# Check Docker Compose
if ! docker compose version &> /dev/null; then
    echo -e "${RED}✗ Docker Compose is not available.${RESET}"
    echo "  Install Docker Compose: https://docs.docker.com/compose/install/"
    exit 1
fi
echo -e "${GREEN}✓${RESET} Docker Compose found: $(docker compose version --short)"

# Check curl
if ! command -v curl &> /dev/null; then
    echo -e "${RED}✗ curl is not installed.${RESET}"
    exit 1
fi

# Check openssl (for secret generation)
if ! command -v openssl &> /dev/null; then
    echo -e "${YELLOW}! openssl not found — will use /dev/urandom for secret generation${RESET}"
    GEN_SECRET="head -c 32 /dev/urandom | xxd -p | tr -d '\n'"
else
    GEN_SECRET="openssl rand -hex 32"
fi

echo ""

# --- License Key ---

if [ -n "${HYPERAI_LICENSE_KEY:-}" ]; then
    echo -e "${GREEN}✓${RESET} License key provided via environment"
    LICENSE_KEY="$HYPERAI_LICENSE_KEY"
else
    echo -e "${BOLD}Enter your license key${RESET} ${DIM}(get one free at https://hyperai.dev/register)${RESET}"
    echo -ne "${PURPLE}  HYPR-${RESET}"
    read -r KEY_SUFFIX
    if [ -z "$KEY_SUFFIX" ]; then
        echo -e "${RED}✗ No license key provided. Get one at https://hyperai.dev/register${RESET}"
        exit 1
    fi
    LICENSE_KEY="HYPR-${KEY_SUFFIX}"
fi

echo ""

# --- Install ---

echo -e "${BOLD}Installing to ${INSTALL_DIR}${RESET}"
mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"

# Download docker-compose.yml
echo -e "${DIM}  Downloading docker-compose.yml...${RESET}"
curl -fsSL "$COMPOSE_URL" -o docker-compose.yml

# Generate .env
SESSION_SECRET=$(eval "$GEN_SECRET")

cat > .env << EOF
# HyperAI Configuration
# Docs: https://hyperai.dev/docs/install

# License (required)
HYPERAI_LICENSE_KEY=${LICENSE_KEY}

# Security (auto-generated — do not share)
SESSION_SECRET=${SESSION_SECRET}

# CORS (update if using a reverse proxy with a custom domain)
ALLOWED_ORIGINS=http://localhost:3000

# AI keys and SMTP are now configured through the setup wizard in the UI.
# You can also set them here as overrides if preferred:
# ANTHROPIC_API_KEY=
# SMTP_HOST=
EOF

echo -e "${GREEN}✓${RESET} Configuration saved to ${INSTALL_DIR}/.env"

# --- Start ---

echo ""
echo -e "${BOLD}Starting HyperAI...${RESET}"
docker compose pull --quiet 2>/dev/null || true
docker compose up -d

# Wait for health check
echo -ne "${DIM}  Waiting for HyperAI to start...${RESET}"
for i in $(seq 1 30); do
    if curl -sf http://localhost:3000/api/v1/health > /dev/null 2>&1; then
        echo ""
        echo -e "${GREEN}✓${RESET} HyperAI is running!"
        break
    fi
    echo -n "."
    sleep 1
done

# Check if it actually started
if ! curl -sf http://localhost:3000/api/v1/health > /dev/null 2>&1; then
    echo ""
    echo -e "${RED}✗ HyperAI didn't start in time.${RESET}"
    echo "  Check logs: docker compose logs hyperai"
    exit 1
fi

# --- Done ---

SERVER_IP=$(hostname -I 2>/dev/null | awk '{print $1}' || echo "localhost")

echo ""
echo -e "${PURPLE}${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}"
echo ""
echo -e "  ${GREEN}${BOLD}HyperAI is ready!${RESET}"
echo ""
echo -e "  ${BOLD}Open:${RESET}  http://${SERVER_IP}:3000"
echo ""
echo -e "  ${BOLD}Next steps:${RESET}"
echo -e "  1. Open HyperAI in your browser"
echo -e "  2. The setup wizard will guide you through:"
echo -e "     ${DIM}• Creating your admin account${RESET}"
echo -e "     ${DIM}• Connecting your Proxmox server${RESET}"
echo -e "     ${DIM}• Configuring AI (optional)${RESET}"
echo ""
echo -e "  ${DIM}Docs:    https://hyperai.dev/docs/install${RESET}"
echo -e "  ${DIM}Config:  ${INSTALL_DIR}/.env${RESET}"
echo -e "  ${DIM}Logs:    docker compose -f ${INSTALL_DIR}/docker-compose.yml logs${RESET}"
echo -e "  ${DIM}Update:  docker compose pull && docker compose up -d${RESET}"
echo ""
echo -e "${PURPLE}${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}"
echo ""
