#!/usr/bin/env bash
set -u
# ============================================================
#  Whisper 本地语音转文字 一键脚本（macOS / Linux / WSL）
#  公开源码，欢迎审查 —— 不放心可先复制给 AI 判断
#  本主题本地工具无需 API Key
# ============================================================

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"; }

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
}

install_ffmpeg_domestic() {
  # 方案1：apt（Debian/Ubuntu/WSL）
  if command -v apt-get >/dev/null 2>&1; then
    info "使用 apt 安装 ffmpeg..."
    if sudo apt-get update -qq && sudo apt-get install -y -qq ffmpeg 2>/dev/null; then
      return 0
    fi
  fi
  # 方案2：dnf（Fedora/RHEL）
  if command -v dnf >/dev/null 2>&1; then
    info "使用 dnf 安装 ffmpeg..."
    if sudo dnf install -y ffmpeg 2>/dev/null; then
      return 0
    fi
  fi
  # 方案3：yum（CentOS 7 等老版本）
  if command -v yum >/dev/null 2>&1; then
    info "使用 yum 安装 ffmpeg..."
    if sudo yum install -y epel-release ffmpeg 2>/dev/null; then
      return 0
    fi
  fi
  return 1
}

install_ffmpeg_overseas() {
  if command -v apt-get >/dev/null 2>&1; then
    sudo apt-get update -qq && sudo apt-get install -y -qq ffmpeg
    return $?
  fi
  if command -v brew >/dev/null 2>&1; then
    brew install ffmpeg
    return $?
  fi
  if command -v dnf >/dev/null 2>&1; then
    sudo dnf install -y ffmpeg
    return $?
  fi
  if command -v yum >/dev/null 2>&1; then
    sudo yum install -y epel-release ffmpeg
    return $?
  fi
  return 1
}

ensure_ffmpeg() {
  step "检查 ffmpeg..."
  if command -v ffmpeg >/dev/null 2>&1; then
    info "ffmpeg 已安装：$(ffmpeg -version 2>&1 | head -1)"
    return 0
  fi
  warn "未检测到 ffmpeg，正在安装..."
  local NET="$1"
  if [ "$NET" = "domestic" ]; then
    if install_ffmpeg_domestic; then
      info "ffmpeg 安装成功"
      return 0
    fi
  else
    if install_ffmpeg_overseas; then
      info "ffmpeg 安装成功"
      return 0
    fi
  fi
  error "所有源安装 ffmpeg 均失败。"
  echo "  · Debian/Ubuntu/WSL：手动执行 sudo apt-get install ffmpeg"
  echo "  · macOS：手动执行 brew install ffmpeg"
  echo "  · Fedora/RHEL：手动执行 sudo dnf install ffmpeg"
  echo "  · CentOS：手动执行 sudo yum install epel-release ffmpeg"
  echo "  · Windows：请移步 https://ffmpeg.org/download.html 下载预编译包"
  return 1
}

check_python() {
  step "检查 Python 3..."
  local found=""
  for p in python3.11 python3.10 python3.9 python3.8 python3; do
    if "$p" --version 2>&1 | grep -qE "^Python 3\.[89]|^Python 3\.1[01]"; then
      found="$p"; break
    fi
    # catch 3.12+
    if "$p" --version 2>&1 | grep -qE "^Python 3\.[0-9][0-9]"; then
      found="$p"; break
    fi
  done
  if [ -n "$found" ]; then
    PY="$found"; info "找到 $PY：$($PY --version 2>&1)"; return 0
  fi
  error "需要 Python 3.8+，未找到。请先安装：https://www.python.org/downloads/"
  return 1
}

install_whisper() {
  local net="$1"
  step "安装 openai-whisper..."

  local pypi_arg=""
  if [ "$net" = "domestic" ]; then
    pypi_arg="-i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn"
  fi

  # 主源尝试
  if eval "$PY -m pip install -U openai-whisper $pypi_arg --timeout 120" >/dev/null 2>&1; then
    info "openai-whisper 安装成功（主源）"
    return 0
  fi

  warn "主源失败，回退备用源..."

  # 备用源：阿里云
  if [ "$net" = "domestic" ]; then
    if "$PY" -m pip install -U openai-whisper \
       -i https://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com \
       --timeout 120 >/dev/null 2>&1; then
      info "openai-whisper 安装成功（阿里云镜像）"
      return 0
    fi
  fi

  # 最终回退：官方源
  if "$PY" -m pip install -U openai-whisper --timeout 120 >/dev/null 2>&1; then
    info "openai-whisper 安装成功（官方源）"
    return 0
  fi

  error "openai-whisper 安装失败。请手动尝试："
  echo "  · 国内：pip install -U openai-whisper -i https://pypi.tuna.tsinghua.edu.cn/simple"
  echo "  · 海外：pip install -U openai-whisper"
  echo "  · 如遇 torch 依赖问题，请先安装 torch：pip install torch torchaudio"
  return 1
}

write_usage_template() {
  step "生成转写使用模板..."

  cat > whisper-usage.sh << 'USAGE'
#!/usr/bin/env bash
# Whisper 转写模板（替换为你自己的文件名）
# 用法：chmod +x whisper-usage.sh && ./whisper-usage.sh your-file.mp3

TARGET="${1:-meeting.mp3}"
MODEL="${2:-small}"   # tiny | base | small | medium | large-v3
LANGUAGE="${3:-zh}"   # zh | en | ja | ko ...

echo "转写中：$TARGET（模型=$MODEL，语言=$LANGUAGE）..."
whisper "$TARGET" --model "$MODEL" --language "$LANGUAGE" --output_format all

echo ""
echo "已完成！输出文件："
ls -lh "${TARGET%.*}".{txt,vtt,srt,tsv,json} 2>/dev/null || echo "（无输出文件，请检查上面报错）"
USAGE

  chmod +x whisper-usage.sh
  info "已生成 whisper-usage.sh（Usage: ./whisper-usage.sh <audio-file> [model] [language]）"
}

main() {
  echo "============================================"
  echo "  Whisper 本地语音转文字 一键脚本"
  echo "  适用于 macOS / Linux / WSL"
  echo "============================================"
  echo ""

  local NET
  NET=$(detect_network)

  ensure_ffmpeg "$NET" || exit 1
  check_python || exit 1
  install_whisper "$NET" || exit 1

  write_usage_template

  # 验证安装
  step "验证安装..."
  if command -v whisper >/dev/null 2>&1; then
    info "Whisper 版本：$(whisper --help 2>&1 | head -1)"
  else
    warn "whisper 命令不在 PATH 中，可能需要重新打开终端"
  fi

  echo ""
  echo "============================================"
  info "全部完成！"
  echo ""
  echo "快速上手："
  echo "  whisper your-audio.mp3 --model tiny --language zh"
  echo "  whisper your-audio.mp3 --model small --language zh --output_format srt"
  echo ""
  echo "一键转写模板：./whisper-usage.sh"
  echo ""
  echo "想省事？云端 OpenAI 兼容 API（如 https://cloudzone-api.cyou/）"
  echo "  90+ 模型、按量计费、国内直连，新手注册有优惠"
  echo "============================================"
}

main "$@"
