#!/bin/bash
# ============================================================
# INQUIRY_KIT v3.0.4 一键环境装机脚本（macOS / Linux）
# ============================================================
# 适用：客户已安装 Accio Work 的场景
# 由 Accio Work 调用执行，全程无人工干预
#
# 关键设计：
#   强制使用系统 /usr/bin/python3，绕开 Accio 嵌入式 Python
#   装 greenlet 时的 macOS Gatekeeper codesign 拒签问题
# ============================================================

set -e

# 1. 定位工具包根目录（脚本所在目录的父目录）
KIT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$KIT_DIR"

echo "================================================"
echo "📦 INQUIRY_KIT v3.0.4 一键装机"
echo "📂 工作目录: $KIT_DIR"
echo "================================================"
echo ""

# 2. 强制使用系统 Python（关键！）
echo "🔍 [1/5] 检测系统 Python..."
PYBIN="/usr/bin/python3"
if [ ! -x "$PYBIN" ]; then
    # Linux 兜底
    PYBIN="$(command -v python3 || true)"
    if [ -z "$PYBIN" ]; then
        echo "❌ 找不到系统 Python，请先安装："
        echo "   macOS: xcode-select --install"
        echo "   Linux: sudo apt install python3 python3-venv"
        exit 1
    fi
fi
echo "    使用解释器: $PYBIN"
"$PYBIN" --version
PY_MAJOR_MINOR=$("$PYBIN" -c "import sys; print(f'{sys.version_info[0]}.{sys.version_info[1]}')")
echo "    版本: Python $PY_MAJOR_MINOR"
echo ""

# 3. 创建/复用 venv
echo "🏗  [2/5] 准备虚拟环境 .venv..."
if [ -L ".venv" ] || [ -d ".venv" ]; then
    # 已存在（可能是软链或旧 venv），保留不动
    echo "    .venv 已存在，跳过创建"
    if [ -L ".venv" ]; then
        echo "    （注意：.venv 是软链，指向 $(readlink .venv)）"
    fi
else
    "$PYBIN" -m venv .venv
    echo "    ✅ 已创建 .venv"
fi
VENV_PY="$KIT_DIR/.venv/bin/python"
VENV_PIP="$KIT_DIR/.venv/bin/pip"
echo ""

# 4. 装 playwright
echo "📦 [3/5] 安装 playwright（如未装）..."
if "$VENV_PY" -c "import playwright" 2>/dev/null; then
    echo "    playwright 已就绪，跳过"
else
    "$VENV_PIP" install -q --upgrade pip
    "$VENV_PIP" install -q playwright
    echo "    ✅ playwright 安装完成"
fi
echo ""

# 5. 下载 Chromium
echo "🌐 [4/5] 下载 Chromium 浏览器内核（首次约 150MB，已装则跳过）..."
"$VENV_PY" -m playwright install chromium 2>&1 | tail -5
echo "    ✅ Chromium 就绪"
echo ""

# 6. 自检
echo "🧪 [5/5] 环境自检..."
"$VENV_PY" -c "
import sys, platform
from importlib.metadata import version as _v
import playwright  # noqa: F401
from playwright.sync_api import sync_playwright  # noqa: F401
print(f'    Python: {sys.version.split()[0]} @ {sys.executable}')
print(f'    Platform: {platform.system()} {platform.machine()}')
try:
    print(f'    Playwright: {_v(\"playwright\")}')
except Exception:
    print('    Playwright: (version unknown)')
print('    ✅ 全部模块可正常 import')
"
echo ""
echo "================================================"
echo "✅ 装机完成！下一步可以跑试抓："
echo ""
echo "  cd \"$KIT_DIR\""
echo "  ./.venv/bin/python -X utf8 scripts/run_scrape.py --mode trial-sample --sample-size 5"
echo ""
echo "================================================"
