#!/usr/bin/env bash
# Setup script for Zaxy.
# Generates .env file, creates directories, and detects optional Docker sidecars.
# Usage: ./scripts/setup.sh [--production]

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
ENV_FILE="${PROJECT_ROOT}/.env"
SECRETS_DIR="${PROJECT_ROOT}/secrets"
MODE="${1:-dev}"

echo "🚀 Zaxy Setup (${MODE})"
echo "   Project root: ${PROJECT_ROOT}"

# ------------------------------------------------------------------
# Generate .env if missing
# ------------------------------------------------------------------
if [[ ! -f "${ENV_FILE}" ]]; then
    echo "📝 Generating ${ENV_FILE}..."

    if [[ "${MODE}" == "--production" ]]; then
        # Strong random password for production
        NEO4J_PASSWORD="$(openssl rand -hex 32)"
        MCP_ADMIN_TOKEN="$(openssl rand -hex 32)"
        MCP_REMOTE_AUTH_TOKEN="$(openssl rand -hex 32)"
        ZAXY_ENV="production"
        NEO4J_URI="bolt://neo4j:7687"
        NEO4J_CA_CERT="/ssl/bolt/trusted/public.crt"
        LOG_FORMAT="json"
        mkdir -p "${SECRETS_DIR}"
        chmod 700 "${SECRETS_DIR}"
        printf "neo4j/%s\n" "${NEO4J_PASSWORD}" > "${SECRETS_DIR}/neo4j_auth.txt"
        printf "%s\n" "${NEO4J_PASSWORD}" > "${SECRETS_DIR}/neo4j_password.txt"
        printf "%s\n" "${MCP_ADMIN_TOKEN}" > "${SECRETS_DIR}/mcp_admin_token.txt"
        printf "%s\n" "${MCP_REMOTE_AUTH_TOKEN}" > "${SECRETS_DIR}/mcp_remote_auth_token.txt"
        touch "${SECRETS_DIR}/openai_api_key.txt"
        touch "${SECRETS_DIR}/pathlight_access_token.txt"
        chmod 600 "${SECRETS_DIR}/"*.txt
    else
        # Dev defaults
        NEO4J_PASSWORD="testpassword"
        MCP_ADMIN_TOKEN=""
        MCP_REMOTE_AUTH_TOKEN=""
        ZAXY_ENV="development"
        NEO4J_URI="bolt://localhost:7687"
        NEO4J_CA_CERT=""
        LOG_FORMAT="console"
    fi

    cat > "${ENV_FILE}" <<EOF
# Auto-generated by scripts/setup.sh on $(date -Iseconds)
# Mode: ${MODE}

ZAXY_ENV=${ZAXY_ENV}
PROJECTION_BACKEND=embedded
EMBEDDED_GRAPH_PATH=.eventloom/projections/embedded.kuzu
LATTICEDB_PATH=.eventloom/projections/memory.latticedb
NEO4J_AUTO_START=false
PGGRAPH_DSN=postgresql://postgres:postgres@localhost:5432/zaxy
PGGRAPH_AUTO_START=false

EVENTLOOM_PATH=.eventloom
EVENTLOOM_THREAD=default

PATHLIGHT_URL=http://pathlight-collector:4100
PATHLIGHT_ENABLED=false
TRACE_RAW_QUERIES=false

SERVER_NAME=zaxy-memory
MCP_REMOTE_SESSION_HEADER=x-zaxy-session-id

LOG_LEVEL=INFO
LOG_FORMAT=${LOG_FORMAT}

QUERY_DEFAULT_LIMIT=10

EMBEDDING_ENABLED=true
EMBEDDING_PROVIDER=hash
EMBEDDING_DIMENSION=1536
OPENAI_EMBEDDING_MODEL=text-embedding-3-small
OPENAI_BASE_URL=https://api.openai.com/v1
EOF

    if [[ "${MODE}" != "--production" ]]; then
        {
            echo "NEO4J_URI=${NEO4J_URI}"
            echo "NEO4J_USER=neo4j"
            echo "NEO4J_PASSWORD=${NEO4J_PASSWORD}"
            echo "NEO4J_PASSWORD_FILE="
            echo "NEO4J_DATABASE=neo4j"
            echo "NEO4J_CA_CERT=${NEO4J_CA_CERT}"
            echo "NEO4J_TRUST_ALL=false"
            echo "MCP_ADMIN_TOKEN=${MCP_ADMIN_TOKEN}"
            echo "MCP_REMOTE_AUTH_TOKEN=${MCP_REMOTE_AUTH_TOKEN}"
        } >> "${ENV_FILE}"
    else
        {
            echo "MCP_ADMIN_TOKEN_FILE=secrets/mcp_admin_token.txt"
            echo "MCP_REMOTE_AUTH_TOKEN_FILE=secrets/mcp_remote_auth_token.txt"
            echo "OPENAI_API_KEY_FILE=secrets/openai_api_key.txt"
            echo "PATHLIGHT_ACCESS_TOKEN_FILE=secrets/pathlight_access_token.txt"
        } >> "${ENV_FILE}"
    fi

    echo "   ✅ Created ${ENV_FILE}"
    if [[ "${MODE}" == "--production" ]]; then
        echo "   🔒 Secrets written to ${SECRETS_DIR}/"
    fi
else
    echo "   ℹ️  ${ENV_FILE} already exists, skipping generation"
fi

# ------------------------------------------------------------------
# Create directories
# ------------------------------------------------------------------
mkdir -p "${PROJECT_ROOT}/.eventloom"
mkdir -p "${PROJECT_ROOT}/.eventloom/projections"
mkdir -p "${SECRETS_DIR}"

echo "   ✅ Created directories"

# ------------------------------------------------------------------
# Detect optional Docker sidecar tooling
# ------------------------------------------------------------------
DOCKER_AVAILABLE=false
if ! command -v docker &> /dev/null; then
    echo "   ⚠️  Docker unavailable; skipping optional sidecar validation"
elif ! docker compose version &> /dev/null && ! docker-compose version &> /dev/null; then
    echo "   ⚠️  Docker Compose unavailable; skipping optional sidecar validation"
else
    DOCKER_AVAILABLE=true
    echo "   ✅ Optional Docker sidecar tooling available"
fi

# ------------------------------------------------------------------
# Summary
# ------------------------------------------------------------------
echo ""
echo "📋 Setup complete. Next steps:"
echo ""
if [[ "${MODE}" == "--production" ]]; then
    echo "   scripts/validate-deployment.sh --root ."
    if [[ "${DOCKER_AVAILABLE}" == "true" ]]; then
        echo "   docker compose -f docker-compose.prod.yml up -d   # embedded production service"
        echo "   docker compose -f docker-compose.prod.yml --profile neo4j up -d zaxy-neo4j   # optional Neo4j sidecar"
    fi
else
    echo "   zaxy status"
    if [[ "${DOCKER_AVAILABLE}" == "true" ]]; then
        echo "   docker compose --profile integration up -d neo4j-test neo4j-tls   # optional integration sidecars"
    fi
    echo "   pytest -m integration"
fi
echo ""
