#!/usr/bin/env bash
# End-to-end demo: start MCP server, run the LangGraph agent, verify the DAG.
#
# Requirements:
#   - uv installed (https://docs.astral.sh/uv/)
#   - Ollama running locally with `qwen3:8b` pulled
#     (override via POC_MODEL and OLLAMA_HOST env vars)
#
# The script is idempotent — keys and ledgers are written under ./keys/.

set -euo pipefail

cd "$(dirname "$0")"

POC_MODEL="${POC_MODEL:-qwen3:8b}"
POC_PORT="${POC_PORT:-8765}"
POC_PURPOSE="${POC_PURPOSE:-Search for quantum entanglement, then summarise the top result.}"

mkdir -p keys
rm -f keys/ledger.jsonl keys/server-audit.jsonl

echo "==> syncing dependencies"
uv sync --quiet

echo "==> starting MCP server on 127.0.0.1:${POC_PORT}"
uv run python -m poc.server --port "${POC_PORT}" >/tmp/poc-server.log 2>&1 &
SERVER_PID=$!
trap 'kill "$SERVER_PID" 2>/dev/null || true' EXIT

for _ in $(seq 1 25); do
    if curl -sSf -o /dev/null -X POST "http://127.0.0.1:${POC_PORT}/mcp" \
            -H 'content-type: application/json' \
            --data '{"jsonrpc":"2.0","id":0,"method":"initialize"}' 2>/dev/null \
       || curl -sS "http://127.0.0.1:${POC_PORT}/mcp" -o /dev/null; then
        break
    fi
    sleep 0.2
done

echo "==> running agent (model=${POC_MODEL})"
uv run poc-agent \
    --purpose "${POC_PURPOSE}" \
    --model "${POC_MODEL}" \
    --mcp-url "http://127.0.0.1:${POC_PORT}/mcp"

echo
echo "==> verifying ledger"
uv run poc-verify

echo
echo "==> server audit log (last 5 lines)"
tail -n 5 keys/server-audit.jsonl || true

echo
echo "demo OK"
