#!/usr/bin/env bash
# Install runner metadata and delegates into a current MetaMask Mobile checkout.
set -euo pipefail

TARGET="$PWD"
GIT_EXCLUDE=true
while [ "$#" -gt 0 ]; do
  case "$1" in
    --target) [ "$#" -ge 2 ] || { echo "Missing value for --target" >&2; exit 2; }; TARGET="$2"; shift 2 ;;
    --no-git-exclude) GIT_EXCLUDE=false; shift ;;
    -h|--help) echo "Usage: inject.sh [--target <metamask-mobile>] [--no-git-exclude]"; exit 0 ;;
    *) echo "Unknown arg: $1" >&2; exit 2 ;;
  esac
done

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RUNNER_DIR="$(cd "$SCRIPT_DIR/../.." && pwd -P)"
. "$SCRIPT_DIR/../shared/harness-path.sh"
TARGET="$(cd "$TARGET" && pwd -P)"
TARGET_REV="$(git -C "$TARGET" rev-parse --verify HEAD 2>/dev/null || true)"
if [ -z "$TARGET_REV" ]; then
  echo "Refusing mobile harness install: cannot resolve checkout HEAD in $TARGET." >&2
  echo "Next: run this command from a current MetaMask Mobile git checkout." >&2
  exit 1
fi

if ! git -C "$TARGET" ls-files --error-unmatch app/dev-tools/AgenticService/AgenticService.ts >/dev/null 2>&1 \
  || ! grep -q "AgenticService.install" "$TARGET/app/core/NavigationService/NavigationService.ts" 2>/dev/null; then
  echo "Current MetaMask Mobile agentic bridge is missing from $TARGET." >&2
  echo "Next: update the checkout to a revision containing app/dev-tools/AgenticService, then retry mm-harness install." >&2
  exit 1
fi

HARNESS_ROOT="$(harness_root)"
HARNESS_REL="$HARNESS_ROOT/mobile"
HARNESS_DIR="$(harness_dir "$TARGET" mobile)"
for rel in "$HARNESS_REL" "$HARNESS_REL/runner" "$HARNESS_REL/scripts"; do
  current="$TARGET"
  IFS='/' read -r -a parts <<< "$rel"
  for part in "${parts[@]}"; do
    [ -n "$part" ] || continue
    current="$current/$part"
    [ ! -L "$current" ] || { echo "Refusing mobile harness install: $rel contains symlink $current." >&2; exit 1; }
  done
done

rm -rf "$HARNESS_DIR/runner" "$HARNESS_DIR/scripts" "$HARNESS_DIR/bridge-runtime"
mkdir -p "$HARNESS_DIR/runner/bin" "$HARNESS_DIR/runner/manifests" "$HARNESS_DIR/runner/recipes" "$HARNESS_DIR/scripts/lib"

RUNNER_EXEC_Q="$(printf '%q' "$RUNNER_DIR/bin/mm-harness")"
TARGET_Q="$(printf '%q' "$TARGET")"
PROTOCOL_ROOT="${METAMASK_RUNNER_PROTOCOL_ROOT:-}"
if [ -z "$PROTOCOL_ROOT" ] && [ -f "$RUNNER_DIR/.farmslot-root" ]; then
  PROTOCOL_ROOT="$(cat "$RUNNER_DIR/.farmslot-root")"
fi
PROTOCOL_ROOT_Q="$(printf '%q' "$PROTOCOL_ROOT")"
{
  printf '%s\n' '#!/usr/bin/env bash' 'set -euo pipefail'
  printf 'TARGET_DIR=%s\n' "$TARGET_Q"
  printf '%s\n' 'if [ -f "$TARGET_DIR/.js.env" ]; then set +u; set -a; . "$TARGET_DIR/.js.env"; set +a; set -u; fi'
  if [ -n "$PROTOCOL_ROOT" ]; then
    printf 'export METAMASK_RUNNER_PROTOCOL_ROOT=${METAMASK_RUNNER_PROTOCOL_ROOT:-%s}\n' "$PROTOCOL_ROOT_Q"
  fi
  printf '%s\n' 'if [ -n "${MM_HARNESS_BIN:-}" ] && [ -x "$MM_HARNESS_BIN" ]; then exec "$MM_HARNESS_BIN" "$@"; fi'
  printf 'if [ -x %s ]; then exec %s "$@"; fi\n' "$RUNNER_EXEC_Q" "$RUNNER_EXEC_Q"
  printf '%s\n' 'if command -v mm-harness >/dev/null 2>&1; then exec mm-harness "$@"; fi'
  printf '%s\n' 'echo "mm-harness not found. Next: npm i -g @deeeed/metamask-harness@latest" >&2' 'exit 127'
} > "$HARNESS_DIR/runner/bin/mm-harness"
chmod +x "$HARNESS_DIR/runner/bin/mm-harness"

