#!/usr/bin/env bash
# ══════════════════════════════════════════════════════════
# Son of Anton — Fix & Complete Deploy (picks up from Step 7)
# ══════════════════════════════════════════════════════════

set -uo pipefail

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

ok()   { echo -e "  ${GREEN}✔${NC} $1"; }
fail() { echo -e "  ${RED}✘${NC} $1"; }
info() { echo -e "  ${BLUE}ℹ${NC} $1"; }
warn() { echo -e "  ${YELLOW}⚠${NC} $1"; }
step() { echo -e "\n${CYAN}═══════════════════════════════════════════════════${NC}"; echo -e "${WHITE}  $1${NC}"; echo -e "${CYAN}═══════════════════════════════════════════════════${NC}"; }

die() { fail "$1"; exit 1; }

CAPROVER_URL="http://localhost:3000"
APP_NAME="son-of-anton"
BEDROCK_API_KEY="ABSKQmVkcm9ja0FQSUtleS12ZGdrLWF0LTc2OTE4NzYxNDEyODpnc0ZzdmVGUlRVendqcVpJUURzR0Nzb2RSZ09hK1JLTnJTekFBY3FJQjBqL0F1UXVyekxic3VmaEtpRT0="
AWS_REGION="eu-central-1"
PRIMARY_MODEL="eu.anthropic.claude-opus-4-6-v1"
FAST_MODEL="eu.anthropic.claude-haiku-4-5-20251001-v1:0"
DEFAULT_QUOTA="2000000"
MAX_UPLOAD_MB="50"

WORK_DIR="/tmp/son-of-anton-fix-$$"
mkdir -p "$WORK_DIR"
trap "rm -rf $WORK_DIR" EXIT

echo ""
echo -e "${MAGENTA}  🔥 Son of Anton — Completing Deploy 🔥${NC}"
echo ""

# ── Get passwords ──────────────────────────────────
echo -e "  ${WHITE}${BOLD}CapRover admin password:${NC}"
read -s -r -p "  > " CAPROVER_PASSWORD; echo ""
[[ -n "$CAPROVER_PASSWORD" ]] || die "Empty password"

echo -e "  ${WHITE}${BOLD}Son of Anton superadmin password:${NC}"
read -s -r -p "  > " SUPERADMIN_PASSWORD; echo ""
[[ -n "$SUPERADMIN_PASSWORD" ]] || die "Empty password"

JWT_SECRET=$(openssl rand -hex 32)
ok "JWT secret: ${JWT_SECRET:0:16}..."

# ── Login ──────────────────────────────────────────
step "Login to CapRover"

LOGIN_RESP=$(curl -s -X POST \
    -H "Content-Type: application/json" \
    -d "{\"password\":\"${CAPROVER_PASSWORD}\"}" \
    "${CAPROVER_URL}/api/v2/login")

CAPTAIN_TOKEN=$(echo "$LOGIN_RESP" | jq -r '.data.token // empty')
[[ -n "$CAPTAIN_TOKEN" ]] || die "Login failed: $(echo "$LOGIN_RESP" | jq -r '.description // "bad password"')"
ok "Logged in"

# ── Set env vars + volume (THE FIX) ───────────────
step "Configure App (env vars + storage)"

