#!/bin/bash

# ============================================================================
# POUNCE HTTP DEPLOY (Backup method when SSH is unavailable)
#
# This uses the /api/v1/deploy endpoint to trigger deployments remotely.
# Requires the internal API key to be configured in the backend.
# ============================================================================

set -euo pipefail

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

# Configuration
API_URL="https://pounce.ch/api/v1"
DEPLOY_KEY="${POUNCE_DEPLOY_KEY:-}"

# Check if deploy key is set
if [ -z "$DEPLOY_KEY" ]; then
    echo -e "${RED}Error: POUNCE_DEPLOY_KEY environment variable not set${NC}"
    echo ""
    echo "Set your deploy key:"
    echo "  export POUNCE_DEPLOY_KEY=your-internal-api-key"
    echo ""
    echo "The key should match the 'internal_api_key' in your backend .env file"
    exit 1
fi

show_help() {
    echo -e "${CYAN}Pounce HTTP Deploy${NC}"
    echo ""
    echo "Usage: ./deploy-http.sh [component]"
    echo ""
    echo "Components:"
    echo "  all      Deploy both backend and frontend (default)"
    echo "  backend  Deploy backend only"
    echo "  frontend Deploy frontend only"
    echo "  status   Check last deployment status"
    echo ""
}

trigger_deploy() {
    local component="${1:-all}"
    
    echo -e "${CYAN}Triggering deployment for: $component${NC}"
    
    response=$(curl -s -X POST "$API_URL/deploy/trigger" \
        -H "Content-Type: application/json" \
        -H "X-Deploy-Key: $DEPLOY_KEY" \
        -d "{\"component\": \"$component\", \"git_pull\": true}")
    
    if echo "$response" | grep -q '"status":"started"'; then
        echo -e "${GREEN}✓ Deployment started${NC}"
        echo "$response" | python3 -m json.tool 2>/dev/null || echo "$response"
        
        echo ""
        echo -e "${YELLOW}Deployment running in background...${NC}"
        echo "Check status with: ./deploy-http.sh status"
    else
        echo -e "${RED}✗ Failed to trigger deployment${NC}"
        echo "$response"
        exit 1
    fi
}

check_status() {
    echo -e "${CYAN}Checking deployment status...${NC}"
    
    response=$(curl -s "$API_URL/deploy/status" \
        -H "X-Deploy-Key: $DEPLOY_KEY")
    
    if echo "$response" | grep -q '"status"'; then
        echo "$response" | python3 -m json.tool 2>/dev/null || echo "$response"
    else
        echo -e "${RED}✗ Failed to get status${NC}"
        echo "$response"
        exit 1
    fi
}

# Main
case "${1:-all}" in
    help|-h|--help)
        show_help
        ;;
    status)
        check_status
        ;;
    *)
        trigger_deploy "$1"
        ;;
esac
