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

TEST_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
CRATE_DIR="$(cd -- "${TEST_DIR}/.." && pwd)"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "${TMP_DIR}"' EXIT

FAKE_CRATE_DIR="${TMP_DIR}/claw"
mkdir -p \
  "${FAKE_CRATE_DIR}/tools/browser_runtime" \
  "${FAKE_CRATE_DIR}/target/debug/resources" \
  "${FAKE_CRATE_DIR}/resources" \
  "${FAKE_CRATE_DIR}/src" \
  "${FAKE_CRATE_DIR}/third_party/zeroclaw/src" \
  "${TMP_DIR}/skill_lib"

cp "${CRATE_DIR}/tools/browser_runtime/sgclaw_browser_entry.sh" \
  "${FAKE_CRATE_DIR}/tools/browser_runtime/sgclaw_browser_entry.sh"
chmod +x "${FAKE_CRATE_DIR}/tools/browser_runtime/sgclaw_browser_entry.sh"

cat > "${FAKE_CRATE_DIR}/Cargo.toml" <<'EOF'
[package]
name = "sgclaw"
version = "0.1.0"
edition = "2021"
EOF

cat > "${FAKE_CRATE_DIR}/Cargo.lock" <<'EOF'
# fake lockfile for launcher test
EOF

cat > "${FAKE_CRATE_DIR}/target/debug/resources/rules.json" <<'EOF'
{"version":"1.0","domains":{"allowed":["www.zhihu.com"]},"pipe_actions":{"allowed":["click","type","navigate","getText"],"blocked":[]}}
EOF

sleep 1

cat > "${FAKE_CRATE_DIR}/resources/rules.json" <<'EOF'
{"version":"1.0","domains":{"allowed":["www.zhihu.com"]},"pipe_actions":{"allowed":["click","type","navigate","getText","eval"],"blocked":[]}}
EOF

cat > "${FAKE_CRATE_DIR}/target/debug/sgclaw" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
grep -q '"eval"' "${SCRIPT_DIR}/resources/rules.json"
EOF
chmod +x "${FAKE_CRATE_DIR}/target/debug/sgclaw"

"${FAKE_CRATE_DIR}/tools/browser_runtime/sgclaw_browser_entry.sh"

grep -q '"eval"' "${FAKE_CRATE_DIR}/target/debug/resources/rules.json"
