#!/bin/bash
# globard-find —— 搜音视频，能听能看能下
# 换搜索源：改 ~/.config/globard-find.conf，不用动这个脚本
#
#   globard-find 周深              搜视频
#   globard-find -m 周深           只搜音乐区
#   globard-find -n 15 周深        要 15 条
#   globard-find -i 周深           搜完弹菜单，方向键挑
#   globard-find -p 2              只听声音
#   globard-find -P 2              看画面
#   globard-find -d 2              下载到音乐目录
#   globard-find -s 2              看详情
#   globard-find -l                再看一遍上次列表

set -u

CACHE="$HOME/.cache/globard-find"
mkdir -p "$CACHE"
LAST="$CACHE/last.json"
CK="$CACHE/cookie.txt"

# ===== 读配置（读不到就用 B站 的默认值）=====
CONF="$HOME/.config/globard-find.conf"
[ -f "$CONF" ] && . "$CONF"

: "${SEARCH_API:=https://api.bilibili.com/x/web-interface/search/type?search_type=video&page=1}"
: "${MUSIC_PARAM:=&tids=3}"
: "${RESULT_PATH:=data.result}"
: "${FIELD_ID:=bvid}"
: "${FIELD_TITLE:=title}"
: "${FIELD_DURATION:=duration}"
: "${FIELD_AUTHOR:=author}"
: "${OK_CODE:=0}"
: "${VIDEO_URL:=https://www.bilibili.com/video/%s}"
: "${COOKIE_URL:=https://www.bilibili.com}"
: "${REFERER:=https://search.bilibili.com}"
: "${UA:=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36}"
: "${DEFAULT_NUM:=10}"
: "${DOWNLOAD_DIR:=$HOME/音乐}"

die() { echo "错误：$*"; exit 1; }

ensure_cookie() {
  [ -z "$COOKIE_URL" ] && return 0
  if [ ! -s "$CK" ] || [ -n "$(find "$CK" -mmin +600 2>/dev/null)" ]; then
    curl -sS --max-time 20 -c "$CK" -o /dev/null \
      -H "User-Agent: $UA" \
      -H "Accept: text/html,application/xhtml+xml" \
      -H "Accept-Language: zh-CN,zh;q=0.9" \
      "$COOKIE_URL" 2>/dev/null
  fi
}

try_fetch() {
  local url="$1"
  ensure_cookie
  curl -sS --max-time 25 -b "$CK" -c "$CK" \
    -H "User-Agent: $UA" \
    -H "Referer: $REFERER" \
    -H "Accept: application/json, text/plain, */*" \
    -H "Accept-Language: zh-CN,zh;q=0.9" \
    "$url" -o "$CACHE/raw.json" 2>/dev/null
}

fetch() {
  local kw="$1" num="$2" only_music="$3"
  local url
  url="$SEARCH_API"
  url="$url&keyword=$(python3 -c "import urllib.parse,sys; print(urllib.parse.quote(sys.argv[1]))" "$kw")"
  [ "$only_music" = "1" ] && url="$url$MUSIC_PARAM"

  try_fetch "$url"
  # 被反爬拦了就换 cookie 再来一次
  if ! head -c 20 "$CACHE/raw.json" 2>/dev/null | grep -q '{'; then
    rm -f "$CK"
    try_fetch "$url"
  fi

  python3 - "$CACHE/raw.json" "$LAST" "$num" \
           "$RESULT_PATH" "$FIELD_ID" "$FIELD_TITLE" "$FIELD_DURATION" "$FIELD_AUTHOR" "$OK_CODE" <<'PY'
import json, sys, re

raw, out, num = sys.argv[1], sys.argv[2], int(sys.argv[3])
rpath, fid, ftitle, fdur, fauthor, okcode = sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7], sys.argv[8], sys.argv[9]

def dig(d, path):
    for k in path.split("."):
        if not isinstance(d, dict):
            return None
        d = d.get(k)
    return d

try:
    d = json.load(open(raw, encoding="utf-8"))
except Exception:
    print("接口返回看不懂，可能被拦了，再试一次"); sys.exit(1)

if okcode != "":
    code = d.get("code")
    if code is not None and str(code) != okcode:
        print("接口说：%s" % d.get("message", "未知原因")); sys.exit(1)

res = dig(d, rpath)
if not isinstance(res, list):
    print("在 %s 里没找到结果列表，检查配置里的 RESULT_PATH" % rpath); sys.exit(1)

items = []
for r in res:
    if not isinstance(r, dict):
        continue
    rid = str(r.get(fid) or "")
    if not rid:
        continue
    t = re.sub(r"<[^>]+>", "", str(r.get(ftitle) or "")).strip()
    t = t.replace("&quot;", '"').replace("&amp;", "&").replace("&#39;", "'")
    items.append({
        "id": rid,
        "title": t,
        "duration": str(r.get(fdur) or ""),
        "author": str(r.get(fauthor) or ""),
    })
    if len(items) >= num:
        break

if not items:
    print("没搜到，换个词"); sys.exit(1)

