#!/bin/bash
# GPS Legal Intake — Deploy to Cloudflare Workers
# Run this once from a machine with wrangler installed and CF credentials

set -e

echo "=== GPS Legal Intake — Deploy ==="

# 1. Install wrangler if not present
if ! command -v wrangler &>/dev/null; then
  npm install -g wrangler
fi

# 2. Create KV namespace (run once)
echo ""
echo "Creating KV namespace..."
KV_OUTPUT=$(wrangler kv:namespace create GPS_SESSIONS 2>&1)
echo "$KV_OUTPUT"
KV_ID=$(echo "$KV_OUTPUT" | grep -oP '(?<=id = ")[^"]+')
if [ -n "$KV_ID" ]; then
  sed -i "s/REPLACE_WITH_KV_NAMESPACE_ID/$KV_ID/" wrangler.toml
  echo "KV namespace ID set: $KV_ID"
fi

# 3. Set secrets
echo ""
echo "Setting secrets (you will be prompted for each value)..."
wrangler secret put ANTHROPIC_API_KEY
wrangler secret put ATTORNEY_EMAIL
wrangler secret put PARTNER_EMAIL
wrangler secret put ADMIN_TOKEN

# 4. Deploy
echo ""
echo "Deploying worker..."
wrangler deploy

echo ""
echo "=== Done ==="
echo "Worker live at: https://gpsintake.bigwigerp.com"
echo "Admin view:     https://gpsintake.bigwigerp.com/admin?token=<your-admin-token>"
echo ""
echo "Next: configure Cloudflare Access at dash.cloudflare.com"
echo "  Zero Trust → Access → Applications → Add application"
echo "  Type: Self-hosted"
echo "  Domain: gpsintake.bigwigerp.com"
echo "  Policy: Allow — Emails — attorney@... partner@..."
