#!/bin/bash
# ============================================================
# now-playing bridge.sh
# 功能 1: 安装依赖（media-control）
# 功能 2: 获取系统当前播放信息，输出 JSON 到 now-playing.json
#
# 用法:
#   bash bridge.sh install   # 仅安装依赖
#   bash bridge.sh uninstall # 卸载安装的依赖
#   bash bridge.sh           # 获取播放信息（由 LaunchAgent 定期调用）
# ============================================================

set -euo pipefail

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

# ---------- 常量 ----------
MEDIA_CONTROL_CMD="media-control"
HOMEBREW_PATHS=("/opt/homebrew/bin" "/usr/local/bin")
CACHE_DIR="${SCRIPT_DIR}/cache"
DATA_FILE="${CACHE_DIR}/now-playing.json"

# ---------- 工具函数 ----------

# 查找 media-control 可执行文件路径
find_media_control() {
    # 先检查 PATH 中是否存在
    if command -v "$MEDIA_CONTROL_CMD" >/dev/null 2>&1; then
        command -v "$MEDIA_CONTROL_CMD"
        return 0
    fi
    # 检查常见 Homebrew 安装路径
    for dir in "${HOMEBREW_PATHS[@]}"; do
        if [[ -x "$dir/$MEDIA_CONTROL_CMD" ]]; then
            echo "$dir/$MEDIA_CONTROL_CMD"
            return 0
        fi
    done
    return 1
}

# 查找 Homebrew 可执行文件路径
find_brew() {
    if command -v brew >/dev/null 2>&1; then
        command -v brew
        return 0
    fi
    for dir in "${HOMEBREW_PATHS[@]}"; do
        if [[ -x "$dir/brew" ]]; then
            echo "$dir/brew"
            return 0
        fi
    done
    return 1
}

# ---------- 安装依赖 ----------
do_install() {
    echo "🔍 检查依赖..." >&2

    # 1. 检查操作系统
    if [[ "$(uname -s)" != "Darwin" ]]; then
        echo "❌ 仅支持 macOS（当前：$(uname -s)）" >&2
        exit 1
    fi

    # 2. 检查 media-control 是否已安装
    if MC_PATH=$(find_media_control); then
        echo "✅ media-control 已安装: $MC_PATH" >&2
        "$MC_PATH" --version 2>&1 || true
        echo "" >&2
        echo "✅ 所有依赖已就绪，无需额外安装。" >&2
        return 0
    fi

    # 3. 需要安装 media-control，先找到 Homebrew
    echo "📦 media-control 未安装，开始安装..." >&2

    BREW_PATH=""
    if BREW_PATH=$(find_brew); then
        echo "✅ 检测到 Homebrew: $BREW_PATH" >&2
    else
        echo "⚠️  未检测到 Homebrew，尝试自动安装..." >&2
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
        # 安装后重新查找
        if BREW_PATH=$(find_brew); then
            echo "✅ Homebrew 安装成功: $BREW_PATH" >&2
        else
            echo "❌ Homebrew 安装失败，请手动安装: https://brew.sh" >&2
            exit 1
        fi
    fi

    # 4. 使用 Homebrew 安装 media-control
    echo "📦 正在通过 Homebrew 安装 media-control..." >&2
    "$BREW_PATH" install media-control

    # 5. 验证安装
    if MC_PATH=$(find_media_control); then
        echo "" >&2
        echo "✅ media-control 安装成功: $MC_PATH" >&2
        "$MC_PATH" --version 2>&1 || true
    else
        echo "❌ media-control 安装失败，请手动执行: brew install media-control" >&2
        exit 1
    fi

    echo "" >&2
    echo "✅ 所有依赖安装完成！插件现在可以正常使用了。" >&2
}

# ---------- 卸载依赖 ----------
do_uninstall() {
    echo "🗑️ 准备卸载..." >&2

    if [[ "$(uname -s)" != "Darwin" ]]; then
        echo "❌ 仅支持 macOS（当前：$(uname -s)）" >&2
        exit 1
    fi

    # 1. 卸载 LaunchAgent
    PLIST_PATH="$HOME/Library/LaunchAgents/com.assist.nowplaying.plist"
    if [[ -f "$PLIST_PATH" ]]; then
        echo "🔄 正在卸载 LaunchAgent..." >&2
        launchctl unload "$PLIST_PATH" 2>/dev/null || true
        rm -f "$PLIST_PATH"
        echo "✅ LaunchAgent 卸载完成！" >&2
    fi

    # 2. 卸载 media-control
    BREW_PATH=""
    if BREW_PATH=$(find_brew); then
        if "$BREW_PATH" list media-control &>/dev/null; then
            echo "📦 正在通过 Homebrew 卸载 media-control..." >&2
            "$BREW_PATH" uninstall media-control
            echo "✅ media-control 卸载完成！" >&2
        else
            echo "✅ media-control 未安装或已通过 Homebrew 卸载。" >&2
        fi
    else
        echo "⚠️ 未检测到 Homebrew，无法自动卸载 media-control！" >&2
    fi
}

# ---------- 获取播放信息 ----------
do_get_playing() {
    # 确保 cache 目录存在
    mkdir -p "$CACHE_DIR"
    MC_PATH=""
    if MC_PATH=$(find_media_control); then
        "$MC_PATH" get -h > "$DATA_FILE" 2>/dev/null
    fi
    exit 0
}

# ---------- 入口 ----------
case "${1:-}" in
    install)
        do_install
        ;;
    uninstall)
        do_uninstall
        ;;
    *)
        do_get_playing
        ;;
esac
