#!/usr/bin/env bash
set -u
# ============================================================
#  Dify 零代码 AI 应用开发 一键脚本（macOS / Linux / WSL）
#  公开源码，欢迎审查 —— 不放心可先复制给 AI 判断
#  默认配置：云间 API 中转站（https://cloudzone-api.cyou/）
#  前置要求：Docker + Docker Compose；CPU ≥ 2 核，内存 ≥ 4GB
# ============================================================

GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; CYAN='\033[0;36m'; NC='\033[0m'
info()  { echo -e "${GREEN}[INFO]${NC} $1"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; }
step()  { echo -e "${CYAN}[STEP]${NC} $1"; }

CLOUDZONE_URL="https://cloudzone-api.cyou"

detect_network() {
  step "检测网络环境（国内 / 国外）..."
  if curl -fsI --max-time 5 "https://claude.ai" >/dev/null 2>&1; then
    info "可直连 claude.ai，判定为海外网络"
    echo "overseas"
  else
    warn "无法直连 claude.ai，判定为国内网络环境（将自动切换国内镜像）"
    echo "domestic"
  fi
}

check_docker() {
  step "检查 Docker 与 Docker Compose..."
  if ! command -v docker >/dev/null 2>&1; then
    error "未找到 docker。请先安装 Docker："
    echo "  · Windows：安装 Docker Desktop（启用 WSL2 后端）https://www.docker.com/products/docker-desktop/"
    echo "  · macOS：安装 Docker Desktop https://www.docker.com/products/docker-desktop/"
    echo "  · Linux：https://docs.docker.com/engine/install/ 按发行版安装"
    return 1
  fi
  if ! docker compose version >/dev/null 2>&1; then
    error "docker compose 不可用（需要 Compose v2）。请升级 Docker 后重试。"
    return 1
  fi
  info "Docker：$(docker --version 2>&1)；Compose：$(docker compose version 2>&1)"
  return 0
}

clone_dify() {
  local net="$1"
  if [ -d "dify/docker" ]; then
    info "检测到 dify/ 目录已存在，跳过 clone"
    return 0
  fi
  step "克隆 Dify 仓库（约 1-3 分钟，视网络而定）..."
  local repo="https://github.com/langgenius/dify.git"
  if [ "$net" = "domestic" ]; then
    repo="https://ghfast.top/https://github.com/langgenius/dify.git"
  fi

  if git clone --depth 1 "$repo" 2>/dev/null; then
    info "clone 成功"
    return 0
  fi
  warn "主源失败，回退备用源..."
  if git clone --depth 1 "https://ghfast.top/https://github.com/langgenius/dify.git" 2>/dev/null; then
    info "备用源 clone 成功"
    return 0
  fi
  error "clone 失败。请手动执行：git clone https://ghfast.top/https://github.com/langgenius/dify.git 后重新运行本脚本。"
  return 1
}

start_dify() {
  step "启动 Dify 全部服务（首次拉镜像可能耗时 5-15 分钟）..."
  cd dify/docker || return 1

  if [ ! -f ".env" ]; then
    info "创建 .env（复制官方模板；.env 是 Dify 的配置文件，可后续修改端口等）"
    cp .env.example .env
  fi

  if docker compose up -d; then
    info "容器已启动"
  else
    warn "首次启动失败，等待 10 秒后重试一次..."
    sleep 10
    if ! docker compose up -d; then
      error "docker compose up 失败。请执行 cd dify/docker && docker compose up 查看详细报错。"
      return 1
    fi
  fi

  step "等待服务就绪（检查容器状态）..."
  docker compose ps
  return 0
}

configure_hint() {
  step "模型 Key 提示（部署完成后在 Dify 里配置模型）..."
  echo ""
  echo "Dify 部署好后需要接入大模型 Key 才能创建应用。默认推荐云间 API 中转站："
  echo "  · OpenAI 兼容格式，Dify 模型供应商直接填 Base URL 即可"
  echo "  · 香港节点国内直连，Claude/GPT/DeepSeek/GLM 等 90+ 模型一把 Key 全管"
  echo ""
  echo "是否现在打开注册页获取 Key？"
  echo "  Y - 立即跳转至 ${CLOUDZONE_URL}"
  echo "  N - 直接跳过（用我自己的 Key）"
  read -r -p "请选择 [Y/N]: " choice
  if [ "${choice:-N}" = "Y" ] || [ "${choice:-N}" = "y" ]; then
    if command -v xdg-open >/dev/null 2>&1; then
      xdg-open "$CLOUDZONE_URL" >/dev/null 2>&1
    elif command -v open >/dev/null 2>&1; then
      open "$CLOUDZONE_URL" >/dev/null 2>&1
    else
      warn "无法自动打开浏览器，请手动访问：$CLOUDZONE_URL"
    fi
    echo "拿到 Key 后，到 Dify「设置 → 模型供应商」填入："
    echo "  API Base URL : https://cloudzone-api.cyou/v1（以控制台显示为准）"
    echo "  API Key      : 刚复制的 sk-... Key"
    echo ""
  else
    info "已跳过。回到 Dify 设置页添加你自己的模型供应商即可。"
  fi
}

main() {
  echo "============================================"
  echo "  Dify 零代码 AI 应用开发 一键脚本"
  echo "  适用于 macOS / Linux / WSL"
  echo "  默认接入：云间 API 中转站"
  echo "============================================"
  echo ""

  local NET
  NET=$(detect_network)

  if ! check_docker; then
    error "Docker 环境不满足，脚本终止。请先安装 Docker（见上方指引）后重跑。"
    exit 1
  fi

  if ! clone_dify "$NET"; then
    exit 1
  fi

  if ! start_dify; then
    error "Dify 启动失败，脚本终止。请按上方提示手动排查。"
    exit 1
  fi

  configure_hint

  echo ""
  echo "============================================"
  info "全部完成！"
  echo "  首次部署：浏览器打开 http://localhost/install 初始化管理员"
  echo "  日常登录：http://localhost （云服务器请换成你的 IP，并放行 80 端口）"
  echo "  模型配置：登录后右上角头像 → 设置 → 模型供应商"
  echo "============================================"
}

main "$@"