#!/bin/bash
set -e

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

# Configuration
PROJECT_ID="cim-summarizer"
REGION="us-central1"
BACKEND_SERVICE_NAME="cim-processor-backend"
FRONTEND_SERVICE_NAME="cim-processor-frontend"

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Function to check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Function to check prerequisites
check_prerequisites() {
    print_status "Checking prerequisites..."
    
    if ! command_exists gcloud; then
        print_error "gcloud CLI is not installed. Please install it first."
        exit 1
    fi
    
    if ! command_exists firebase; then
        print_error "Firebase CLI is not installed. Please install it first."
        exit 1
    fi
    
    if ! command_exists docker; then
        print_warning "Docker is not installed. Cloud Run deployment will not be available."
    fi
    
    print_success "Prerequisites check completed"
}

# Function to authenticate with Google Cloud
authenticate_gcloud() {
    print_status "Authenticating with Google Cloud..."
    
    # Check if already authenticated
    if gcloud auth list --filter=status:ACTIVE --format="value(account)" | grep -q .; then
        print_success "Already authenticated with Google Cloud"
    else
        gcloud auth login
        gcloud config set project $PROJECT_ID
        print_success "Google Cloud authentication completed"
    fi
}

# Function to deploy backend
deploy_backend() {
    local deployment_type=$1
    
    print_status "Deploying backend using $deployment_type..."
    
    cd backend
    
    case $deployment_type in
        "firebase")
            print_status "Building backend for Firebase Functions..."
            npm run build
            
            print_status "Deploying to Firebase Functions..."
            firebase deploy --only functions
            ;;
        "cloud-run")
            if ! command_exists docker; then
                print_error "Docker is required for Cloud Run deployment"
                exit 1
            fi
            
            print_status "Building Docker image..."
            docker build -t gcr.io/$PROJECT_ID/$BACKEND_SERVICE_NAME:latest .
            
            print_status "Pushing Docker image to Container Registry..."
            docker push gcr.io/$PROJECT_ID/$BACKEND_SERVICE_NAME:latest
            
            print_status "Deploying to Cloud Run..."
            gcloud run deploy $BACKEND_SERVICE_NAME \
                --image gcr.io/$PROJECT_ID/$BACKEND_SERVICE_NAME:latest \
                --region $REGION \
                --platform managed \
                --allow-unauthenticated \
                --memory 4Gi \
                --cpu 2 \
                --timeout 300 \
                --concurrency 80
            ;;
        *)
            print_error "Unknown deployment type: $deployment_type"
            exit 1
            ;;
    esac
    
    cd ..
    print_success "Backend deployment completed"
}

# Function to deploy frontend
deploy_frontend() {
    print_status "Deploying frontend..."
    
    cd frontend
    
    print_status "Building frontend..."
    npm run build
    
    print_status "Deploying to Firebase Hosting..."
    firebase deploy --only hosting
    
    cd ..
    print_success "Frontend deployment completed"
}

# Function to run tests
run_tests() {
    print_status "Running tests..."
    
    # Backend tests
    cd backend
    print_status "Running backend tests..."
    npm test
    cd ..
    
    # Frontend tests
    cd frontend
    print_status "Running frontend tests..."
    npm test
    cd ..
    
    print_success "All tests completed"
}

# Function to show usage
show_usage() {
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  -b, --backend TYPE     Deploy backend (firebase|cloud-run|both)"
    echo "  -f, --frontend         Deploy frontend"
    echo "  -t, --test             Run tests before deployment"
    echo "  -a, --all              Deploy everything (backend to Cloud Run + frontend)"
    echo "  -h, --help             Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 -b firebase         Deploy backend to Firebase Functions"
    echo "  $0 -b cloud-run        Deploy backend to Cloud Run"
    echo "  $0 -f                  Deploy frontend to Firebase Hosting"
    echo "  $0 -a                  Deploy everything"
    echo "  $0 -t -b firebase      Run tests and deploy backend to Firebase"
}

# Main script
main() {
    local deploy_backend_type=""
    local deploy_frontend=false
    local run_tests_flag=false
    
    # Parse command line arguments
    while [[ $# -gt 0 ]]; do
        case $1 in
            -b|--backend)
                deploy_backend_type="$2"
                shift 2
                ;;
            -f|--frontend)
                deploy_frontend=true
                shift
                ;;
            -t|--test)
                run_tests_flag=true
                shift
                ;;
            -a|--all)
                deploy_backend_type="cloud-run"
                deploy_frontend=true
                shift
                ;;
            -h|--help)
                show_usage
                exit 0
                ;;
            *)
                print_error "Unknown option: $1"
                show_usage
                exit 1
                ;;
        esac
    done
    
    # If no options specified, show usage
    if [[ -z "$deploy_backend_type" && "$deploy_frontend" == false ]]; then
        show_usage
        exit 1
    fi
    
    print_status "Starting deployment process..."
    
    # Check prerequisites
    check_prerequisites
    
    # Authenticate with Google Cloud
    authenticate_gcloud
    
    # Run tests if requested
    if [[ "$run_tests_flag" == true ]]; then
        run_tests
    fi
    
    # Deploy backend
    if [[ -n "$deploy_backend_type" ]]; then
        deploy_backend "$deploy_backend_type"
    fi
    
    # Deploy frontend
    if [[ "$deploy_frontend" == true ]]; then
        deploy_frontend
    fi
    
    print_success "Deployment process completed successfully!"
    
    # Show deployment URLs
    if [[ -n "$deploy_backend_type" ]]; then
        case $deploy_backend_type in
            "firebase")
                print_status "Backend deployed to Firebase Functions"
                ;;
            "cloud-run")
                print_status "Backend deployed to Cloud Run"
                gcloud run services describe $BACKEND_SERVICE_NAME --region=$REGION --format="value(status.url)"
                ;;
        esac
    fi
    
    if [[ "$deploy_frontend" == true ]]; then
        print_status "Frontend deployed to Firebase Hosting"
        firebase hosting:sites:list
    fi
}

# Run main function with all arguments
main "$@" 