#!/usr/bin/env bash
# Complete Phase 2: Foundation Infrastructure
# This script completes all Phase 2 tasks

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

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 - Complete"

# 2.1 Terraform Initialization
section "2.1 Terraform Initialization"
if [ -f "$PROJECT_ROOT/scripts/deployment/init-terraform.sh" ]; then
    info "Running Terraform initialization..."
    "$PROJECT_ROOT/scripts/deployment/init-terraform.sh"
else
    warn "Terraform initialization script not found"
    info "Manual steps:"
    info "1. Install Terraform: ./scripts/setup/install-terraform.sh"
    info "2. Configure backend in .env"
    info "3. Run: cd terraform && terraform init"
fi

# 2.2 Terraform Configuration (already done)
section "2.2 Terraform Configuration"
if [ -f "$PROJECT_ROOT/terraform/terraform.tfvars" ]; then
    log "terraform.tfvars exists and configured"
    info "Configuration summary:"
    grep -E "^(environment|location|cluster_name|use_well_architected)" "$PROJECT_ROOT/terraform/terraform.tfvars | head -5"
else
    error "terraform.tfvars not found"
fi

# 2.3 Resource Groups (will be created by Terraform)
section "2.3 Resource Groups"
info "Resource groups will be created by Terraform apply"
info "Expected resource groups (using naming convention):"
info "  - Compute: az-p-we-rg-comp-001"
info "  - Network: az-p-we-rg-net-001 (if using Well-Architected)"
info "  - Storage: az-p-we-rg-stor-001 (if using Well-Architected)"
info "  - Security: az-p-we-rg-sec-001 (if using Well-Architected)"

# 2.4 Terraform Planning
section "2.4 Terraform Planning"
TERRAFORM_DIR="$PROJECT_ROOT/terraform"
cd "$TERRAFORM_DIR" || error "Failed to change to terraform directory"

if command -v terraform &> /dev/null; then
    if [ -d ".terraform" ]; then
        info "Running terraform plan..."
        if terraform plan -out=tfplan 2>&1 | tee /tmp/terraform-plan.log; then
            log "Terraform plan completed"
            info "Plan saved to: tfplan"
            info "Plan log saved to: /tmp/terraform-plan.log"
            
            # Show summary
            info "Plan summary:"
            grep -E "(Plan:|to add|to change|to destroy)" /tmp/terraform-plan.log | tail -5 || true
            
            warn "Review the plan before applying"
            info "To apply: terraform apply tfplan"
        else
            error "Terraform plan failed. Check errors above."
        fi
    else
        warn "Terraform not initialized. Run: ./scripts/deployment/init-terraform.sh"
    fi
else
    warn "Terraform not installed. Run: ./scripts/setup/install-terraform.sh"
fi

section "Phase 2 Summary"
log "Configuration: ✅ Complete"
log "Terraform files: ✅ Ready"
if [ -f "$TERRAFORM_DIR/tfplan" ]; then
    log "Terraform plan: ✅ Generated"
    info "Ready for: terraform apply tfplan"
else
    warn "Terraform plan: ⏳ Pending"
    info "Run: cd terraform && terraform plan"
fi

info "Next: Phase 3 - Networking Infrastructure (after terraform apply)"

