#!/bin/bash
# migrate-identity.sh - Auto-detect and populate identity.json with Ollama/Python config
# Run this on each machine to complete the identity.json migration

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
IDENTITY_PATH="$SCRIPT_DIR/../identity.json"

if [ ! -f "$IDENTITY_PATH" ]; then
    echo "[ERROR] identity.json not found at $IDENTITY_PATH"
    echo "        Run onboarding first to create it."
    exit 1
fi

echo "[INFO] Detecting machine configuration..."

# Detect Python
PYTHON_CMD=""
for cmd in py python3 python; do
    if command -v "$cmd" >/dev/null 2>&1; then
        if "$cmd" -c "import sys; sys.exit(0)" >/dev/null 2>&1; then
            PYTHON_CMD="$cmd"
            break
        fi
    fi
done
[ -z "$PYTHON_CMD" ] && PYTHON_CMD="python3"
echo "  Python: $PYTHON_CMD"

# Detect platform
PLATFORM=""
case "$(uname -s)" in
    Darwin) PLATFORM="macos" ;;
    Linux) PLATFORM="linux" ;;
    CYGWIN*|MINGW*|MSYS*) PLATFORM="windows" ;;
    *) PLATFORM="unknown" ;;
esac
echo "  Platform: $PLATFORM"

# Detect architecture
ARCH=""
case "$(uname -m)" in
    x86_64|amd64) ARCH="amd64" ;;
    arm64|aarch64) ARCH="arm64" ;;
    *) ARCH="unknown" ;;
esac
echo "  Architecture: $ARCH"

# Coord API default — only used if identity.json doesn't already define one.
# The on-LAN address works for all on-network/VPN/Tailscale-routed machines today;
# off-network boxes should edit identity.json to point at a reachable endpoint.
COORD_API_DEFAULT="http://172.16.3.30:8001"

# Detect Ollama endpoint
OLLAMA_ENDPOINT=""
OLLAMA_FALLBACK="http://100.101.122.4:11434"  # Beast via Tailscale
PROSE_MODEL="qwen3:14b"  # default

if curl -s -m 2 http://localhost:11434/api/tags >/dev/null 2>&1; then
    OLLAMA_ENDPOINT="http://localhost:11434"
    echo "  Ollama: local (localhost:11434)"

    # Check if this is GURU-5070 with 12GB VRAM - use qwen3:8b
    HOSTNAME=$(hostname)
    if [[ "$HOSTNAME" == "GURU-5070" ]] || [[ "$HOSTNAME" == "DESKTOP-0O8A1RL" ]]; then
        PROSE_MODEL="qwen3:8b"
        echo "    Prose model: qwen3:8b (12GB VRAM machine)"
    else
        echo "    Prose model: qwen3:14b (default)"
    fi
else
    OLLAMA_ENDPOINT="$OLLAMA_FALLBACK"
    echo "  Ollama: remote (Beast via Tailscale)"
    echo "    Prose model: qwen3:14b (default)"
fi

# Detect Grok CLI (xAI) — optional capability extension (image/video, live web+X
# data, independent second model). Per-machine; sets identity grok.installed so
# the /grok skill knows whether it can run locally. Does NOT set is_fleet_host
# (that's a manual fleet-coordination choice, preserved if already present).
GROK_BIN=""
if command -v grok >/dev/null 2>&1; then
    GROK_BIN="$(command -v grok)"
else
    for c in "$HOME/.grok/bin/grok.exe" "$HOME/.grok/bin/grok" "${LOCALAPPDATA:-}/Programs/grok/grok.exe"; do
        if [ -x "$c" ]; then GROK_BIN="$c"; break; fi
    done
fi
if [ -n "$GROK_BIN" ]; then
    GROK_BIN="$(cygpath -m "$GROK_BIN" 2>/dev/null || echo "$GROK_BIN")"
    GROK_INSTALLED="true"
    echo "  Grok: installed ($GROK_BIN)"
else
    GROK_INSTALLED="false"
    echo "  Grok: not installed"
fi

