#!/bin/bash
# Kipinä Studio — paikallinen kehitysympäristö
# Buildaa frontendin, käynnistää hubin ja native-noden (Ollama)
# Käyttö: ./deploy-local.sh
set -e
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR"

cleanup() { echo ""; echo "Pysäytetään..."; kill $HUB_PID $NODE_PID 2>/dev/null; exit 0; }
trap cleanup INT TERM

# Portti vapaaksi
lsof -ti:3000 | xargs kill -9 2>/dev/null || true

# Frontend
echo "[1/3] Frontend..."
cd "$SCRIPT_DIR/frontend"
[ -d node_modules ] || npm install --silent
npm run build 2>&1 | tail -1
cd "$SCRIPT_DIR"

# Hub
echo "[2/3] Hub..."
STATIC_DIR="$SCRIPT_DIR/frontend/dist" cargo run -p hub 2>&1 &
HUB_PID=$!
until curl -sf http://localhost:3000 >/dev/null 2>&1; do sleep 1; done

# Native-node
NODE_PID=""
if curl -sf http://localhost:11434/api/tags >/dev/null 2>&1; then
    MODEL=$(curl -s http://localhost:11434/api/tags | python3 -c "
import sys,json
ms=json.load(sys.stdin).get('models',[])
for m in ms:
    n=m['name']
    if '7b' in n and 'coder' in n: print(n); exit()
for m in ms:
    if 'coder' in m['name']: print(m['name']); exit()
if ms: print(ms[0]['name'])
" 2>/dev/null)
    if [ -n "$MODEL" ]; then
        echo "[3/3] Native-node ($MODEL)..."
        HUB_URL=ws://localhost:3000/ws OLLAMA_MODEL="$MODEL" \
            cargo run -p native-node --no-default-features 2>&1 &
        NODE_PID=$!
    else
        echo "[3/3] Ollama: ei malleja (ollama pull qwen2.5-coder:7b)"
    fi
else
    echo "[3/3] Ei Ollamaa — Wasm-fallback selaimessa"
fi

echo ""
echo "=== http://localhost:3000 === Ctrl+C pysäyttää"
open http://localhost:3000 2>/dev/null || xdg-open http://localhost:3000 2>/dev/null || true
wait $HUB_PID
