#!/bin/bash

# SAR CLI - Quick command-line interface for Sovereign AI Router
# Usage: sar "your question here"

SAR_HOME="${SAR_HOME:-$HOME/.sar}"
JWT_SECRET=$(grep JWT_SECRET "$SAR_HOME/.env" 2>/dev/null | cut -d'=' -f2)
SAR_URL="${SAR_URL:-http://localhost:3000/v1/chat/completions}"

if [ -z "$JWT_SECRET" ]; then
  echo "❌ JWT_SECRET not found. Is SAR deployed? Run: ./deploy-prod.sh"
  exit 1
fi

# Generate JWT token (15 min expiry)
TOKEN=$(node -e "console.log(require('jsonwebtoken').sign({sub:'user',role:'user'}, '$JWT_SECRET',{expiresIn:'15m'}))" 2>/dev/null)

if [ $# -eq 0 ]; then
  echo "SAR CLI - Sovereign AI Router"
  echo "Usage: sar \"your question or prompt\""
  echo ""
  echo "Examples:"
  echo "  sar \"What's the weather in Denver?\""
  echo "  sar \"Explain quantum computing\""
  echo "  sar \"Write a Python function to sort a list\""
  echo ""
  echo "Options:"
  echo "  --model MODEL    Use specific model (auto, gpt-4o, claude-3-haiku, llama)"
  echo "  --stream         Stream response as it arrives"
  echo "  --save FILE      Save conversation to file"
  echo "  --system MSG     Set system message"
  exit 0
fi

# Parse arguments
MODEL="auto"
STREAM=false
SAVE_FILE=""
SYSTEM_MSG="You are a helpful AI assistant that provides accurate, concise responses."

while [[ $# -gt 0 ]]; do
  case $1 in
    --model)
      MODEL="$2"
      shift 2
      ;;
    --stream)
      STREAM=true
      shift
      ;;
    --save)
      SAVE_FILE="$2"
      shift 2
      ;;
    --system)
      SYSTEM_MSG="$2"
      shift 2
      ;;
    -*)
      echo "Unknown option: $1"
      exit 1
      ;;
    *)
      PROMPT="$*"
      break
      ;;
  esac
done

if [ -z "$PROMPT" ]; then
  echo "❌ No prompt provided"
  exit 1
fi

# Build JSON payload
PAYLOAD=$(cat <<EOF
{
  "model": "$MODEL",
  "messages": [
    {"role": "system", "content": "$SYSTEM_MSG"},
    {"role": "user", "content": "$PROMPT"}
  ],
  "stream": $STREAM
}
EOF
)

# Make request
if [ "$STREAM" = true ]; then
  # Streaming mode (SSE)
  curl -s -X POST "$SAR_URL" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d "$PAYLOAD" | while IFS= read -r line; do
    if [[ $line == data:* ]]; then
      CONTENT="${line#data: }"
      if [ "$CONTENT" != "[DONE]" ]; then
        echo -n "$CONTENT" | jq -r '.choices[0].delta.content // empty' 2>/dev/null
      fi
    fi
  done
else
  # Standard request
  RESPONSE=$(curl -s -X POST "$SAR_URL" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d "$PAYLOAD")
  
  # Check for errors
  if echo "$RESPONSE" | jq -e '.error' >/dev/null 2>&1; then
    echo "❌ Error: $(echo "$RESPONSE" | jq -r '.error.message')"
    exit 1
  fi
  
  # Extract response content
  CONTENT=$(echo "$RESPONSE" | jq -r '.choices[0].message.content')
  
  # Output response
  echo "$CONTENT"
  
  # Save to file if requested
  if [ -n "$SAVE_FILE" ]; then
    echo "$CONTENT" > "$SAVE_FILE"
    echo ""
    echo "💾 Saved to: $SAVE_FILE"
  fi
fi