#!/usr/bin/env bash
# deploy.sh -- Deploy ProofTrail to Railway
# Usage: ./deploy.sh [--init]
set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

info()  { echo -e "${GREEN}[+]${NC} $1"; }
warn()  { echo -e "${YELLOW}[!]${NC} $1"; }
error() { echo -e "${RED}[x]${NC} $1" >&2; exit 1; }

# --- Pre-flight checks ---

command -v railway >/dev/null || error "Railway CLI not installed. Run: brew install railway"
command -v uv >/dev/null      || error "uv not installed. Run: brew install uv"

info "Running tests..."
PROOFTRAIL_ADMIN_SECRET=test uv run pytest tests/ -q || error "Tests failed. Fix before deploying."

# --- Check for secrets in codebase ---

# Match full API keys (pt_live_ + 32 hex chars) but ignore test fixtures with obvious dummy values
if grep -rPn 'pt_live_[0-9a-f]{32}' --include="*.py" . 2>/dev/null \
    | grep -v ".venv" | grep -v "__pycache__" \
    | grep -v "0000000000000000" | grep -v "dead" | grep -v "test"; then
    error "Leaked API key found in source files. Remove before deploying."
fi

if [ -f "prooftrail.db" ] && git ls-files --error-unmatch prooftrail.db 2>/dev/null; then
    error "prooftrail.db is git-tracked. Add to .gitignore and run: git rm --cached prooftrail.db"
fi

# --- Init (first-time only) ---

if [ "${1:-}" = "--init" ]; then
    info "Creating Railway project..."
    railway init --name prooftrail
    railway service link prooftrail

    info "Setting environment variables..."
    ADMIN_SECRET=$(openssl rand -hex 32)
    railway variables set \
        PROOFTRAIL_ADMIN_SECRET="$ADMIN_SECRET" \
        PROOFTRAIL_DB_PATH=/data/prooftrail.db

    info "Creating persistent volume..."
    railway volume add --mount-path /data

    info "Generating public domain..."
    railway domain

    warn "Admin secret set. Save it to your password manager (NOT in terminal history)."
    warn "To view it: railway variables | grep ADMIN_SECRET"
    echo ""
fi

# --- Deploy ---

info "Checking Railway auth..."
railway whoami || error "Not logged in. Run: railway login"

info "Checking service link..."
railway status || error "No project linked. Run: ./deploy.sh --init"

info "Deploying to Railway..."
railway up --detach

info "Waiting for deployment..."
for i in $(seq 1 30); do
    sleep 10
    STATUS=$(railway service status 2>&1 | grep "Status:" | awk '{print $2}')
    case "$STATUS" in
        SUCCESS)
            info "Deployment successful!"
            break
            ;;
        FAILED|CRASHED)
            error "Deployment failed. Check logs: railway logs"
            ;;
        *)
            echo -n "."
            ;;
    esac
done
echo ""

# --- Verify ---

DOMAIN=$(railway variables 2>&1 | grep "RAILWAY_PUBLIC_DOMAIN" | awk -F'│' '{print $2}' | xargs)
if [ -n "$DOMAIN" ]; then
    URL="https://$DOMAIN"
    info "Testing health endpoint..."
    HEALTH=$(curl -sf "$URL/health" 2>/dev/null || echo "FAIL")
    if echo "$HEALTH" | grep -q '"ok"'; then
        info "Health check passed!"
        echo ""
        echo -e "${GREEN}ProofTrail is live at: $URL${NC}"
        echo -e "  API docs: $URL/docs"
        echo -e "  Health:   $URL/health"
    else
        warn "Health check returned: $HEALTH"
        warn "Check logs: railway logs"
    fi
else
    warn "Could not determine domain. Run: railway domain"
fi
