#!/bin/bash
# generate-log-config.sh - Generate .env.logging from LOG_LEVEL
# Maps a single LOG_LEVEL environment variable to per-container settings
#
# Usage: ./generate-log-config.sh [LOG_LEVEL]
#   LOG_LEVEL: DEBUG, INFO, WARN, or ERROR (default: INFO)
#
# Output: Creates .env.logging file with container-specific log settings
#
# Exit codes:
#   0 - Configuration generated successfully
#   1 - Invalid LOG_LEVEL provided

set -euo pipefail

LOG_LEVEL="${1:-INFO}"

# Validate input
case "$LOG_LEVEL" in
  DEBUG|INFO|WARN|ERROR) ;;
  *)
    echo "Error: Invalid LOG_LEVEL '$LOG_LEVEL'. Must be DEBUG, INFO, WARN, or ERROR." >&2
    exit 1
    ;;
esac

# Convert to lowercase for services that need it
LOG_LEVEL_LOWER=$(echo "$LOG_LEVEL" | tr '[:upper:]' '[:lower:]')

# Map PostgreSQL log settings based on level
case "$LOG_LEVEL" in
  DEBUG) POSTGRES_LOG_STATEMENT="all"; POSTGRES_LOG_MIN_DURATION="0" ;;
  INFO)  POSTGRES_LOG_STATEMENT="ddl"; POSTGRES_LOG_MIN_DURATION="500" ;;
  WARN)  POSTGRES_LOG_STATEMENT="none"; POSTGRES_LOG_MIN_DURATION="1000" ;;
  ERROR) POSTGRES_LOG_STATEMENT="none"; POSTGRES_LOG_MIN_DURATION="-1" ;;
esac

# Map Redis log level
case "$LOG_LEVEL" in
  DEBUG) REDIS_LOGLEVEL="debug" ;;
  INFO)  REDIS_LOGLEVEL="verbose" ;;
  WARN)  REDIS_LOGLEVEL="notice" ;;
  ERROR) REDIS_LOGLEVEL="warning" ;;
esac

# Generate .env.logging file
cat > .env.logging << EOF
# Generated by generate-log-config.sh - DO NOT EDIT MANUALLY
# Regenerate with: ./scripts/ci/generate-log-config.sh $LOG_LEVEL
LOG_LEVEL=$LOG_LEVEL

# Backend/OCR (Pino)
BACKEND_LOG_LEVEL=$LOG_LEVEL_LOWER

# Frontend (Vite)
VITE_LOG_LEVEL=$LOG_LEVEL_LOWER

# PostgreSQL
POSTGRES_LOG_STATEMENT=$POSTGRES_LOG_STATEMENT
POSTGRES_LOG_MIN_DURATION=$POSTGRES_LOG_MIN_DURATION

# Redis
REDIS_LOGLEVEL=$REDIS_LOGLEVEL

# Traefik
TRAEFIK_LOG_LEVEL=$LOG_LEVEL
EOF

echo "Generated .env.logging with LOG_LEVEL=$LOG_LEVEL"