# Detect Google Gemini CLI — optional capability extension (independent second
# model: verify / review / text). Sibling of Grok. Per-machine; sets identity
# gemini.installed so the /agy skill knows whether it can run locally. Does NOT
# set is_fleet_host (manual fleet-coordination choice, preserved if present).
GEMINI_BIN=""
if command -v gemini >/dev/null 2>&1; then
    GEMINI_BIN="$(command -v gemini)"
else
    for c in "${APPDATA:-}/npm/gemini" "$HOME/AppData/Roaming/npm/gemini" \
             "/usr/local/bin/gemini" "$HOME/.npm-global/bin/gemini"; do
        if [ -n "$c" ] && [ -x "$c" ]; then GEMINI_BIN="$c"; break; fi
    done
fi
if [ -n "$GEMINI_BIN" ]; then
    GEMINI_BIN="$(cygpath -m "$GEMINI_BIN" 2>/dev/null || echo "$GEMINI_BIN")"
    GEMINI_INSTALLED="true"
    echo "  Gemini: installed ($GEMINI_BIN)"
else
    GEMINI_INSTALLED="false"
    echo "  Gemini: not installed"
fi

# Build updated identity.json
echo ""
echo "[INFO] Updating identity.json..."

# Read existing, add new fields, write back.
# On Windows, native Python can't open Git Bash POSIX paths (/d/...); convert to a
# drive-letter/forward-slash path for the interpreter. No-op (falls back) elsewhere.
IDENTITY_PATH_PY=$(cygpath -m "$IDENTITY_PATH" 2>/dev/null || echo "$IDENTITY_PATH")
"$PYTHON_CMD" -c "
import json, sys
with open('$IDENTITY_PATH_PY', 'r') as f:
    data = json.load(f)

# Add new fields if not present
if 'python' not in data:
    data['python'] = {}
data['python']['command'] = '$PYTHON_CMD'

if 'ollama' not in data:
    data['ollama'] = {}
data['ollama']['endpoint'] = '$OLLAMA_ENDPOINT'
data['ollama']['fallback'] = '$OLLAMA_FALLBACK'
data['ollama']['prose_model'] = '$PROSE_MODEL'

if 'platform' not in data:
    data['platform'] = '$PLATFORM'
if 'architecture' not in data:
    data['architecture'] = '$ARCH'

# Grok capability flag (per-machine). Preserve manual keys like is_fleet_host.
g = data.get('grok') or {}
if '$GROK_INSTALLED' == 'true':
    g['installed'] = True
    g['binary'] = r'$GROK_BIN'
    g.setdefault('auth', 'oidc')
    g.setdefault('capabilities', ['text', 'verify', 'image', 'video', 'xsearch'])
else:
    g['installed'] = False
data['grok'] = g

# Gemini capability flag (per-machine, sibling of grok). Preserve manual is_fleet_host.
gm = data.get('gemini') or {}
if '$GEMINI_INSTALLED' == 'true':
    gm['installed'] = True
    gm['binary'] = r'$GEMINI_BIN'
    gm.setdefault('auth', 'oauth')
    gm['capabilities'] = ['text', 'verify', 'review', 'image-analyze', 'search']
else:
    gm['installed'] = False
data['gemini'] = gm

# Coord API endpoint — populate only if absent so existing machines keep their override.
if 'coord_api' not in data:
    data['coord_api'] = '$COORD_API_DEFAULT'

data['last_updated'] = '$(date -u +"%Y-%m-%dT%H:%M:%SZ")'

with open('$IDENTITY_PATH_PY', 'w') as f:
    json.dump(data, f, indent=2)
    f.write('\n')

print('[OK] identity.json updated')
"

echo ""
echo "[SUCCESS] Migration complete. New fields added:"
echo "  python.command: $PYTHON_CMD"
echo "  ollama.endpoint: $OLLAMA_ENDPOINT"
echo "  ollama.fallback: $OLLAMA_FALLBACK"
echo "  ollama.prose_model: $PROSE_MODEL"
echo "  platform: $PLATFORM"
echo "  architecture: $ARCH"
echo "  grok.installed: $GROK_INSTALLED"
echo "  gemini.installed: $GEMINI_INSTALLED"
echo "  coord_api: (default $COORD_API_DEFAULT if not already set)"
echo ""
echo "Review: cat $IDENTITY_PATH"
