#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
DIST_DIR="$ROOT_DIR/dist"
PKG_DIR="$DIST_DIR/windows-client-package"
APP_NAME="PinterestAIOperator"
APP_VERSION="$(node -e "console.log(require(process.argv[1]).version)" "$ROOT_DIR/package.json" 2>/dev/null || echo "0.0.0")"
APP_DIR="$PKG_DIR/$APP_NAME"
APP_RES="$APP_DIR/app"
ZIP_PATH="$DIST_DIR/PinterestAIOperator-${APP_VERSION}-client-windows.zip"
LEGACY_ZIP_PATH="$DIST_DIR/PinterestAIOperator-client-windows.zip"
NODE_VERSION="${PINTEREST_AUTO_WINDOWS_NODE_VERSION:-20.18.1}"
NODE_DIST_NAME="node-v${NODE_VERSION}-win-x64"
NODE_ZIP_PATH="$DIST_DIR/${NODE_DIST_NAME}.zip"
NODE_RUNTIME_DIR="$APP_DIR/runtime/node"
BUNDLE_NODE="${PINTEREST_AUTO_BUNDLE_NODE:-true}"

mkdir -p "$DIST_DIR"
rm -rf "$PKG_DIR" "$ZIP_PATH" "$LEGACY_ZIP_PATH"
mkdir -p "$APP_RES"

rsync -a "$ROOT_DIR"/ "$APP_RES"/ \
  --exclude ".DS_Store" \
  --exclude ".env" \
  --exclude ".env.local" \
  --exclude ".next-dev/" \
  --exclude ".next-dev2/" \
  --exclude ".next-verify/" \
  --exclude ".next/cache/" \
  --exclude "data/db.json" \
  --exclude "license-keys/update-private.pem" \
  --exclude "/dist/" \
  --exclude "tsconfig.tsbuildinfo"

mkdir -p "$APP_RES/packaging"
node "$ROOT_DIR/scripts/write-default-db.mjs" "$APP_RES/packaging/default-db.json"

if [[ "$BUNDLE_NODE" != "false" ]]; then
  mkdir -p "$NODE_RUNTIME_DIR"
  if [[ ! -f "$NODE_ZIP_PATH" ]]; then
    echo "Downloading Node.js Windows runtime ${NODE_VERSION}..."
    curl -fL "https://nodejs.org/dist/v${NODE_VERSION}/${NODE_DIST_NAME}.zip" -o "$NODE_ZIP_PATH"
  fi
  TMP_NODE_DIR="$DIST_DIR/node-runtime-tmp"
  rm -rf "$TMP_NODE_DIR"
  mkdir -p "$TMP_NODE_DIR"
  unzip -q "$NODE_ZIP_PATH" -d "$TMP_NODE_DIR"
  rsync -a "$TMP_NODE_DIR/$NODE_DIST_NAME"/ "$NODE_RUNTIME_DIR"/
  rm -rf "$TMP_NODE_DIR"
fi

cat > "$APP_DIR/Run Server.cmd" <<'CMD'
@echo off
setlocal EnableExtensions

set "APP_DIR=%~dp0app"
set "DATA_DIR=%LOCALAPPDATA%\Pinterest AI Operator"
set "LOG_DIR=%DATA_DIR%\Logs"
if not exist "%LOG_DIR%" mkdir "%LOG_DIR%"

cd /d "%APP_DIR%"
set "NEXT_DIST_DIR=.next"
set "PINTEREST_AUTO_DATA_DIR=%DATA_DIR%"
set "PORT=%~1"
if "%PORT%"=="" set "PORT=3000"
set "NODE_EXE=%~dp0runtime\node\node.exe"
if not exist "%NODE_EXE%" set "NODE_EXE=node"

if exist "%DATA_DIR%\.env.local" (
  for /f "usebackq tokens=1,* delims==" %%A in ("%DATA_DIR%\.env.local") do (
    if not "%%A"=="" set "%%A=%%B"
  )
)

"%NODE_EXE%" node_modules\next\dist\bin\next start >> "%LOG_DIR%\pinterest-auto.log" 2>&1
CMD

