#!/bin/bash
#
# Phase 13: Monitoring & Observability
# Configure Application Insights, Log Analytics, alerts, dashboards
#

set -euo pipefail

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

log_info "=========================================="
log_info "Phase 13: Monitoring & Observability"
log_info "=========================================="

# 13.1 Application Insights
log_step "13.1 Creating Application Insights..."

APP_INSIGHTS_NAME="${PROJECT_NAME}-${ENVIRONMENT}-ai"
APP_INSIGHTS_EXISTS=$(az monitor app-insights component show \
  --app "${APP_INSIGHTS_NAME}" \
  --resource-group "${AKS_RESOURCE_GROUP}" \
  --query name -o tsv 2>/dev/null || echo "")

if [ -z "${APP_INSIGHTS_EXISTS}" ]; then
  log_info "Creating Application Insights resource..."
  az monitor app-insights component create \
    --app "${APP_INSIGHTS_NAME}" \
    --location "${AZURE_REGION}" \
    --resource-group "${AKS_RESOURCE_GROUP}" \
    --application-type web \
    || log_warning "Failed to create Application Insights"
else
  log_success "Application Insights already exists"
fi

# Get instrumentation key
INSTRUMENTATION_KEY=$(az monitor app-insights component show \
  --app "${APP_INSIGHTS_NAME}" \
  --resource-group "${AKS_RESOURCE_GROUP}" \
  --query instrumentationKey -o tsv 2>/dev/null || echo "")

if [ -n "${INSTRUMENTATION_KEY}" ]; then
  log_info "Storing instrumentation key in Key Vault..."
  az keyvault secret set \
    --vault-name "${KEY_VAULT_NAME}" \
    --name "app-insights-instrumentation-key" \
    --value "${INSTRUMENTATION_KEY}" \
    || log_warning "Failed to store instrumentation key"
fi

# 13.2 Log Analytics Workspace
log_step "13.2 Creating Log Analytics workspace..."

LOG_ANALYTICS_NAME="${PROJECT_NAME}-${ENVIRONMENT}-logs"
LOG_ANALYTICS_EXISTS=$(az monitor log-analytics workspace show \
  --workspace-name "${LOG_ANALYTICS_NAME}" \
  --resource-group "${AKS_RESOURCE_GROUP}" \
  --query name -o tsv 2>/dev/null || echo "")

if [ -z "${LOG_ANALYTICS_EXISTS}" ]; then
  log_info "Creating Log Analytics workspace..."
  az monitor log-analytics workspace create \
    --workspace-name "${LOG_ANALYTICS_NAME}" \
    --resource-group "${AKS_RESOURCE_GROUP}" \
    --location "${AZURE_REGION}" \
    || log_warning "Failed to create Log Analytics workspace"
else
  log_success "Log Analytics workspace already exists"
fi

log_info "Monitoring configuration complete"
log_info "Next steps (manual):"
log_info "  1. Configure alerts in Azure Portal"
log_info "  2. Set up Grafana dashboards"
log_info "  3. Configure log queries"
log_info "  4. Set up notification channels"

# Save state
save_state "phase13" "complete"

log_success "=========================================="
log_success "Phase 13: Monitoring & Observability - COMPLETE"
log_success "=========================================="

