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

BRAID_HOME="${BRAID_HOME:-$HOME/.braid}"
TRUST_DIR="$BRAID_HOME/trust"
ROUTE_DIR="$TRUST_DIR/source-route"
TRUSTED_KEY="$TRUST_DIR/sender.pub"
TRUST_META="$TRUST_DIR/trust.json"
INBOX="$BRAID_HOME/inbox"
PORT="${BRAID_RECEIVER_PORT:-8745}"
BRAID_BIN="${BRAID_BIN:-$HOME/.local/bin/braid-client}"

say() { printf '%s\n' "$*"; }
fail() { say "Braid: $*" >&2; exit 1; }
pause_if_interactive() { if [[ -t 0 ]]; then echo; read -r -p "Press Enter to close this window..." _ || true; fi; }

[[ -x "$BRAID_BIN" ]] || { say "Braid CLI not found at $BRAID_BIN. Re-run the Linux installer."; pause_if_interactive; exit 1; }
mkdir -p "$TRUST_DIR" "$INBOX"

import_trust_if_available() {
  local candidate="" p
  for p in "$HOME/Downloads/Braid-Trust.braidtrust" "$HOME/Desktop/Braid-Trust.braidtrust" "$HOME/Downloads/Braid-Pairing.braidpair" "$HOME/Desktop/Braid-Pairing.braidpair"; do
    if [[ -f "$p" ]]; then candidate="$p"; break; fi
  done
  [[ -n "$candidate" ]] || return 1
  say "Braid: found trust enrollment bundle: $candidate"
  "$HOME/.local/bin/braid-trust-import" "$candidate"
}

migrate_existing_trust() {
  local legacy_route="" legacy_key="" legacy_meta=""
  if [[ -f "$BRAID_HOME/pairing/source-route/route.json" && -f "$BRAID_HOME/pairing/sender.pub" ]]; then
    legacy_route="$BRAID_HOME/pairing/source-route"; legacy_key="$BRAID_HOME/pairing/sender.pub"; legacy_meta="$BRAID_HOME/pairing/pairing.json"
  elif [[ -f "$BRAID_HOME/mac-route/route.json" && -f "$BRAID_HOME/sender.pub" ]]; then
    legacy_route="$BRAID_HOME/mac-route"; legacy_key="$BRAID_HOME/sender.pub"
  elif [[ -f "$BRAID_HOME/route/route.json" && -f "$BRAID_HOME/sender.pub" ]]; then
    legacy_route="$BRAID_HOME/route"; legacy_key="$BRAID_HOME/sender.pub"
  fi
  if [[ -n "$legacy_route" ]]; then
    say "Braid: migrating existing trusted route/public key into Braid Trust state."
    rm -rf "$ROUTE_DIR"
    mkdir -p "$TRUST_DIR"
    cp -a "$legacy_route" "$ROUTE_DIR"
    cp -f "$legacy_key" "$TRUSTED_KEY"
    chmod 0644 "$TRUSTED_KEY" 2>/dev/null || true
    python3 - "$TRUST_META" "$legacy_meta" <<'PY2'
import json,sys
embed='all-minilm:latest'
if len(sys.argv)>2 and sys.argv[2]:
    try: embed=json.load(open(sys.argv[2])).get('embed_model',embed)
    except Exception: pass
json.dump({'schema':'braid.trust-bundle.v1','version':'1.5.2','embed_model':embed,'private_key_included':False,'scope':'authorized-signer-route','migration':'legacy-v1.5.2'}, open(sys.argv[1],'w'), separators=(',',':'))
PY2
    return 0
  fi
  return 1
}

if [[ ! -f "$TRUSTED_KEY" || ! -f "$ROUTE_DIR/route.json" ]]; then
  import_trust_if_available || migrate_existing_trust || true
fi

if [[ ! -f "$TRUSTED_KEY" || ! -f "$ROUTE_DIR/route.json" ]]; then
  cat <<'TXT'
Braid v1.5.2 is installed and the visualizer is open.

Secure receiver is NOT started yet because this node has not been enrolled in Braid Trust.
Braid intentionally requires an authorized sender PUBLIC key and exact frozen route.

On a trusted sender:
  braid-trust-export

Copy Braid-Trust.braidtrust into this machine's Downloads folder, then
launch Braid Client again. The private signing key never leaves the sender.
TXT
  pause_if_interactive
  exit 2
fi

if ! "$BRAID_BIN" hetero-route-info "$ROUTE_DIR" >/dev/null; then
  fail "The enrolled route package failed verification. Re-import the Braid Trust bundle."
fi

EMBED_MODEL="${BRAID_EMBED_MODEL:-}"
if [[ -z "$EMBED_MODEL" && -f "$TRUST_META" ]]; then
  EMBED_MODEL="$(python3 - "$TRUST_META" <<'PY2'
import json,sys
try: print(json.load(open(sys.argv[1])).get('embed_model',''))
except Exception: print('')
PY2
)"
fi
EMBED_MODEL="${EMBED_MODEL:-all-minilm:latest}"

ensure_ollama_model() {
  command -v ollama >/dev/null 2>&1 || fail "Ollama is required for semantic receive mode. Install/start Ollama, then relaunch Braid."
  local env_json
  if ! env_json="$("$BRAID_BIN" environment 2>/dev/null)"; then
    fail "Braid could not query the local Ollama environment. Start Ollama, then relaunch Braid."
  fi
  if ! printf '%s' "$env_json" | python3 -c 'import json,sys; m=sys.argv[1]; d=json.load(sys.stdin); raise SystemExit(0 if d.get("ollama",{}).get("reachable") and any(x.get("name")==m for x in d.get("ollama",{}).get("models",[])) else 1)' "$EMBED_MODEL"; then
    say "Braid: local embedding model $EMBED_MODEL is unavailable; requesting it from Ollama..."
    ollama pull "$EMBED_MODEL" || fail "Ollama could not provide $EMBED_MODEL. Confirm the Ollama service is running and relaunch Braid."
  fi
}

preferred_ip() {
  "$BRAID_BIN" environment | python3 -c 'import json,sys; print(json.load(sys.stdin).get("lan",{}).get("preferred") or "")'
}

ensure_ollama_model
IP="$(preferred_ip)"
[[ -n "$IP" && "$IP" != "None" ]] || fail "Could not determine a LAN address."

say "Braid v1.5.2 secure receiver"
say "  bind: $IP:$PORT"
say "  embedding: $EMBED_MODEL"
say "  trust route: $ROUTE_DIR"
say "  trusted sender key: $TRUSTED_KEY"
say "  inbox: $INBOX"
say ""
say "Receiver is starting. Keep this window open."
exec "$BRAID_BIN" receive \
  --trusted-key "$TRUSTED_KEY" \
  --route-package "$ROUTE_DIR" \
  --bind "$IP" --allow-lan --port "$PORT" \
  --output-dir "$INBOX" \
  --semantic-embed-model "$EMBED_MODEL"