cat > "$APP_DIR/Start Pinterest AI Operator.cmd" <<'CMD'
@echo off
setlocal EnableExtensions EnableDelayedExpansion

set "NO_PAUSE=%~1"
set "APP_DIR=%~dp0app"
set "DATA_DIR=%LOCALAPPDATA%\Pinterest AI Operator"
set "LOG_DIR=%DATA_DIR%\Logs"
if not exist "%LOG_DIR%" mkdir "%LOG_DIR%"

set "NODE_EXE=%~dp0runtime\node\node.exe"
if exist "%NODE_EXE%" goto node_ready
where node >nul 2>nul
if errorlevel 1 (
  echo.
  echo 未找到 Node.js。请确认安装包完整，或先安装 Node.js 20+：
  echo https://nodejs.org/
  echo.
  if /I not "%NO_PAUSE%"=="/silent" pause
  exit /b 1
)
set "NODE_EXE=node"
:node_ready

if not exist "%APP_DIR%\node_modules\next\dist\bin\next" (
  echo.
  echo 未找到依赖文件。请确认压缩包已完整解压，或运行 Repair Dependencies.cmd。
  echo.
  if /I not "%NO_PAUSE%"=="/silent" pause
  exit /b 1
)

if not exist "%DATA_DIR%\.env.local" (
  > "%DATA_DIR%\.env.local" echo PINTEREST_CLIENT_ID=
  >> "%DATA_DIR%\.env.local" echo PINTEREST_CLIENT_SECRET=
  >> "%DATA_DIR%\.env.local" echo PINTEREST_REDIRECT_URI=
  >> "%DATA_DIR%\.env.local" echo PINTEREST_ACCESS_TOKEN=
  >> "%DATA_DIR%\.env.local" echo OPENCLAW_SHARED_TOKEN=local-test-token
  >> "%DATA_DIR%\.env.local" echo PINTEREST_AUTO_LICENSE_SERVER_URL=
  >> "%DATA_DIR%\.env.local" echo PINTEREST_AUTO_REQUIRE_REMOTE_LICENSE=true
  >> "%DATA_DIR%\.env.local" echo PINTEREST_AUTO_LICENSE_HEARTBEAT_TIMEOUT_MS=10000
  >> "%DATA_DIR%\.env.local" echo PINTEREST_AUTO_UPDATE_MANIFEST_URL=
  >> "%DATA_DIR%\.env.local" echo PINTEREST_AUTO_UPDATE_CHANNEL=stable
  >> "%DATA_DIR%\.env.local" echo PINTEREST_AUTO_UPDATE_REQUIRE_SIGNATURE=true
  >> "%DATA_DIR%\.env.local" echo PINTEREST_AUTO_UPDATE_PUBLIC_KEY_PATH=license-keys/update-public.pem
)

if not exist "%DATA_DIR%\db.json" (
  copy "%APP_DIR%\packaging\default-db.json" "%DATA_DIR%\db.json" >nul
)

set "MAIN_PORT=%PINTEREST_AUTO_PORT%"
if "%MAIN_PORT%"=="" set "MAIN_PORT=3000"
set /a TRY_PORT=%MAIN_PORT%

:check_port
powershell -NoProfile -ExecutionPolicy Bypass -Command "if (Get-NetTCPConnection -LocalPort !TRY_PORT! -State Listen -ErrorAction SilentlyContinue) { exit 0 } else { exit 1 }" >nul 2>nul
if errorlevel 1 goto port_free
set /a TRY_PORT+=1
set /a MAX_PORT=%MAIN_PORT%+20
if !TRY_PORT! GTR !MAX_PORT! (
  echo.
  echo 3000-3020 端口都被占用，请关闭旧的 Pinterest AI Operator 后重试。
  echo.
  if /I not "%NO_PAUSE%"=="/silent" pause
  exit /b 1
)
goto check_port

:port_free
set "MAIN_PORT=!TRY_PORT!"

echo.
echo Pinterest AI Operator 正在启动...
echo 日志文件：%LOG_DIR%\pinterest-auto.log
echo 数据目录：%DATA_DIR%
echo 访问地址：http://127.0.0.1:%MAIN_PORT%
echo.