[ -z "$PROTOCOL_ROOT" ] || printf '%s\n' "$PROTOCOL_ROOT" > "$HARNESS_DIR/runner/.farmslot-root"
printf '%s\n' "$RUNNER_DIR" > "$HARNESS_DIR/runner/.runner-source"
cp "$RUNNER_DIR/library/manifests/mobile.action-manifest.json" "$HARNESS_DIR/action-manifest.json"
cp "$RUNNER_DIR/library/manifests/mobile.action-manifest.json" "$HARNESS_DIR/runner/manifests/mobile.action-manifest.json"
cp "$RUNNER_DIR/library/manifests/extension.action-manifest.json" "$HARNESS_DIR/runner/manifests/extension.action-manifest.json"
rsync -a --delete "$RUNNER_DIR/library/recipes/" "$HARNESS_DIR/runner/recipes/"
rm -rf "$HARNESS_DIR/runner/flows"
rm -f "$HARNESS_DIR/runner/library.json"
cp "$RUNNER_DIR/adapters/mobile/verify.sh" "$HARNESS_DIR/scripts/verify.sh"
cp -R "$RUNNER_DIR/adapters/mobile/bridge-runtime" "$HARNESS_DIR/bridge-runtime"
cp "$RUNNER_DIR/adapters/shared/harness-path.sh" "$HARNESS_DIR/scripts/lib/harness-path.sh"
cp "$RUNNER_DIR/adapters/shared/path-defaults.json" "$HARNESS_DIR/scripts/lib/path-defaults.json"
chmod -R u+rwX,go+rX "$HARNESS_DIR"

add_git_exclude() {
  local entry="$1" git_dir exclude_file
  git -C "$TARGET" check-ignore -q "${entry%/}" 2>/dev/null && return 0
  git_dir="$(git -C "$TARGET" rev-parse --git-dir)"
  case "$git_dir" in /*) ;; *) git_dir="$TARGET/$git_dir" ;; esac
  exclude_file="$git_dir/info/exclude"
  mkdir -p "$(dirname "$exclude_file")"; touch "$exclude_file"
  grep -qxF "$entry" "$exclude_file" || { echo "$entry" >> "$exclude_file"; echo "$entry" >> "$HARNESS_DIR/added-git-exclude"; }
}
if [ "$GIT_EXCLUDE" = true ]; then
  add_git_exclude "$HARNESS_ROOT/"
fi

RUNNER_REV="$(git -C "$RUNNER_DIR" rev-parse HEAD 2>/dev/null || echo unknown)"
SOURCE_FINGERPRINT="$(node "$RUNNER_DIR/adapters/shared/harness-source-fingerprint.mjs" "$RUNNER_DIR" mobile)"
CLEANUP_Q="$(printf '%q' "$SCRIPT_DIR/cleanup.sh")"
TARGET_CLEANUP_Q="$(printf '%q' "$TARGET")"
CLEANUP_COMMAND="RECIPE_HARNESS_ROOT=$(printf '%q' "$HARNESS_ROOT") $CLEANUP_Q --target $TARGET_CLEANUP_Q"
node - "$HARNESS_DIR/manifest.json" "$TARGET_REV" "$RUNNER_DIR" "$RUNNER_REV" "$SOURCE_FINGERPRINT" "$TARGET" "$HARNESS_REL" "$HARNESS_ROOT" "$CLEANUP_COMMAND" <<'NODE'
const fs = require('node:fs');
const [manifestPath, targetRevision, runnerDir, runnerRevision, sourceFingerprint, target, harnessRel, harnessRoot, cleanupCommand] = process.argv.slice(2);
fs.writeFileSync(manifestPath, JSON.stringify({
  adapter: 'mobile',
  installMode: 'product-owned',
  targetRevision,
  installedAt: new Date().toISOString(),
  source: { runnerDir, runnerRevision },
  sourceFingerprint,
  target,
  protocolVersion: 'v1',
  actionManifestPath: `${harnessRel}/action-manifest.json`,
  runnerEntrypoint: `${harnessRel}/runner/bin/mm-harness`,
  runtimeHelpers: { verify: `${harnessRel}/scripts/verify.sh` },
  harnessInstalledPaths: [`${harnessRel}/runner`, `${harnessRel}/scripts`, `${harnessRel}/bridge-runtime`, `${harnessRel}/action-manifest.json`],
  productOwnedPaths: ['app/dev-tools/AgenticService', 'app/core/NavigationService/NavigationService.ts'],
  cleanupCommand,
  productDiffExcludes: [`:(exclude)${harnessRoot}`],
}, null, 2) + '\n');
NODE

echo "Installed mobile harness metadata: $HARNESS_DIR/manifest.json"
