#!/bin/bash

set -euo pipefail

if ! command -v jq &> /dev/null; then
  echo "❌ 'jq' is required but not installed."
  exit 1
fi

# Configuration
BASE_URL=${CASTAI_BASE_URL:-"https://api.cast.ai"}
API_KEY=${CASTAI_API_KEY:-""}
TF_OUTPUT_FILE="castai_runtime_rules.tf.example"
ENABLED_ONLY=false
DEPENDENCY_MODULE="module.castai-gke-cluster"

# Parse optional arguments
while [[ $# -gt 0 ]]; do
  case "$1" in
    --enabled-only)
      ENABLED_ONLY=true
      shift
      ;;
    *)
      echo "❌ Unknown option: $1"
      echo "Usage: $0 [--enabled-only]"
      exit 1
      ;;
  esac
done

# Check for API key
if [ -z "$API_KEY" ]; then
  echo "❌ Error: CASTAI_API_KEY environment variable not set."
  exit 1
fi

# Full API endpoint
ENDPOINT="$BASE_URL/v1/security/runtime/rules?search=&page.limit=5000&sort.field=severity&sort.order=desc"

echo "🔍 Fetching CAST AI Runtime Rules from: $ENDPOINT"

# Fetch data
response=$(curl -s "$ENDPOINT" \
  -H "Accept: application/json" \
  -H "X-API-Key: $API_KEY" \
  --fail -v)

if [ -z "$response" ]; then
  echo "❌ Failed to fetch data from CAST AI."
  exit 1
fi

if [ "$ENABLED_ONLY" = true ]; then
  rules=$(echo "$response" | jq '.rules | map(select(.enabled == true))')
else
  rules=$(echo "$response" | jq '.rules')
fi

# Count and print number of enabled rules
RULE_COUNT=$(echo "$rules" | jq 'length')
echo "✅ Found $RULE_COUNT rule(s)."

# Start new TF file
echo "# This file is autogenerated by fetch_castai_runtime_rules.sh" > "$TF_OUTPUT_FILE"

# Escape double quotes
escape_quotes() {
  echo "$1" | sed 's/"/\\"/g'
}

echo "$rules" | jq -c '.[]' | while read -r rule_json; do
  name=$(echo "$rule_json" | jq -r '.name')
  name_escaped=$(escape_quotes "$name")
  safe_name=$(echo "$name" | iconv -c -t ascii | tr '[:upper:]' '[:lower:]' | tr -c 'a-z0-9_' '_' | sed 's/^_*//')

  category=$(echo "$rule_json" | jq -r '.category')
  severity=$(echo "$rule_json" | jq -r '.severity')
  enabled=$(echo "$rule_json" | jq -r '.enabled')
  rule_text=$(echo "$rule_json" | jq -r '.ruleText // ""')
  resource_selector=$(echo "$rule_json" | jq -r '.resourceSelector // ""' | sed 's/[[:space:]]*$//')
  rule_engine_type=$(echo "$rule_json" | jq -r '.ruleEngineType')
  labels=$(echo "$rule_json" | jq -c '.labels // {}')

  cat >> "$TF_OUTPUT_FILE" <<EOF

resource "castai_security_runtime_rule" "$safe_name" {
  name              = "$name_escaped"
  category          = "$category"
  severity          = "$severity"
  enabled           = $enabled
  rule_text         = <<EOT
$rule_text
EOT
  rule_engine_type  = "$rule_engine_type"
EOF

  if [ -n "$resource_selector" ]; then
    cat >> "$TF_OUTPUT_FILE" <<EOF
  resource_selector = <<EOT
$resource_selector
EOT
EOF
  fi

  if [ "$labels" != "{}" ]; then
    echo "  labels = {" >> "$TF_OUTPUT_FILE"
    echo "$labels" | jq -r 'to_entries[] | "    \(.key) = \"\(.value | gsub("\""; "\\\""))\""' >> "$TF_OUTPUT_FILE"
    echo "  }" >> "$TF_OUTPUT_FILE"
  fi

  echo "  depends_on = [${DEPENDENCY_MODULE}]" >> "$TF_OUTPUT_FILE"
  echo "}" >> "$TF_OUTPUT_FILE"
done

# Print import commands
echo ""
echo "📝 Terraform resources written to: $TF_OUTPUT_FILE"
echo ""
echo "📦 Suggested Terraform import commands:"

rules_list=$(echo "$rules" | jq -r '.[].name')
count=$(echo "$rules_list" | wc -l | tr -d ' ')
current=0

echo "$rules_list" | while read -r name; do
  current=$((current + 1))
  safe_name=$(echo "$name" | iconv -c -t ascii | tr '[:upper:]' '[:lower:]' | tr -c 'a-z0-9_' '_' | sed 's/^_*//')
  if [ "$current" -lt "$count" ]; then
    echo "terraform import -var-file=tf.vars castai_security_runtime_rule.$safe_name \"$name\" &&"
  else
    echo "terraform import -var-file=tf.vars castai_security_runtime_rule.$safe_name \"$name\""
  fi
done
