# ============================================================
# INQUIRY_KIT v3.0.4 一键环境装机脚本（Windows / PowerShell）
# ============================================================
# 适用：客户已安装 Accio Work 的场景
# 由 Accio Work 调用执行，全程无人工干预
# ============================================================

$ErrorActionPreference = "Stop"

# 1. 定位工具包根目录
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$KitDir = Split-Path -Parent $ScriptDir
Set-Location $KitDir

Write-Host "================================================"
Write-Host "📦 INQUIRY_KIT v3.0.4 一键装机"
Write-Host "📂 工作目录: $KitDir"
Write-Host "================================================"
Write-Host ""

# 2. 定位 Python（Windows 用 py launcher 或 PATH 上的 python）
Write-Host "🔍 [1/5] 检测 Python..."
$PyBin = $null
$candidates = @("py", "python", "python3")
foreach ($c in $candidates) {
    try {
        $v = & $c --version 2>&1
        if ($LASTEXITCODE -eq 0) { $PyBin = $c; break }
    } catch {}
}
if (-not $PyBin) {
    Write-Host "❌ 找不到 Python，请先安装：https://www.python.org/downloads/" -ForegroundColor Red
    Write-Host "   安装时记得勾选 'Add Python to PATH'"
    exit 1
}
Write-Host "    使用解释器: $PyBin"
& $PyBin --version
Write-Host ""

# 3. 创建/复用 venv
Write-Host "🏗  [2/5] 准备虚拟环境 .venv..."
if (Test-Path ".venv") {
    Write-Host "    .venv 已存在，跳过创建"
} else {
    & $PyBin -m venv .venv
    Write-Host "    ✅ 已创建 .venv"
}
$VenvPy = Join-Path $KitDir ".venv\Scripts\python.exe"
$VenvPip = Join-Path $KitDir ".venv\Scripts\pip.exe"
Write-Host ""

# 4. 装 playwright
Write-Host "📦 [3/5] 安装 playwright（如未装）..."
$hasPw = $false
try { & $VenvPy -c "import playwright" 2>&1 | Out-Null; if ($LASTEXITCODE -eq 0) { $hasPw = $true } } catch {}
if ($hasPw) {
    Write-Host "    playwright 已就绪，跳过"
} else {
    & $VenvPip install --quiet --upgrade pip
    & $VenvPip install --quiet playwright
    Write-Host "    ✅ playwright 安装完成"
}
Write-Host ""

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

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