#!/bin/bash

# ==============================================================================
# AI Agent Workspace Bootstrapper
# ==============================================================================
# This script automates the setup of a portable agent environment on any machine.
# It authenticates with a secure Vercel gateway to download API keys and GitHub
# credentials, clones the agent-core engine, sets up virtual environments, and
# registers global system commands.
# ==============================================================================

# Dynamic placeholder replaced by Vercel serverless function
AUTH_URL="https://agent.s33k.ai/api/auth"

# Terminal formatting colors (ANSI)
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m' # No Color

# Print banner
echo -e "${CYAN}${BOLD}"
echo "   ___        _   _                     _ _          "
echo "  / _ \      | | (_)                   (_) |         "
echo " / /_\ \_ __ | |_ _  __ _ _ __ __ ___   _| |_ _   _  "
echo " |  _  | '_ \| __| |/ _\` | '__/ _\` \ \ / / | __| | | | "
echo " | | | | | | | |_| | (_| | | | (_| |\ V /| | |_| |_| | "
echo " \_| |_/_| |_|\__|_|\__, |_|  \__,_| \_/ |_|\__|\__, | "
echo "                     __/ |                       __/ | "
echo "                    |___/                       |___/  "
echo -e "${NC}"
echo -e "${BLUE}${BOLD}====================================================================${NC}"
echo -e "${CYAN}${BOLD}                 Portable AI Agent Workspace Setup                  ${NC}"
echo -e "${BLUE}${BOLD}====================================================================${NC}"
echo ""

# Helper function to parse JSON values using Python, Node, or jq
parse_json_val() {
  local json="$1"
  local key="$2"
  if command -v python3 >/dev/null 2>&1; then
    python3 -c "import sys, json;
try:
    print(json.loads(sys.argv[1]).get(sys.argv[2], ''))
except Exception:
    pass" "$json" "$key"
  elif command -v node >/dev/null 2>&1; then
    node -e "try { console.log(JSON.parse(process.argv[1])[process.argv[2]] || ''); } catch(e) {}" "$json" "$key"
  elif command -v jq >/dev/null 2>&1; then
    echo "$json" | jq -r ".$key // empty"
  else
    # Fallback basic regex parsing
    echo "$json" | grep -o "\"$key\"[[:space:]]*:[[:space:]]*\"[^\"]*\"" | head -n 1 | cut -d'"' -f4
  fi
}

