#!/bin/bash
#
# 打包 Agent 代码为 agent.tar.gz，供服务端 /api/v3/agent/download 分发
#
# 用法: cd sdk/agent && bash package.sh
# 输出: sdk/agent/dist/agent.tar.gz
#

set -eo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
DIST_DIR="$SCRIPT_DIR/dist"
TEMP_DIR=$(mktemp -d)

echo "📦 打包 Agent 代码..."

# 创建临时目录结构
mkdir -p "$TEMP_DIR/agent/skills/wechat" \
         "$TEMP_DIR/agent/skills/douyin" \
         "$TEMP_DIR/agent/skills/xhs" \
         "$TEMP_DIR/agent/skills/xianyu" \
         "$TEMP_DIR/agent/skills/soul" \
         "$TEMP_DIR/agent/hawk"

# 复制核心文件
for f in agent.py skill_executor.py skill_bus.py error_handler.py vision_helper.py voice_agent.py requirements.txt config.json.example; do
    if [ -f "$SCRIPT_DIR/$f" ]; then
        cp "$SCRIPT_DIR/$f" "$TEMP_DIR/agent/"
    fi
done

# 复制技能文件
cp "$SCRIPT_DIR/skills/__init__.py" "$TEMP_DIR/agent/skills/"
cp "$SCRIPT_DIR/skills/base.py" "$TEMP_DIR/agent/skills/"
cp "$SCRIPT_DIR/skills/voice_control.py" "$TEMP_DIR/agent/skills/"
cp "$SCRIPT_DIR/skills/app_manager.py" "$TEMP_DIR/agent/skills/"
cp "$SCRIPT_DIR/skills/search.py" "$TEMP_DIR/agent/skills/"
[ -f "$SCRIPT_DIR/skills/network_reconnect.py" ] && cp "$SCRIPT_DIR/skills/network_reconnect.py" "$TEMP_DIR/agent/skills/"
[ -f "$SCRIPT_DIR/skills/connection_guard.py" ] && cp "$SCRIPT_DIR/skills/connection_guard.py" "$TEMP_DIR/agent/skills/"

# Hawk 模块（网络层，与 Agent 隔离）
for f in __init__.py network.py; do
    [ -f "$SCRIPT_DIR/hawk/$f" ] && cp "$SCRIPT_DIR/hawk/$f" "$TEMP_DIR/agent/hawk/"
done

# Hook 模块（Frida Hook 通道）
mkdir -p "$TEMP_DIR/agent/hook/scripts"
for f in README.md setup_redmi11.sh wechat_hook_v1.js; do
    [ -f "$SCRIPT_DIR/hook/$f" ] && cp "$SCRIPT_DIR/hook/$f" "$TEMP_DIR/agent/hook/"
done

for sub in wechat douyin xhs xianyu soul; do
    if [ -d "$SCRIPT_DIR/skills/$sub" ]; then
        cp "$SCRIPT_DIR/skills/$sub/__init__.py" "$TEMP_DIR/agent/skills/$sub/" 2>/dev/null || true
        cp "$SCRIPT_DIR/skills/$sub/skill.py" "$TEMP_DIR/agent/skills/$sub/" 2>/dev/null || true
    fi
done

# 打包
mkdir -p "$DIST_DIR"
cd "$TEMP_DIR"
# 解压后文件直接在当前目录（不带 agent/ 前缀），方便安装脚本
cd agent
tar czf "$DIST_DIR/agent.tar.gz" .

# 清理
rm -rf "$TEMP_DIR"

SIZE=$(du -sh "$DIST_DIR/agent.tar.gz" | cut -f1)
echo "✅ 打包完成: $DIST_DIR/agent.tar.gz ($SIZE)"
