#!/usr/bin/env bash
# Initialize Terraform with proper backend configuration
# This script helps initialize Terraform with Azure backend

set -euo pipefail


SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"
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
TERRAFORM_DIR="$PROJECT_ROOT/terraform"

log() {
    log_success "[✓] $1"
}

error() {
    log_error "[✗] $1"
    exit 1
}

warn() {
    log_warn "[!] $1"
}

info() {
    log_info "[i] $1"
}

section() {
    echo
    log_info "=== $1 ==="
}

section "Terraform Initialization"

# Check Terraform
if ! command -v terraform &> /dev/null; then
    error "Terraform is not installed. Run: ./scripts/setup/install-terraform.sh"
fi

log "Terraform version: $(terraform version | head -n 1)"

# Check Azure authentication
if ! az account show &> /dev/null; then
    error "Not logged in to Azure. Run: az login"
fi

log "Azure authentication verified"

# Load environment variables
if [ -f "$PROJECT_ROOT/.env" ]; then
    source "$PROJECT_ROOT/.env"
    log ".env file loaded"
else
    warn ".env file not found"
fi

# Check backend configuration
section "Backend Configuration"
cd "$TERRAFORM_DIR" || error "Failed to change to terraform directory"

if [ -n "${ARM_STORAGE_ACCOUNT_NAME:-}" ] && [ -n "${ARM_ACCESS_KEY:-}" ]; then
    log "Terraform backend configured via environment variables"
    info "Storage Account: $ARM_STORAGE_ACCOUNT_NAME"
    info "Container: ${ARM_CONTAINER_NAME:-tfstate}"
    info "Resource Group: ${ARM_RESOURCE_GROUP_NAME:-tfstate-rg}"
else
    warn "Terraform backend not fully configured"
    info "Required environment variables:"
    info "  - ARM_STORAGE_ACCOUNT_NAME"
    info "  - ARM_ACCESS_KEY"
    info "  - ARM_CONTAINER_NAME (optional, defaults to tfstate)"
    info "  - ARM_RESOURCE_GROUP_NAME (optional, defaults to tfstate-rg)"
    info ""
    info "Run: ./scripts/deployment/populate-env.sh"
    info "Or create storage account manually and set variables"
    
    # Offer to create storage account
    read -p "Do you want to create Terraform backend storage account now? (y/n): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        info "Creating Terraform backend storage..."
        "$PROJECT_ROOT/scripts/deployment/populate-env.sh"
    else
        error "Terraform backend must be configured before initialization"
    fi
fi

# Initialize Terraform
section "Initializing Terraform"
if [ -d ".terraform" ]; then
    warn "Terraform already initialized"
    read -p "Re-initialize? (y/n): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        info "Re-initializing Terraform..."
        terraform init -reconfigure
    else
        info "Running terraform init -upgrade..."
        terraform init -upgrade
    fi
else
    info "Initializing Terraform..."
    terraform init
fi

if [ $? -eq 0 ]; then
    log "Terraform initialized successfully"
else
    error "Terraform initialization failed"
fi

# Verify initialization
section "Verification"
if [ -d ".terraform" ]; then
    log "Terraform working directory exists"
    
    # Check providers
    info "Checking providers..."
    terraform providers || warn "Provider check failed"
    
    # Show backend configuration
    info "Backend configuration:"
    terraform show -backend-config 2>/dev/null || info "Backend config not available"
else
    error "Terraform initialization appears to have failed"
fi

section "Initialization Complete"
log "Terraform is ready for planning"
info "Next steps:"
info "1. Review configuration: cat terraform.tfvars"
info "2. Plan deployment: terraform plan -out=tfplan"
info "3. Review plan output"
info "4. Apply when ready: terraform apply tfplan"

