#!/bin/bash

# ============================================
# 脚本配置
# ============================================
URL="${1:-http://127.0.0.1:18789}"   # 要导航的网页（默认本地控制台）
CHECK_INTERVAL=5                     # 每隔 5 秒检查一次 Chrome
MAX_WAIT=600                         # 最多等待 10 分钟（可调整）

# ============================================
# 检测操作系统
# ============================================
OS=$(uname -s)
case "$OS" in
    Darwin*) OS_TYPE="Mac" ;;
    Linux*) OS_TYPE="Linux" ;;
    CYGWIN*|MINGW*|MSYS*) OS_TYPE="Windows" ;;
    *) echo "Unsupported OS: $OS"; exit 1 ;;
esac

# ============================================
# 设置 Chrome 默认路径
# ============================================
case "$OS_TYPE" in
    Mac) CHROME="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" ;;
    Linux) CHROME="$(which google-chrome || which chromium-browser || echo "")" ;;
    Windows) CHROME="/mnt/c/Program Files/Google/Chrome/Application/chrome.exe" ;;
esac

# ============================================
# 检测 Chrome 是否存在
# ============================================
if [ -z "$CHROME" ] || [ ! -f "$CHROME" ]; then
    echo "Chrome not found on your system!"
    
    # 打开官方下载页面
    case "$OS_TYPE" in
        Mac) open "https://www.google.com/chrome/" ;;
        Linux) xdg-open "https://www.google.com/linux/chrome/" >/dev/null 2>&1 || echo "Please download Chrome from https://www.google.com/linux/chrome/" ;;
        Windows) powershell.exe -Command "Start-Process 'https://www.google.com/chrome/'" ;;
    esac

    echo "Please install Chrome. Waiting for installation..."
    
    # 开始轮询等待用户安装
    ELAPSED=0
    while [ ! -f "$CHROME" ]; do
        sleep $CHECK_INTERVAL
        ELAPSED=$((ELAPSED + CHECK_INTERVAL))
        if [ $ELAPSED -ge $MAX_WAIT ]; then
            echo "Timed out waiting for Chrome. Please install manually and rerun this script."
            exit 1
        fi
    done
    echo "Chrome installation detected!"
fi

# ============================================
# 打开目标 URL
# ============================================
echo "Opening URL: $URL ..."
case "$OS_TYPE" in
    Mac|Linux) "$CHROME" "$URL" ;;
    Windows) powershell.exe -Command "Start-Process '$CHROME' '$URL'" ;;
esac

echo "Done!"
