#!/usr/bin/env bash
# LangSight quickstart — generates .env and starts the full stack.
# Usage: ./scripts/quickstart.sh
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(dirname "$SCRIPT_DIR")"
ENV_FILE="$ROOT_DIR/.env"

echo "──────────────────────────────────────────────────────"
echo "  LangSight Quickstart"
echo "──────────────────────────────────────────────────────"
echo ""

# ── Generate .env if it doesn't exist ───────────────────────────────────────
if [ -f "$ENV_FILE" ]; then
  echo "[ok] .env already exists — skipping generation."
else
  echo "[..] Generating .env with secure random secrets..."

  # Generate secrets
  API_KEY="ls_$(openssl rand -hex 32)"
  AUTH_SECRET="$(openssl rand -base64 32)"
  POSTGRES_PASSWORD="$(openssl rand -hex 16)"
  CLICKHOUSE_PASSWORD="$(openssl rand -hex 16)"

  cat > "$ENV_FILE" <<EOF
# Generated by scripts/quickstart.sh — $(date -u +"%Y-%m-%dT%H:%M:%SZ")
# Do not commit this file to git.

# API authentication
LANGSIGHT_API_KEYS=${API_KEY}

# Dashboard session secret
AUTH_SECRET=${AUTH_SECRET}

# Dashboard admin login
LANGSIGHT_ADMIN_EMAIL=admin@admin.com
LANGSIGHT_ADMIN_PASSWORD=admin

# Database passwords
POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
CLICKHOUSE_USER=langsight
CLICKHOUSE_PASSWORD=${CLICKHOUSE_PASSWORD}
EOF

  echo "[ok] .env created."
  echo ""
  echo "  API key:        ${API_KEY}"
  echo "  Admin email:    admin@localhost"
  echo "  Admin password: langsight-demo-2026"
  echo ""
fi

# ── Start Docker Compose ────────────────────────────────────────────────────
echo "[..] Starting LangSight stack (this may take 1-2 min on first run)..."
cd "$ROOT_DIR"
docker compose up -d --build --wait 2>&1 | tail -5

echo ""
echo "──────────────────────────────────────────────────────"
echo "  LangSight is running!"
echo "──────────────────────────────────────────────────────"
echo ""
echo "  Dashboard:  http://localhost:3003"
echo "  API:        http://localhost:8000/api/status"
echo "  Login:      admin@admin.com / admin"
echo ""
echo "  API Key:    $(grep LANGSIGHT_API_KEYS "$ENV_FILE" | cut -d= -f2)"
echo ""
echo "  Next steps:"
echo "    1. Open http://localhost:3003 and log in"
echo "    2. Seed demo data:  python scripts/seed-demo.py"
echo "    3. Or trace your own agent:"
echo ""
echo "       from langsight.sdk import LangSightClient"
echo "       client = LangSightClient("
echo "           url=\"http://localhost:8000\","
echo "           api_key=\"<your-api-key>\""
echo "       )"
echo "       traced = client.wrap(mcp_session, server_name=\"my-mcp\")"
echo ""
echo "──────────────────────────────────────────────────────"
