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

####################################################################
# Koro ERP — Link AI Studio to the ERP Gateway
#
# Run this on the ERP server AFTER deploying the AI service on a
# separate VM using ai/docker-compose.yml.
#
# What it does:
#   1. Prompts for the AI VM's address
#   2. Tests that the AI service is reachable and healthy
#   3. Updates AI_SERVICE_URL in .env
#   4. Restarts the gateway container to pick up the new URL
#
# Usage:
#   chmod +x link-ai.sh
#   ./link-ai.sh
#   ./link-ai.sh --ai-url http://10.0.1.50:7025   # non-interactive
####################################################################

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

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

info()  { echo -e "${BLUE}[INFO]${NC}  $*"; }
ok()    { echo -e "${GREEN}  [OK]${NC}  $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $*"; }
fail()  { echo -e "${RED}[FAIL]${NC}  $*"; exit 1; }
ask()   { echo -en "${CYAN}   [?]${NC}  $* "; }

echo ""
echo -e "${BOLD}${BLUE}╔═══════════════════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}${BLUE}║          Koro ERP — Link AI Studio to Gateway            ║${NC}"
echo -e "${BOLD}${BLUE}╚═══════════════════════════════════════════════════════════╝${NC}"
echo ""

# ── Parse flags ──────────────────────────────────────────────────
AI_URL=""
COMPOSE_FILE="../apis/docker-compose.yml"
ENV_FILE="../apis/.env"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --ai-url)    AI_URL="$2";       shift 2 ;;
    --saas)      COMPOSE_FILE="../apis/docker-compose.yml"; ENV_FILE="../apis/.env"; shift ;;
    --env-file)  ENV_FILE="$2";     shift 2 ;;
    *) shift ;;
  esac
done

# ── Verify .env exists ───────────────────────────────────────────
[[ -f "$ENV_FILE" ]] || fail ".env file not found at $ENV_FILE. Run the APIs installer first."

# ── Get AI VM address ────────────────────────────────────────────
if [[ -z "$AI_URL" ]]; then
  echo -e "  Enter the AI service URL."
  echo -e "  ${YELLOW}Examples:${NC}"
  echo -e "    http://10.0.1.50:7025       (private IP, same network)"
  echo -e "    http://ai.internal:7025     (private DNS)"
  echo ""
  ask "AI service URL [http://AI-VM-IP:7025]:"
  read -r AI_URL
  AI_URL="${AI_URL:-}"
  [[ -z "$AI_URL" ]] && fail "No URL provided."
fi

# Normalise: strip trailing slash
AI_URL="${AI_URL%/}"

# ── Test connectivity ─────────────────────────────────────────────
info "Testing connectivity to $AI_URL ..."
HEALTH_URL="${AI_URL}/health"

HTTP_CODE=$(curl -s -o /tmp/koro_ai_health.json -w "%{http_code}" \
  --connect-timeout 10 --max-time 15 "$HEALTH_URL" 2>/dev/null || echo "000")

if [[ "$HTTP_CODE" == "200" ]]; then
  ok "AI service is reachable and healthy (HTTP $HTTP_CODE)."
elif [[ "$HTTP_CODE" == "000" ]]; then
  echo ""
  warn "Could not reach $HEALTH_URL"
  warn "This could mean:"
  warn "  • The AI VM is not running (check: docker compose -f docker-compose.yml ps)"
  warn "  • Port 7025 is blocked by a firewall"
  warn "  • The IP/hostname is wrong"
  echo ""
  ask "Continue anyway and update .env? [y/N]:"
  read -r FORCE
  [[ "${FORCE,,}" == "y" ]] || fail "Aborted."
else
  warn "AI service responded with HTTP $HTTP_CODE (expected 200). Proceeding anyway."
fi

# ── Update AI_SERVICE_URL in .env ────────────────────────────────
info "Updating AI_SERVICE_URL in $ENV_FILE ..."

if grep -q "^AI_SERVICE_URL=" "$ENV_FILE"; then
  # Replace existing value
  CURRENT=$(grep "^AI_SERVICE_URL=" "$ENV_FILE" | cut -d= -f2-)
  if sed --version >/dev/null 2>&1; then
    sed -i "s|^AI_SERVICE_URL=.*|AI_SERVICE_URL=${AI_URL}|" "$ENV_FILE"
  else
    sed -i '' "s|^AI_SERVICE_URL=.*|AI_SERVICE_URL=${AI_URL}|" "$ENV_FILE"
  fi
  ok "Updated AI_SERVICE_URL: $CURRENT → $AI_URL"
else
  # Append
  echo "AI_SERVICE_URL=${AI_URL}" >> "$ENV_FILE"
  ok "Added AI_SERVICE_URL=${AI_URL} to $ENV_FILE"
fi

# ── Restart gateway ───────────────────────────────────────────────
info "Restarting gateway to apply new AI_SERVICE_URL ..."

COMPOSE_CMD="docker compose"
if ! docker compose version &>/dev/null 2>&1; then
  COMPOSE_CMD="docker-compose"
fi

ENV_ARG=""
[[ "$ENV_FILE" != ".env" ]] && ENV_ARG="--env-file $ENV_FILE"

$COMPOSE_CMD $ENV_ARG -f "$COMPOSE_FILE" up -d gateway

ok "Gateway restarted."

# ── Verify gateway can reach AI ───────────────────────────────────
echo ""
info "Verifying gateway → AI routing ..."
sleep 3

GATEWAY_PORT=$(grep "^GATEWAY_PORT=" "$ENV_FILE" 2>/dev/null | cut -d= -f2- || echo "7009")
GATEWAY_PORT="${GATEWAY_PORT:-7009}"

STATUS_CODE=$(curl -s -o /dev/null -w "%{http_code}" \
  --connect-timeout 5 "http://localhost:${GATEWAY_PORT}/health" 2>/dev/null || echo "000")

if [[ "$STATUS_CODE" == "200" ]]; then
  ok "Gateway is healthy."
else
  warn "Gateway health check returned HTTP $STATUS_CODE — check logs:"
  warn "  $COMPOSE_CMD -f $COMPOSE_FILE logs gateway"
fi

# ── Done ──────────────────────────────────────────────────────────
echo ""
echo -e "${BOLD}${GREEN}════════════════════════════════════════${NC}"
echo -e "${BOLD}${GREEN}  AI Studio linked successfully!        ${NC}"
echo -e "${BOLD}${GREEN}════════════════════════════════════════${NC}"
echo ""
echo -e "  AI service URL : ${CYAN}${AI_URL}${NC}"
echo -e "  All requests to /api/v1/ai/* will now be forwarded"
echo -e "  from the gateway to the AI VM."
echo ""
echo -e "  ${YELLOW}Next steps:${NC}"
echo -e "    • Open the ERP web UI → AI Studio"
echo -e "    • Verify you can create models and start training"
echo -e "    • Monitor the AI VM: ${CYAN}${AI_URL}/health${NC}"
echo ""
echo -e "  ${YELLOW}To change the AI URL later:${NC}"
echo -e "    ./link-ai.sh --ai-url http://NEW-IP:7025"
echo ""