# The fix: volumeName must be a real name, not empty string
CONFIG_RESP=$(curl -s -X POST \
    -H "Content-Type: application/json" \
    -H "x-captain-auth: ${CAPTAIN_TOKEN}" \
    -d "{
  \"appName\": \"${APP_NAME}\",
  \"instanceCount\": 1,
  \"envVars\": [
    {\"key\":\"BEDROCK_API_KEY\",\"value\":\"${BEDROCK_API_KEY}\"},
    {\"key\":\"JWT_SECRET\",\"value\":\"${JWT_SECRET}\"},
    {\"key\":\"SUPERADMIN_PASSWORD\",\"value\":\"${SUPERADMIN_PASSWORD}\"},
    {\"key\":\"AWS_REGION\",\"value\":\"${AWS_REGION}\"},
    {\"key\":\"PRIMARY_MODEL\",\"value\":\"${PRIMARY_MODEL}\"},
    {\"key\":\"FAST_MODEL\",\"value\":\"${FAST_MODEL}\"},
    {\"key\":\"DEFAULT_QUOTA\",\"value\":\"${DEFAULT_QUOTA}\"},
    {\"key\":\"MAX_UPLOAD_MB\",\"value\":\"${MAX_UPLOAD_MB}\"}
  ],
  \"volumes\": [
    {
      \"containerPath\": \"/data\",
      \"volumeName\": \"${APP_NAME}-data\"
    }
  ],
  \"ports\": [],
  \"containerHttpPort\": 80,
  \"notExposeAsWebApp\": false,
  \"forceSsl\": false,
  \"websocketSupport\": true,
  \"captainDefinitionRelativeFilePath\": \"./captain-definition\",
  \"description\": \"Son of Anton by Mahmoud Aglan\"
}" \
    "${CAPROVER_URL}/api/v2/user/apps/appDefinitions/update")

CONFIG_STATUS=$(echo "$CONFIG_RESP" | jq -r '.status')
if [[ "$CONFIG_STATUS" == "100" ]]; then
    ok "Environment variables set (8 vars)"
    ok "Persistent volume: ${APP_NAME}-data -> /data"
    ok "Container port: 80, WebSocket: enabled"
else
    echo "$CONFIG_RESP" | jq .
    die "Config failed: $(echo "$CONFIG_RESP" | jq -r '.description')"
fi

# ── Clone + tar ────────────────────────────────────
step "Clone repo & build deploy package"

git clone --depth 1 "http://gitlab.caprover.al-arcade.com/root/son-of-anton.git" "$WORK_DIR/repo" 2>&1 | while read -r l; do info "$l"; done
ok "Cloned"

cd "$WORK_DIR/repo"
tar -cf "$WORK_DIR/deploy.tar" \
    --exclude='.git' \
    --exclude='node_modules' \
    --exclude='__pycache__' \
    --exclude='*.pyc' \
    --exclude='.env' \
    --exclude='deploy.sh' \
    --exclude='soadeploy.sh' \
    --exclude='fix-deploy.sh' \
    .
cd /tmp

TAR_SIZE=$(du -h "$WORK_DIR/deploy.tar" | cut -f1)
ok "Deploy package: ${TAR_SIZE}"

# ── Deploy ─────────────────────────────────────────
step "Deploy to CapRover (this takes 5-10 min)"

echo -e "  ${YELLOW}Building Docker image: React frontend + Python backend + ChromaDB${NC}"
echo -e "  ${YELLOW}First build is slow. Be patient...${NC}"
echo ""

DEPLOY_RESP=$(curl -s --max-time 900 \
    -X POST \
    -H "x-captain-auth: ${CAPTAIN_TOKEN}" \
    -F "sourceFile=@${WORK_DIR}/deploy.tar" \
    "${CAPROVER_URL}/api/v2/user/apps/appData/${APP_NAME}")

DEPLOY_STATUS=$(echo "$DEPLOY_RESP" | jq -r '.status')
if [[ "$DEPLOY_STATUS" == "100" ]]; then
    ok "DEPLOY SUCCESSFUL!"
else
    DEPLOY_DESC=$(echo "$DEPLOY_RESP" | jq -r '.description')
    echo ""
    fail "Deploy response: ${DEPLOY_DESC}"
    echo ""
    warn "Check build logs: CapRover Dashboard > ${APP_NAME} > Deployment"
    warn "Or run: docker service logs srv-captain--${APP_NAME} --tail 200"
    echo ""
    echo -e "  ${YELLOW}Continue with HTTPS setup anyway? (y/n)${NC}"
    read -r choice
    [[ "$choice" == "y" || "$choice" == "Y" ]] || die "Stopped."
fi

# ── Wait for container ─────────────────────────────
step "Waiting for container to start"
for i in $(seq 20 -1 1); do
    printf "\r  ⏳ %2ds " "$i"
    sleep 1
done
printf "\r                \r"
ok "Wait complete"

# ── HTTPS ──────────────────────────────────────────
step "Enable HTTPS"

SSL_RESP=$(curl -s --max-time 60 \
    -X POST \
    -H "Content-Type: application/json" \
    -H "x-captain-auth: ${CAPTAIN_TOKEN}" \
    -d "{\"appName\":\"${APP_NAME}\"}" \
    "${CAPROVER_URL}/api/v2/user/apps/appDefinitions/enablebasedomainssl")

SSL_STATUS=$(echo "$SSL_RESP" | jq -r '.status')
if [[ "$SSL_STATUS" == "100" ]]; then
    ok "HTTPS certificate issued"

    # Force SSL
    FORCE_RESP=$(curl -s -X POST \
        -H "Content-Type: application/json" \
        -H "x-captain-auth: ${CAPTAIN_TOKEN}" \
        -d "{
      \"appName\": \"${APP_NAME}\",
      \"instanceCount\": 1,
      \"envVars\": [
        {\"key\":\"BEDROCK_API_KEY\",\"value\":\"${BEDROCK_API_KEY}\"},
        {\"key\":\"JWT_SECRET\",\"value\":\"${JWT_SECRET}\"},
        {\"key\":\"SUPERADMIN_PASSWORD\",\"value\":\"${SUPERADMIN_PASSWORD}\"},
        {\"key\":\"AWS_REGION\",\"value\":\"${AWS_REGION}\"},
        {\"key\":\"PRIMARY_MODEL\",\"value\":\"${PRIMARY_MODEL}\"},
        {\"key\":\"FAST_MODEL\",\"value\":\"${FAST_MODEL}\"},
        {\"key\":\"DEFAULT_QUOTA\",\"value\":\"${DEFAULT_QUOTA}\"},
        {\"key\":\"MAX_UPLOAD_MB\",\"value\":\"${MAX_UPLOAD_MB}\"}
      ],
      \"volumes\": [{\"containerPath\":\"/data\",\"volumeName\":\"${APP_NAME}-data\"}],
      \"ports\": [],
      \"containerHttpPort\": 80,
      \"notExposeAsWebApp\": false,
      \"forceSsl\": true,
      \"websocketSupport\": true,
      \"captainDefinitionRelativeFilePath\": \"./captain-definition\",
      \"description\": \"Son of Anton by Mahmoud Aglan\"
    }" \
        "${CAPROVER_URL}/api/v2/user/apps/appDefinitions/update")

    FORCE_STATUS=$(echo "$FORCE_RESP" | jq -r '.status')
    [[ "$FORCE_STATUS" == "100" ]] && ok "Force HTTPS enabled" || warn "Force-HTTPS failed (HTTPS still works)"
else
    SSL_DESC=$(echo "$SSL_RESP" | jq -r '.description')
    warn "HTTPS skipped: ${SSL_DESC}"
    warn "Enable manually from CapRover dashboard later"
fi

# ── Detect URL ─────────────────────────────────────
step "Detect App URL"

SYS_RESP=$(curl -s -H "x-captain-auth: ${CAPTAIN_TOKEN}" "${CAPROVER_URL}/api/v2/user/system/info")
ROOT_DOMAIN=$(echo "$SYS_RESP" | jq -r '.data.rootDomain // empty')

if [[ -n "$ROOT_DOMAIN" ]]; then
    APP_URL="https://${APP_NAME}.${ROOT_DOMAIN}"
    ok "URL: ${APP_URL}"
else
    APP_URL="https://${APP_NAME}.YOUR-DOMAIN.com"
    warn "Could not detect domain — check CapRover dashboard"
fi

# ── Save credentials ──────────────────────────────
CRED_FILE="$HOME/son-of-anton-credentials.txt"
cat > "$CRED_FILE" <<EOF
═══════════════════════════════════════════════
  SON OF ANTON — Credentials
  Generated: $(date)
═══════════════════════════════════════════════

URL:              ${APP_URL}
Username:         superadmin
Password:         ${SUPERADMIN_PASSWORD}

JWT_SECRET:       ${JWT_SECRET}
BEDROCK_API_KEY:  ${BEDROCK_API_KEY}

DO NOT SHARE THIS FILE.
═══════════════════════════════════════════════
EOF
chmod 600 "$CRED_FILE"
ok "Credentials saved: ${CRED_FILE}"

# ── Done! ──────────────────────────────────────────
echo ""
echo ""
echo -e "${GREEN}  ╔══════════════════════════════════════════════════╗${NC}"
echo -e "${GREEN}  ║                                                  ║${NC}"
echo -e "${GREEN}  ║    🔥  SON OF ANTON IS LIVE!  🔥                ║${NC}"
echo -e "${GREEN}  ║                                                  ║${NC}"
echo -e "${GREEN}  ╚══════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "  ${WHITE}${BOLD}URL:       ${CYAN}${APP_URL}${NC}"
echo -e "  ${WHITE}${BOLD}Username:  ${CYAN}superadmin${NC}"
echo -e "  ${WHITE}${BOLD}Password:  ${CYAN}${SUPERADMIN_PASSWORD}${NC}"
echo ""
echo -e "  ${WHITE}Creds file:  ${YELLOW}cat ~/son-of-anton-credentials.txt${NC}"
echo -e "  ${WHITE}Build logs:  ${YELLOW}docker service logs srv-captain--${APP_NAME} --tail 100${NC}"
echo ""
echo -e "  ${MAGENTA}Created by Mahmoud Aglan — AL-Arcade${NC}"
echo ""