# Helper function to extract and write agent_keys from JSON to .env file
write_agent_keys() {
  local json="$1"
  local filepath="$2"
  if command -v python3 >/dev/null 2>&1; then
    python3 -c "
import sys, json
try:
    data = json.loads(sys.argv[1]).get('agent_keys', {})
    with open(sys.argv[2], 'w') as f:
        for k, v in data.items():
            f.write(f'{k}=\"{v}\"\n')
except Exception as e:
    print('Error writing keys:', e, file=sys.stderr)
    sys.exit(1)
" "$json" "$filepath"
  elif command -v node >/dev/null 2>&1; then
    node -e "
try {
    const data = JSON.parse(process.argv[1]).agent_keys || {};
    const fs = require('fs');
    let content = '';
    for (const [k, v] of Object.entries(data)) {
        content += \`\${k}=\"\${v}\"\n\`;
    }
    fs.writeFileSync(process.argv[2], content);
} catch(e) {
    console.error('Error writing keys:', e);
    process.exit(1);
}
" "$json" "$filepath"
  else
    # Grep-based fallback for write_agent_keys
    echo "$json" | grep -o '"[A-Za-z0-9_]*"[[:space:]]*:[[:space:]]*"[^"]*"' | while read -r line; do
      key=$(echo "$line" | cut -d'"' -f2)
      val=$(echo "$line" | cut -d'"' -f4)
      if [ "$key" != "github_token" ] && [ "$key" != "github_user" ] && [ "$key" != "repo_name" ]; then
        echo "${key}=\"${val}\"" >> "$filepath"
      fi
    done
  fi
}

# 1. Prompt for password silently
echo -e "${YELLOW}${BOLD}[1/3] Authentication${NC}"
if [ -z "$DEPLOY_PASS" ]; then
  if [ -t 0 ]; then
    read -s -p "Enter deployment password: " DEPLOY_PASS
    echo ""
  elif [ -c /dev/tty ] && [ -t 1 ]; then
    read -s -p "Enter deployment password: " DEPLOY_PASS < /dev/tty
    echo ""
  else
    read -s -p "Enter deployment password: " DEPLOY_PASS
    echo ""
  fi
fi

# Strip any trailing carriage returns (\r) or leading/trailing whitespace
DEPLOY_PASS=$(echo "$DEPLOY_PASS" | tr -d '\r' | xargs)

# 2. Fetch config payload from Vercel gatekeeper
echo -e "Connecting to secure gateway..."
RESPONSE=$(curl -S -s -X POST "$AUTH_URL" \
  -H "Content-Type: application/json" \
  -d "{\"password\": \"$DEPLOY_PASS\"}")
CURL_EXIT=$?

# Fallback to insecure if SSL/CA certificate error occurs (common in Anaconda environments or behind proxies)
if [ $CURL_EXIT -eq 60 ] || [ $CURL_EXIT -eq 77 ]; then
  echo -e "${YELLOW}⚠️ Warning: Local SSL certificate verification failed (exit code $CURL_EXIT).${NC}"
  echo -e "Retrying handshake with SSL check bypassed..."
  RESPONSE=$(curl -S -s -k -X POST "$AUTH_URL" \
    -H "Content-Type: application/json" \
    -d "{\"password\": \"$DEPLOY_PASS\"}")
  CURL_EXIT=$?
fi

if [ $CURL_EXIT -ne 0 ]; then
  echo -e "${RED}${BOLD}❌ Error: Connection to auth gateway failed (curl exit code: $CURL_EXIT).${NC}"
  echo -e "Verify that you can connect to: $AUTH_URL"
  exit 1
fi

# Validate auth
IS_ERROR=$(parse_json_val "$RESPONSE" "error")
if [ -n "$IS_ERROR" ] || [ -z "$RESPONSE" ]; then
  echo -e "${RED}${BOLD}❌ Error: Authentication failed. ${IS_ERROR:-"Gatekeeper returned empty response."}${NC}"
  exit 1
fi

echo -e "${GREEN}${BOLD}✅ Authentication successful!${NC}"
echo ""

# Extract metadata
GITHUB_TOKEN=$(parse_json_val "$RESPONSE" "github_token")
GITHUB_USER=$(parse_json_val "$RESPONSE" "github_user")
REPO_NAME=$(parse_json_val "$RESPONSE" "repo_name")

if [ -z "$GITHUB_TOKEN" ] || [ -z "$GITHUB_USER" ] || [ -z "$REPO_NAME" ]; then
  echo -e "${RED}${BOLD}❌ Error: Required metadata (tokens/user/repo) is missing in response.${NC}"
  exit 1
fi

# 3. Setting the workspace directory
CURRENT_DIR="$PWD"
DEFAULT_DIR="$HOME/my-ai-workspace"

echo -e "${YELLOW}${BOLD}[2/3] Setting workspace directory...${NC}"
if [ "$CURRENT_DIR" != "$HOME" ]; then
  WORKSPACE_DIR="$CURRENT_DIR"
else
  WORKSPACE_DIR="$DEFAULT_DIR"
fi

echo -e "Workspace directory set to: ${GREEN}$WORKSPACE_DIR${NC}"
mkdir -p "$WORKSPACE_DIR/projects"

# Generate master secrets file
echo -e "Writing secure local master .env file..."
write_agent_keys "$RESPONSE" "$WORKSPACE_DIR/.env"
echo "GITHUB_TOKEN=\"$GITHUB_TOKEN\"" >> "$WORKSPACE_DIR/.env"
echo "GITHUB_USER=\"$GITHUB_USER\"" >> "$WORKSPACE_DIR/.env"
chmod 600 "$WORKSPACE_DIR/.env"
echo -e "${GREEN}✅ Local secrets loaded and secured.${NC}"
echo ""

# 4. Clone or pull the core engine repository
echo -e "${YELLOW}${BOLD}[3/3] Syncing core engine repository...${NC}"
cd "$WORKSPACE_DIR"

if [ -d "$REPO_NAME" ]; then
  echo -e "Repository $REPO_NAME already exists. Pulling latest updates..."
  cd "$REPO_NAME"
  # Keep credentials temporarily in memory for git pull
  git pull "https://oauth2:${GITHUB_TOKEN}@github.com/${GITHUB_USER}/${REPO_NAME}.git"
  cd ..
else
  echo -e "Cloning private repository: github.com/${GITHUB_USER}/${REPO_NAME}..."
  git clone "https://oauth2:${GITHUB_TOKEN}@github.com/${GITHUB_USER}/${REPO_NAME}.git"
fi

if [ ! -d "$REPO_NAME" ]; then
  echo -e "${RED}${BOLD}❌ Error: Core engine cloning/pulling failed.${NC}"
  exit 1
fi
echo -e "${GREEN}✅ Core engine synced.${NC}"
echo ""

# 5. Delegate remainder of setup to modular script inside cloned repository
echo -e "${YELLOW}${BOLD}Delegating to repository setup manager...${NC}"
chmod +x "$WORKSPACE_DIR/$REPO_NAME/scripts/setup.sh"
if bash "$WORKSPACE_DIR/$REPO_NAME/scripts/setup.sh" "$WORKSPACE_DIR" "$REPO_NAME"; then
  echo ""
  echo -e "${BLUE}${BOLD}====================================================================${NC}"
  echo -e "${GREEN}${BOLD}🚀 Setup complete! Your workspace has been configured successfully.${NC}"
  echo -e "${CYAN}Workspace Root:${NC} $WORKSPACE_DIR"
  echo -e "${CYAN}Active Core Engine:${NC} $WORKSPACE_DIR/$REPO_NAME"
  echo ""
  echo -e "${YELLOW}To begin immediately, open a new terminal or run:${NC}"
  echo -e "  source ~/.bashrc  (or source ~/.zshrc)"
  echo -e "${YELLOW}Then, navigate to any folder and run:${NC}"
  echo -e "  start  (or agent-run)"
  echo -e "${BLUE}${BOLD}====================================================================${NC}"
else
  echo -e "${RED}${BOLD}❌ Error: Post-clone repository setup failed.${NC}"
  exit 1
fi

