#!/usr/bin/env bash
# Generate Phase 2 terraform.tfvars from Phase 1 outputs and .env file
# Usage: ./generate-phase2-tfvars.sh [output_file]

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
# Load .env via dotenv (RPC CR/LF trim). Fallback: raw source.
if [[ -f "$SCRIPT_DIR/../lib/deployment/dotenv.sh" ]]; then
  # shellcheck disable=SC1090
  source "$SCRIPT_DIR/../lib/deployment/dotenv.sh"
  load_deployment_env --repo-root "${PROJECT_ROOT:-$REPO_ROOT}"
elif [[ -n "${PROJECT_ROOT:-}" && -f "$PROJECT_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$PROJECT_ROOT/.env"
  set +a
elif [[ -n "${REPO_ROOT:-}" && -f "$REPO_ROOT/.env" ]]; then
  set -a
  # shellcheck disable=SC1090
  source "$REPO_ROOT/.env"
  set +a
fi
OUTPUT_FILE="${1:-${PROJECT_ROOT}/terraform/phases/phase2/terraform.tfvars}"

# Load .env if it exists
if [ -f "${PROJECT_ROOT}/.env" ]; then
    source "${PROJECT_ROOT}/.env"
fi

echo "Generating Phase 2 terraform.tfvars..."
echo "Output file: ${OUTPUT_FILE}"

# Check if we're in Phase 1 directory
cd "${PROJECT_ROOT}/terraform/phases/phase1"

# Get Phase 1 outputs
if ! terraform output -json phase1_us_regions > /tmp/phase1_outputs.json 2>/dev/null; then
    echo "Error: Cannot get Phase 1 outputs. Ensure Phase 1 is deployed and terraform is initialized."
    exit 1
fi

# Extract VM information from Phase 1 outputs
PHASE1_DATA=$(terraform output -json phase1_us_regions)

# Use .env variables with fallbacks
ENVIRONMENT="${ENVIRONMENT:-${TF_VAR_environment:-prod}}"
VM_ADMIN_USERNAME="${VM_ADMIN_USERNAME:-${TF_VAR_vm_admin_username:-besuadmin}}"
SSH_PRIVATE_KEY_PATH="${SSH_PRIVATE_KEY_PATH:-${TF_VAR_ssh_private_key_path:-}}"

if [ -z "$SSH_PRIVATE_KEY_PATH" ]; then
    echo "Warning: SSH_PRIVATE_KEY_PATH not set. Please set it in .env or provide as variable."
    echo "Example: SSH_PRIVATE_KEY_PATH=/path/to/private/key"
fi

# Generate terraform.tfvars
cat > "${OUTPUT_FILE}" <<EOF
# Phase 2 Terraform Variables
# Generated from Phase 1 outputs and .env file
# Generated: $(date)

environment = "${ENVIRONMENT}"
vm_admin_username = "${VM_ADMIN_USERNAME}"
ssh_private_key_path = "${SSH_PRIVATE_KEY_PATH}"

# Phase 1 VM information (auto-generated from Phase 1 outputs)
phase1_vm_info = {
EOF

# Extract region data and generate tfvars
echo "$PHASE1_DATA" | jq -r 'to_entries[] | 
  "  \(.key) = {
    vm_names    = \(.value.vm_names | tojson)
    private_ips = \(.value.private_ips | tojson)
    public_ips  = \(.value.public_ips | tojson)
    resource_group = \"\(.value.resource_group)\"
    region      = \"\(.value.region)\"
  }"' >> "${OUTPUT_FILE}"

cat >> "${OUTPUT_FILE}" <<EOF
}

# Docker compose source path (relative to this file)
docker_compose_source_path = "../../../docker/phase2"
EOF

echo "✅ Phase 2 terraform.tfvars generated successfully!"
echo "File: ${OUTPUT_FILE}"
echo ""
echo "Next steps:"
echo "1. Review the generated file: cat ${OUTPUT_FILE}"
echo "2. Update SSH_PRIVATE_KEY_PATH in .env if needed"
echo "3. Deploy Phase 2: cd terraform/phases/phase2 && terraform apply"