start "Pinterest AI Operator Server" /min cmd /c ""%~dp0Run Server.cmd" "%MAIN_PORT%""
timeout /t 4 /nobreak >nul
start "" "http://127.0.0.1:%MAIN_PORT%"

echo 已打开浏览器。如果页面暂时无法访问，请等待几秒后刷新。
echo 首次使用请填写 Web 云端授权地址和 License Key。
echo 后续升级只需替换程序目录，%DATA_DIR% 会保留授权和业务数据。
echo.
if /I not "%NO_PAUSE%"=="/silent" pause
CMD

cat > "$APP_DIR/Repair Dependencies.cmd" <<'CMD'
@echo off
setlocal EnableExtensions

set "APP_DIR=%~dp0app"
cd /d "%APP_DIR%"

set "NPM_CMD=%~dp0runtime\node\npm.cmd"
if exist "%NPM_CMD%" goto npm_ready
where npm >nul 2>nul
if errorlevel 1 (
  echo 未找到 npm。请先安装 Node.js 20+。
  pause
  exit /b 1
)
set "NPM_CMD=npm"
:npm_ready

echo 正在重新安装 Windows 依赖，请保持网络可用...
"%NPM_CMD%" install
pause
CMD

cat > "$APP_DIR/Launch Pinterest AI Operator.vbs" <<'VBS'
Set shell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
root = fso.GetParentFolderName(WScript.ScriptFullName)
cmd = """" & root & "\Start Pinterest AI Operator.cmd" & """ /silent"
shell.Run cmd, 0, False
VBS

cat > "$APP_DIR/Create Desktop Shortcut.cmd" <<'CMD'
@echo off
setlocal EnableExtensions

set "TARGET=%SystemRoot%\System32\wscript.exe"
set "ARGS=""%~dp0Launch Pinterest AI Operator.vbs"""

powershell -NoProfile -ExecutionPolicy Bypass -Command "$desktop=[Environment]::GetFolderPath('Desktop'); $shell=New-Object -ComObject WScript.Shell; $shortcut=$shell.CreateShortcut((Join-Path $desktop 'Pinterest AI Operator.lnk')); $shortcut.TargetPath='%TARGET%'; $shortcut.Arguments='%ARGS%'; $shortcut.WorkingDirectory='%~dp0'; $shortcut.Save()"

echo 已在桌面创建 Pinterest AI Operator 快捷方式。
pause
CMD

cat > "$APP_DIR/README-WINDOWS-CLIENT.txt" <<'README'
Pinterest AI Operator Windows 客户端

使用方式：
1. 解压整个 PinterestAIOperator 文件夹。
2. 双击 Start Pinterest AI Operator.cmd。
3. 程序会启动本机服务并打开控制台。
4. 首次使用请填写你的 Web 云端授权服务器 URL 和 License Key。
5. 商业动作会检查授权租约和每日额度。
6. 远程更新会下载并校验更新包；替换程序目录由用户手动确认。
7. 后续升级只需替换程序目录；授权、数据库和 OAuth 数据会保留在用户数据目录。

可选：
- 双击 Create Desktop Shortcut.cmd 可在桌面创建快捷方式。
- 如果依赖在 Windows 上无法启动，双击 Repair Dependencies.cmd 重新安装 Windows 依赖。

要求：
- Windows 10/11
- 不需要额外安装 Node.js；安装包内已带 Windows Node runtime。若你手动删除 runtime 目录，则需要 Node.js 20+。

日志：
%LOCALAPPDATA%\Pinterest AI Operator\Logs\pinterest-auto.log

数据：
%LOCALAPPDATA%\Pinterest AI Operator
README

python3 - "$APP_DIR" <<'PY'
import sys
from pathlib import Path

root = Path(sys.argv[1])
for path in root.glob("*.cmd"):
    text = path.read_text(encoding="utf-8")
    path.write_bytes(text.replace("\r\n", "\n").replace("\n", "\r\n").encode("utf-8"))
PY

(
  cd "$PKG_DIR"
  zip -qry "$ZIP_PATH" "$APP_NAME" -x "*.DS_Store" "__MACOSX/*"
)

cp "$ZIP_PATH" "$LEGACY_ZIP_PATH"
echo "$ZIP_PATH"
