#!/bin/bash
# Auth0 CLI Setup Script for Point Topic MCP
# All Auth0 CLI commands must be stored here for reproducibility
# Do not run ad-hoc CLI commands - add them to this script
#
# Usage: ./infrastructure/auth0-setup.sh
# This script will:
#   1. Check if auth0 CLI is installed
#   2. Login to Auth0 (if not already logged in)
#   3. Create the Point Topic MCP application
#   4. Save credentials to infrastructure/auth0-credentials.json
#   5. Output environment variables for .env file

set -euo pipefail

# Configuration
AUTH0_DOMAIN="point-topic.eu.auth0.com"
APP_NAME="Point Topic MCP"
CALLBACK_URL="https://point-topic-mcp.fastmcp.app/auth/callback"  # FastMCP Cloud callback
LOGOUT_URL="https://point-topic-mcp.fastmcp.app"
CREDENTIALS_FILE="infrastructure/auth0-credentials.json"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Auth0 Setup for Point Topic MCP${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Check if auth0 CLI is installed
if ! command -v auth0 &> /dev/null; then
    echo -e "${RED}Error: Auth0 CLI is not installed${NC}"
    echo ""
    echo "Please install Auth0 CLI first:"
    echo "  brew install auth0"
    echo ""
    echo "Or download from: https://github.com/auth0/auth0-cli"
    exit 1
fi

echo -e "${GREEN}✓ Auth0 CLI found${NC}"
echo ""

# Check if already logged in
echo -e "${YELLOW}Checking Auth0 login status...${NC}"
if ! auth0 tenants list &> /dev/null; then
    echo -e "${YELLOW}Not logged in. Initiating Auth0 login...${NC}"
    auth0 login
else
    echo -e "${GREEN}✓ Already logged in to Auth0${NC}"
fi

echo ""
echo -e "${BLUE}Configuration:${NC}"
echo "  Domain: $AUTH0_DOMAIN"
echo "  App Name: $APP_NAME"
echo "  Callback URL: $CALLBACK_URL"
echo "  Logout URL: $LOGOUT_URL"
echo ""

# Check if credentials file already exists
if [ -f "$CREDENTIALS_FILE" ]; then
    echo -e "${YELLOW}⚠ Credentials file already exists: $CREDENTIALS_FILE${NC}"
    read -p "Do you want to overwrite it? (y/N): " overwrite
    if [[ ! $overwrite =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}Setup cancelled. Using existing credentials.${NC}"
        echo ""
        echo "To use existing credentials, run:"
        echo "  cat $CREDENTIALS_FILE"
        exit 0
    fi
fi

# Create Auth0 Application
echo -e "${BLUE}Creating Auth0 Application...${NC}"
echo ""

# Create the application and capture the response
APP_RESPONSE=$(auth0 apps create \
    --name "$APP_NAME" \
    --type "regular" \
    --callbacks "$CALLBACK_URL" \
    --logout-urls "$LOGOUT_URL" \
    --reveal-secrets \
    --json \
    --no-input 2>&1) || {
    echo -e "${RED}Error creating Auth0 application:${NC}"
    echo "$APP_RESPONSE"
    exit 1
}

# Extract credentials from response
CLIENT_ID=$(echo "$APP_RESPONSE" | grep -o '"client_id": "[^"]*"' | cut -d'"' -f4)
CLIENT_SECRET=$(echo "$APP_RESPONSE" | grep -o '"client_secret": "[^"]*"' | cut -d'"' -f4)
APP_ID=$(echo "$APP_RESPONSE" | grep -o '"id": "[^"]*"' | head -1 | cut -d'"' -f4)

if [ -z "$CLIENT_ID" ] || [ -z "$CLIENT_SECRET" ]; then
    echo -e "${RED}Error: Failed to extract credentials from Auth0 response${NC}"
    echo "Response: $APP_RESPONSE"
    exit 1
fi

echo -e "${GREEN}✓ Auth0 Application created successfully${NC}"
echo "  App ID: $APP_ID"
echo ""

# Create or get the API audience
# For now, we'll use a standard audience format
API_AUDIENCE="https://point-topic-mcp-api"

# Save credentials to file
echo -e "${BLUE}Saving credentials to $CREDENTIALS_FILE...${NC}"

# Create credentials JSON
cat > "$CREDENTIALS_FILE" << EOF
{
  "created_at": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "auth0_domain": "$AUTH0_DOMAIN",
  "app_name": "$APP_NAME",
  "app_id": "$APP_ID",
  "client_id": "$CLIENT_ID",
  "client_secret": "$CLIENT_SECRET",
  "api_audience": "$API_AUDIENCE",
  "callback_url": "$CALLBACK_URL",
  "logout_url": "$LOGOUT_URL"
}
EOF

echo -e "${GREEN}✓ Credentials saved to $CREDENTIALS_FILE${NC}"
echo ""

# Output environment variables
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Environment Variables for .env file${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
echo "# Auth0 Configuration"
echo "AUTH0_DOMAIN=$AUTH0_DOMAIN"
echo "AUTH0_CLIENT_ID=$CLIENT_ID"
echo "AUTH0_CLIENT_SECRET=$CLIENT_SECRET"
echo "AUTH0_AUDIENCE=$API_AUDIENCE"
echo ""
echo -e "${YELLOW}⚠ IMPORTANT: Add these to your .env file${NC}"
echo ""

# Output server configuration
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Server Configuration${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
echo "Base URL for FastMCP Cloud: https://point-topic-mcp.fastmcp.app"
echo "Callback Path: /auth/callback"
echo "Full Callback URL: $CALLBACK_URL"
echo ""
echo -e "${GREEN}✓ Auth0 setup complete!${NC}"
echo ""
echo "Next steps:"
echo "  1. Add the environment variables above to your .env file"
echo "  2. Ensure credentials file exists: $CREDENTIALS_FILE"
echo "  3. Start the MCP server: python -m point_topic_mcp.server_http"
echo "  4. Test with Cursor IDE or opencode client"
echo ""

# Make credentials file readable only by owner
chmod 600 "$CREDENTIALS_FILE"
echo -e "${YELLOW}Credentials file permissions set to 600 (owner only)${NC}"