json.dump(items, open(out, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print("搜到 %d 条：" % len(items))
for i, x in enumerate(items, 1):
    print("%d. %s [%s] %s" % (i, x["title"], x["duration"] or "时长未知", x["author"]))
PY
}

get_field() {
  local n="$1" f="$2"
  [ -f "$LAST" ] || die "还没搜过东西，先 globard-find 关键词"
  python3 - "$LAST" "$n" "$f" <<'PY'
import json, sys
path, n, f = sys.argv[1], int(sys.argv[2]), sys.argv[3]
d = json.load(open(path, encoding="utf-8"))
if n < 1 or n > len(d):
    sys.exit(1)
print(d[n-1].get(f, ""))
PY
}

show_list() {
  [ -f "$LAST" ] || die "还没有搜过东西"
  python3 - "$LAST" <<'PY'
import json, sys
d = json.load(open(sys.argv[1], encoding="utf-8"))
print("共 %d 条：" % len(d))
for i, x in enumerate(d, 1):
    print("%d. %s [%s] %s" % (i, x["title"], x["duration"] or "时长未知", x["author"]))
PY
}

do_play() {
  local n="$1" want_video="$2"
  local rid title url sock
  rid=$(get_field "$n" id) || die "没有第 $n 条"
  title=$(get_field "$n" title)
  [ -z "$rid" ] && die "没有第 $n 条"
  url=$(printf "$VIDEO_URL" "$rid")
  sock="/tmp/globard-mpv.sock"

  # 上一次的还在就先停掉
  if [ -S "$sock" ]; then
    pkill -u "$(id -u)" -f "mpv.*globard-mpv.sock" 2>/dev/null
    sleep 1
    rm -f "$sock"
  fi

  if [ "$want_video" = "1" ]; then
    echo "看第 $n 条：$title"
    mpv --title="$title" \
        --input-ipc-server="$sock" \
        --ytdl-format="bestvideo[height<=720]+bestaudio/best[height<=720]/best" \
        --really-quiet --osd-level=0 \
        "$url" >/dev/null 2>&1 &
  else
    echo "听第 $n 条：$title"
    mpv --no-video --title="$title" \
        --input-ipc-server="$sock" \
        --ytdl-format="bestaudio/best" \
        --really-quiet --osd-level=0 \
        "$url" >/dev/null 2>&1 &
  fi
  echo $! > /tmp/globard-mpv.pid
  sleep 2
  echo "在后台放了。暂停 globard y，快退 globard e，快进 globard r，停 globard q"
}

do_download() {
  local n="$1"
  local rid title url outdir
  rid=$(get_field "$n" id) || die "没有第 $n 条"
  title=$(get_field "$n" title)
  url=$(printf "$VIDEO_URL" "$rid")
  outdir="$DOWNLOAD_DIR"
  mkdir -p "$outdir"
  echo "下载第 $n 条：$title"
  echo "存到：$outdir"
  yt-dlp -x --audio-format mp3 --audio-quality 0 \
    -o "$outdir/%(title)s.%(ext)s" --no-mtime --no-warnings \
    "$url" 2>&1 | tail -4
  echo "完成。最新三条："
  ls -t "$outdir" 2>/dev/null | head -3
}

do_menu() {
  local kw="$1" num="$2" only_music="$3"
  fetch "$kw" "$num" "$only_music" || die "搜索失败"
  [ -f "$LAST" ] || die "没有结果"

  local opts=()
  while IFS=$'\t' read -r idx label; do
    opts+=("$idx" "$label")
  done < <(python3 - "$LAST" <<'PY'
import json, sys
d = json.load(open(sys.argv[1], encoding="utf-8"))
for i, x in enumerate(d, 1):
    label = "%s [%s] %s" % (x["title"], x["duration"] or "?", x["author"])
    print("%d\t%s" % (i, label[:110]))
PY
)

  local pick
  pick=$(whiptail --title "挑一个" \
         --menu "方向键上下选，回车确认，Esc 取消" \
         22 100 12 "${opts[@]}" 3>&1 1>&2 2>&3) || { echo "取消了"; return 1; }

  echo
  echo "选了第 $pick 条。"
  local ans
  read -r -p "回车直接听 / 输入 v 看画面 / 输入 d 下载 / 输入 n 不放了： " ans
  case "${ans:-}" in
    v|V) do_play "$pick" 1 ;;
    d|D) do_download "$pick" ;;
    n|N) echo "好" ;;
    *)   do_play "$pick" 0 ;;
  esac
}

MODE="search"; NUM="$DEFAULT_NUM"; MUSIC=0
while [ $# -gt 0 ]; do
  case "$1" in
    -m) MUSIC=1; shift ;;
    -n) NUM="${2:-$DEFAULT_NUM}"; shift 2 ;;
    -i) MODE="menu"; shift ;;
    -p) MODE="play"; N="${2:-1}"; shift 2 ;;
    -P) MODE="video"; N="${2:-1}"; shift 2 ;;
    -d) MODE="download"; N="${2:-1}"; shift 2 ;;
    -l) MODE="list"; shift ;;
    -s) MODE="info"; N="${2:-1}"; shift 2 ;;
    -h|--help) sed -n '2,13p' "$0" | sed 's/^# //'; exit 0 ;;
    *) KW="$1"; shift ;;
  esac
done

case "$MODE" in
  play)     do_play "${N:-1}" 0 ;;
  video)    do_play "${N:-1}" 1 ;;
  download) do_download "${N:-1}" ;;
  list)     show_list ;;
  info)
    rid=$(get_field "${N:-1}" id) || die "没有第 ${N:-1} 条"
    echo "标题：$(get_field "${N:-1}" title)"
    echo "作者：$(get_field "${N:-1}" author)"
    echo "时长：$(get_field "${N:-1}" duration)"
    echo "编号：$rid"
    echo "地址：$(printf "$VIDEO_URL" "$rid")"
    ;;
  menu)
    [ -n "${KW:-}" ] || die "要搜什么？globard-find -i 关键词"
    do_menu "$KW" "$NUM" "$MUSIC"
    ;;
  search)
    [ -n "${KW:-}" ] || die "要搜什么？用法：globard-find 关键词"
    fetch "$KW" "$NUM" "$MUSIC" || die "搜索失败"
    echo
    echo "听：globard-find -p 编号    看：globard-find -P 编号"
    echo "下：globard-find -d 编号    菜单：globard-find -i 关键词"
    ;;
esac
