#!/usr/bin/env bash
set -euo pipefail

# scripts/generate_env.sh
# Interactive generator for .env from .env.example
# Usage: ./scripts/generate_env.sh [--yes]

BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
EXAMPLE="$BASE_DIR/.env.example"
TARGET="$BASE_DIR/.env"

confirm=false
if [[ "${1:-}" == "--yes" ]]; then
  confirm=true
fi

if [[ ! -f "$EXAMPLE" ]]; then
  echo "Error: .env.example not found at $EXAMPLE"
  exit 1
fi

echo "Generating $TARGET from $EXAMPLE"

if [[ -f "$TARGET" && "$confirm" = false ]]; then
  read -p "$TARGET exists. Overwrite? (y/N): " ans
  case "$ans" in
    [Yy]*) ;;
    *) echo "Aborted"; exit 0;;
  esac
fi

# Copy example first
cp "$EXAMPLE" "$TARGET"

# For each variable in example, prompt the user to keep or change
while IFS= read -r line; do
  if [[ "$line" =~ ^# ]] || [[ -z "$line" ]]; then
    continue
  fi
  key=$(echo "$line" | cut -d= -f1)
  val=$(echo "$line" | cut -d= -f2-)
  # Trim
  key=$(echo "$key" | xargs)
  val=$(echo "$val" | xargs)

  current=$(grep -E "^$key=" "$TARGET" || true)
  current_val=""
  if [[ -n "$current" ]]; then
    current_val=$(echo "$current" | cut -d= -f2-)
  fi

  if [[ "$confirm" = true ]]; then
    # non-interactive: keep example defaults or environment overrides
    if [[ -n "${!key-}" ]]; then
      new_val="${!key}"
      sed -i "s|^$key=.*|$key=$new_val|" "$TARGET"
    fi
    continue
  fi

  read -p "$key [$current_val]: " new_val
  if [[ -n "$new_val" ]]; then
    sed -i "s|^$key=.*|$key=$new_val|" "$TARGET"
  fi

done < <(grep -E '^[A-Z0-9_]+=.*' "$EXAMPLE")

echo "Written $TARGET"

echo "You can re-run this script with --yes to auto-fill from environment variables."
