#!/usr/bin/env bash
# Phase 2: Foundation Infrastructure - Terraform Setup
# This script prepares Terraform for deployment

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 "Phase 2: Foundation Infrastructure"

# 2.1 Terraform Initialization
section "2.1 Terraform Initialization"
cd "$TERRAFORM_DIR" || error "Failed to change to terraform directory"

# Check Terraform installation
if ! command -v terraform &> /dev/null; then
    error "Terraform is not installed. Install from: https://www.terraform.io/downloads"
fi

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

# Check backend configuration
info "Checking Terraform backend configuration..."
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}"
else
    warn "Terraform backend not fully configured"
    info "Required: ARM_STORAGE_ACCOUNT_NAME, ARM_ACCESS_KEY"
    info "Run: ./scripts/deployment/populate-env.sh"
fi

# Initialize Terraform
if [ ! -d ".terraform" ]; then
    info "Initializing Terraform..."
    terraform init
    log "Terraform initialized"
else
    log "Terraform already initialized"
    info "Running terraform init -upgrade..."
    terraform init -upgrade
fi

# 2.2 Terraform Configuration
section "2.2 Terraform Configuration"
if [ -f "terraform.tfvars" ]; then
    log "terraform.tfvars exists"
    info "Current configuration:"
    grep -E "^(environment|location|cluster_name|use_well_architected)" terraform.tfvars || true
else
    warn "terraform.tfvars not found"
    if [ -f "terraform.tfvars.example" ]; then
        info "Copying from terraform.tfvars.example..."
        cp terraform.tfvars.example terraform.tfvars
        log "Created terraform.tfvars from example"
        warn "Please review and update terraform.tfvars with your values"
    else
        error "terraform.tfvars.example not found"
    fi
fi

# 2.3 Resource Groups (Preview)
section "2.3 Resource Groups"
info "Resource groups will be created by Terraform"
info "Preview of resource group names (using naming convention):"
info "  - Network: az-p-we-rg-net-001"
info "  - Compute: az-p-we-rg-comp-001"
info "  - Storage: az-p-we-rg-stor-001"
info "  - Security: az-p-we-rg-sec-001"

# 2.4 Terraform Planning
section "2.4 Terraform Planning"
info "Running terraform plan to preview changes..."
if terraform plan -out=tfplan 2>&1 | tee /tmp/terraform-plan.log; then
    log "Terraform plan completed successfully"
    info "Plan saved to: tfplan"
    info "Review the plan output above"
    warn "To apply: terraform apply tfplan"
else
    error "Terraform plan failed. Check errors above."
fi

section "Phase 2 Complete"
log "Terraform is ready for deployment"
info "Next steps:"
info "1. Review terraform plan output"
info "2. If satisfied, run: terraform apply tfplan"
info "3. Or continue to Phase 3: Networking Infrastructure"

