#!/usr/bin/env bash
# sync-wallet-fixture.sh — copy the wallet fixture to the canonical runtime slot.
#
# Purpose:
#   After a successful overlay install, ensures the canonical wallet fixture is
#   present in the checkout's runtime dir. Non-zero exit is informational (no
#   fixture source found); the install already succeeded, so the overlay is fresh.
#
# Inputs (flags / env):
#   --target <checkout>     (default $PWD)
#   --slot-id <id>          (env FARMSLOT_SLOT_ID, SLOT_ID — farmslot sync source)
#   --cdp-port <port>       (env CDP_PORT — extension fixture seeding port)
#
# Outputs:
#   Copies wallet-fixture.json to <target>/<RECIPE_RUNTIME_DIR>/wallet-fixture.json
#   when a source is found. Exit 0 always (non-zero only when no source found;
#   callers treat this as informational).
#
# OS-glue only: file copy and farmslot delegation; decision logic lives in
# src/commands/fixtures.ts.
set -uo pipefail

TARGET="$PWD"
SLOT_ID="${FARMSLOT_SLOT_ID:-${SLOT_ID:-}}"
CDP_PORT="${CDP_PORT:-}"

require_value() { [ "$#" -ge 2 ] || { printf 'Missing value for %s\n' "$1" >&2; exit 2; }; }

while [ "$#" -gt 0 ]; do
  case "$1" in
    --target)   require_value "$@"; TARGET="$2";   shift 2 ;;
    --slot-id)  require_value "$@"; SLOT_ID="$2";  shift 2 ;;
    --cdp-port) require_value "$@"; CDP_PORT="$2"; shift 2 ;;
    -h|--help)
      printf 'Usage: sync-wallet-fixture.sh [--target <dir>] [--slot-id <id>] [--cdp-port <port>]\n'
      exit 0
      ;;
    *) printf 'Unknown arg: %s\n' "$1" >&2; exit 2 ;;
  esac
done

TARGET="$(cd "$TARGET" && pwd)"
RUNTIME_DIR="${RECIPE_RUNTIME_DIR:-temp/recipe/runtime}"
CANONICAL="$TARGET/$RUNTIME_DIR/wallet-fixture.json"

mkdir -p "$(dirname "$CANONICAL")"

# Already present — nothing to do.
if [ -f "$CANONICAL" ]; then
  exit 0
fi

# RECIPE_WALLET_FIXTURE env points at a fixture directly.
if [ -n "${RECIPE_WALLET_FIXTURE:-}" ] && [ -f "${RECIPE_WALLET_FIXTURE}" ]; then
  cp "${RECIPE_WALLET_FIXTURE}" "$CANONICAL"
  chmod 600 "$CANONICAL" 2>/dev/null || true
  printf 'sync-wallet-fixture: linked wallet-fixture.json from RECIPE_WALLET_FIXTURE\n' >&2
  exit 0
fi

# Farmslot slot sync (requires farmslot root and sync-fixtures.sh).
if [ -n "$SLOT_ID" ]; then
  FARMSLOT_ROOT="${FARMSLOT_ROOT:-}"
  for candidate in "$HOME/dev/farmslot" "$HOME/farmslot"; do
    [ -d "$candidate/scripts" ] || continue
    FARMSLOT_ROOT="$candidate"
    break
  done
  if [ -n "$FARMSLOT_ROOT" ] && [ -f "$FARMSLOT_ROOT/scripts/sync-fixtures.sh" ]; then
    if bash "$FARMSLOT_ROOT/scripts/sync-fixtures.sh" --slot "$SLOT_ID" 2>/dev/null; then
      [ -f "$CANONICAL" ] && exit 0
    fi
  fi
fi

# No fixture source found — informational non-zero (callers tolerate this).
printf 'sync-wallet-fixture: no wallet fixture source found for %s\n' "$TARGET" >&2
exit 1
