#!/bin/bash
# ================================================================
#  AI数智员工 统一 APK 构建脚本 v4.0
# ================================================================
# 构建单一 APK 发布包 — 不再包含 Termux/Python Agent
# ================================================================

set -eo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
ANDROID_DIR="${PROJECT_ROOT}/android-app"
OUTPUT_DIR="${PROJECT_ROOT}/release"

echo "╔══════════════════════════════════════╗"
echo "║  AI数智员工 v4.0 构建                ║"
echo "╚══════════════════════════════════════╝"

# 1. Copy hub.html to assets
echo "📦 同步 assets..."
cp -f "${PROJECT_ROOT}/app/static/hub.html" "${ANDROID_DIR}/app/src/main/assets/hub.html" 2>/dev/null || true
cp -f "${PROJECT_ROOT}/agent/hook/wechat_hook_v2.js" "${ANDROID_DIR}/app/src/main/assets/wechat_hook_v2.js" 2>/dev/null || true
cp -f "${PROJECT_ROOT}/agent/hook/wechat_version_compat.json" "${ANDROID_DIR}/app/src/main/assets/wechat_version_compat.json" 2>/dev/null || true

# 2. Build APK
echo "🔨 构建 APK..."
cd "$ANDROID_DIR"
./gradlew assembleRelease --no-daemon

APK_DEBUG="${ANDROID_DIR}/app/build/outputs/apk/debug/app-debug.apk"
APK_RELEASE="${ANDROID_DIR}/app/build/outputs/apk/release/app-release-unsigned.apk"
APK_FILE="${APK_RELEASE}"
[[ ! -f "$APK_FILE" ]] && APK_FILE="$APK_DEBUG"

if [[ ! -f "$APK_FILE" ]]; then
    echo "❌ 构建失败"
    exit 1
fi

# 3. Package release
mkdir -p "$OUTPUT_DIR"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
RELEASE_DIR="${OUTPUT_DIR}/ai-agent-v4.0-${TIMESTAMP}"
mkdir -p "$RELEASE_DIR"

cp "$APK_FILE" "${RELEASE_DIR}/AI数智员工.apk"
cp "${SCRIPT_DIR}/master_deploy.sh" "${RELEASE_DIR}/"

cat > "${RELEASE_DIR}/README.md" << 'EOF'
# AI数智员工 v4.0 统一安装包

## 安装方式

### 方式一：手动安装
1. 将 `AI数智员工.apk` 传输到手机
2. 在手机上安装 APK
3. 打开 APP → 扫码绑定

### 方式二：批量部署
```bash
./master_deploy.sh --server ws://YOUR_SERVER:8899/ws/device
```

## 功能说明
- ✅ 5 通道连接（WebSocket/Hook/ADB/AI Agent/scrcpy）
- ✅ 内置防封模块（风控/养号/人性化操作/环境检测/传感器模拟）
- ✅ AI 大脑（LLM 决策 + 离线自主运行）
- ✅ 内嵌工作台（hub.html）
- ✅ Root 可选（有 Root 启用 Frida Hook，无 Root 其余通道正常）

## 无需安装
- ❌ 不再需要 Termux
- ❌ 不再需要 Python Agent
- ❌ 不再需要旧版工作手机Agent APP
EOF

cd "$OUTPUT_DIR"
tar czf "ai-agent-v4.0-${TIMESTAMP}.tar.gz" "ai-agent-v4.0-${TIMESTAMP}"

echo ""
echo "✅ 构建完成！"
echo "   APK: ${RELEASE_DIR}/AI数智员工.apk"
echo "   包:  ${OUTPUT_DIR}/ai-agent-v4.0-${TIMESTAMP}.tar.gz"
echo "   大小: $(du -h "$APK_FILE" | awk '{print $1}')"
