#!/bin/bash
#
# Phase 1: Prerequisites
# Development environment setup and validation
#

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/config.sh"

log_info "=========================================="
log_info "Phase 1: Prerequisites"
log_info "=========================================="

# 1.1 Development Environment Setup
log_step "1.1 Checking development environment..."

check_prerequisites

# Check Node.js version
NODE_VERSION=$(node --version | cut -d'v' -f2 | cut -d'.' -f1)
if [ "${NODE_VERSION}" -lt 18 ]; then
  error_exit "Node.js version 18 or higher is required. Current: $(node --version)"
fi
log_success "Node.js version: $(node --version)"

# Check pnpm version
PNPM_VERSION=$(pnpm --version | cut -d'.' -f1)
if [ "${PNPM_VERSION}" -lt 8 ]; then
  error_exit "pnpm version 8 or higher is required. Current: $(pnpm --version)"
fi
log_success "pnpm version: $(pnpm --version)"

# Check Terraform version
TERRAFORM_VERSION=$(terraform version -json | jq -r '.terraform_version' | cut -d'.' -f1)
if [ "${TERRAFORM_VERSION}" -lt 1 ]; then
  error_exit "Terraform version 1.5.0 or higher is required"
fi
log_success "Terraform version: $(terraform version -json | jq -r '.terraform_version')"

log_success "All tools verified"

# 1.2 Azure Account Setup
log_step "1.2 Setting up Azure account..."

check_azure_login

if [ -z "${AZURE_SUBSCRIPTION_ID}" ]; then
  log_warning "AZURE_SUBSCRIPTION_ID not set. Using current subscription."
  AZURE_SUBSCRIPTION_ID=$(az account show --query id -o tsv)
fi

az account set --subscription "${AZURE_SUBSCRIPTION_ID}" || error_exit "Failed to set subscription"

SUBSCRIPTION_NAME=$(az account show --query name -o tsv)
log_success "Using Azure subscription: ${SUBSCRIPTION_NAME} (${AZURE_SUBSCRIPTION_ID})"

# Verify permissions
log_step "Checking Azure permissions..."
ROLE=$(az role assignment list --assignee "$(az account show --query user.name -o tsv)" --query "[0].roleDefinitionName" -o tsv 2>/dev/null || echo "Unknown")
if [[ "${ROLE}" != *"Contributor"* ]] && [[ "${ROLE}" != *"Owner"* ]]; then
  log_warning "Current role: ${ROLE}. Contributor or Owner role recommended."
else
  log_success "Permissions verified: ${ROLE}"
fi

# 1.3 Install Dependencies
log_step "1.3 Installing dependencies..."

cd "${PROJECT_ROOT}"

if [ ! -d "node_modules" ]; then
  log_info "Installing dependencies with pnpm..."
  pnpm install --frozen-lockfile || error_exit "Failed to install dependencies"
  log_success "Dependencies installed"
else
  log_info "Dependencies already installed, skipping..."
fi

# 1.4 Build Packages
log_step "1.4 Building packages..."

if [ "${SKIP_BUILD:-false}" != "true" ]; then
  log_info "Building all packages..."
  pnpm build || error_exit "Failed to build packages"
  log_success "All packages built"
else
  log_info "Skipping build (SKIP_BUILD=true)"
fi

# 1.5 Initialize Git Submodules (if any)
log_step "1.5 Initializing git submodules..."

if [ -f "${PROJECT_ROOT}/.gitmodules" ]; then
  git submodule update --init --recursive || log_warning "Failed to update submodules"
  log_success "Git submodules initialized"
else
  log_info "No git submodules found"
fi

# Save state
save_state "phase1" "complete"

log_success "=========================================="
log_success "Phase 1: Prerequisites - COMPLETE"
log_success "=========================================="

