#!/usr/bin/env bash
# Generate .env files for root, api/, and web/.
# Requires colors.sh to be sourced first.
# Expects the following variables to be set by the wizard:
#   admin_email, admin_password, admin_name, org_name
#   llm_provider, llm_api_key
#   slack_bot_token, slack_app_token, slack_channel  (optional)

# ---------------------------------------------------------------------------
# Key generation helpers
# ---------------------------------------------------------------------------
gen_hex()    { openssl rand -hex "$1" 2>/dev/null; }
gen_alphanum() {
  # N printable ASCII alphanumeric chars.
  # The tr|head pipeline ends with SIGPIPE on tr when head closes early;
  # '|| true' prevents pipefail from treating exit-141 as a script error.
  LC_ALL=C tr -dc 'A-Za-z0-9' </dev/urandom 2>/dev/null | head -c "$1" || true
}

gen_fernet_key() {
  # Fernet key = URL-safe base64 of 32 random bytes (44 chars with padding)
  # Try python3 first (available on most systems); fallback keeps the '=' padding.
  python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())" 2>/dev/null \
    || openssl rand -base64 32 | tr '+/' '-_'
}

# ---------------------------------------------------------------------------
# Root .env  (consumed by docker-compose)
# ---------------------------------------------------------------------------
write_root_env() {
  info "Writing root .env..."

  POSTGRES_PASSWORD="$(gen_alphanum 24)"
  MINIO_PASSWORD="$(gen_alphanum 24)"
  LANGFUSE_SECRET="$(gen_hex 32)"
  LANGFUSE_SALT="$(gen_hex 20)"
  # Langfuse requires exactly 64 hex chars
  LANGFUSE_ENC_KEY="$(gen_hex 32)"

  export POSTGRES_PASSWORD MINIO_PASSWORD LANGFUSE_SECRET LANGFUSE_SALT LANGFUSE_ENC_KEY

  cat >"$REPO_ROOT/.env" <<EOF
# Generated by install.sh — do not edit by hand unless you know what you're doing.

POSTGRES_USER=synkora
POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
POSTGRES_DB=synkora

MINIO_ROOT_USER=minioadmin
MINIO_ROOT_PASSWORD=${MINIO_PASSWORD}

LANGFUSE_NEXTAUTH_SECRET=${LANGFUSE_SECRET}
LANGFUSE_SALT=${LANGFUSE_SALT}
LANGFUSE_ENCRYPTION_KEY=${LANGFUSE_ENC_KEY}
LANGFUSE_REDIS_PASSWORD=$(gen_alphanum 20)
EOF

  success "Root .env written"
}

# ---------------------------------------------------------------------------
# api/.env  (all required overrides + copy remaining defaults from .env.example)
# ---------------------------------------------------------------------------
write_api_env() {
  info "Writing api/.env..."

  SECRET_KEY="$(gen_hex 32)"
  JWT_SECRET_KEY="$(gen_hex 32)"
  ENCRYPTION_KEY="$(gen_fernet_key)"

  export SECRET_KEY JWT_SECRET_KEY ENCRYPTION_KEY

  local OPENAI_KEY=""
  local ANTHROPIC_KEY=""
  case "$llm_provider" in
    openai)    OPENAI_KEY="$llm_api_key" ;;
    anthropic) ANTHROPIC_KEY="$llm_api_key" ;;
  esac

  # Start from example, then override
  if [ -f "$REPO_ROOT/api/.env.example" ]; then
    cp "$REPO_ROOT/api/.env.example" "$REPO_ROOT/api/.env"
  fi

  # Overwrite / append critical vars (using a here-doc appended after the example)
  # We append so any new vars in .env.example are preserved.
  cat >>"$REPO_ROOT/api/.env" <<EOF

# ---- Overrides applied by install.sh ----

# Application
APP_ENV=production
APP_DEBUG=false
SECRET_KEY=${SECRET_KEY}
API_HOST=0.0.0.0
API_PORT=5001

# Database (connecting to the postgres Docker service)
DB_HOST=postgres
DB_PORT=5432
DB_USERNAME=synkora
DB_PASSWORD=${POSTGRES_PASSWORD}
DB_DATABASE=synkora

# Redis (connecting to the redis Docker service)
REDIS_URL=redis://redis:6379/0
CELERY_BROKER_URL=redis://redis:6379/1
CELERY_RESULT_BACKEND=redis://redis:6379/2

# JWT
JWT_SECRET_KEY=${JWT_SECRET_KEY}

# Encryption
ENCRYPTION_KEY=${ENCRYPTION_KEY}

# CORS — allow both local dev origins
CORS_ORIGINS=http://localhost:3005,http://localhost:3000

# LLM Providers
OPENAI_API_KEY=${OPENAI_KEY}
ANTHROPIC_API_KEY=${ANTHROPIC_KEY}

# App identity
APP_BASE_URL=http://localhost:3005
SUPPORT_EMAIL=${admin_email}
CONTACT_EMAIL=${admin_email}

# Vector store (Qdrant is running in compose)
VECTOR_STORE=QDRANT
QDRANT_URL=http://qdrant:6333

# MinIO storage
AWS_S3_BUCKET=synkora-storage
AWS_REGION=us-east-1
AWS_ACCESS_KEY_ID=minioadmin
AWS_SECRET_ACCESS_KEY=${MINIO_PASSWORD}
AWS_ENDPOINT_URL=http://minio:9000
AWS_PUBLIC_ENDPOINT_URL=http://localhost:9000

# Langfuse (self-hosted via compose)
LANGFUSE_PUBLIC_KEY=
LANGFUSE_SECRET_KEY=
LANGFUSE_HOST=http://langfuse-web:3000
LANGFUSE_ENABLED=false
EOF

  success "api/.env written"
}

# ---------------------------------------------------------------------------
# web/.env
# ---------------------------------------------------------------------------
write_web_env() {
  info "Writing web/.env..."

  if [ -f "$REPO_ROOT/web/.env.example" ]; then
    cp "$REPO_ROOT/web/.env.example" "$REPO_ROOT/web/.env"
  fi

  cat >>"$REPO_ROOT/web/.env" <<EOF

# ---- Overrides applied by install.sh ----
NEXT_PUBLIC_API_URL=http://localhost:5001
NEXT_PUBLIC_APP_NAME=Synkora
NEXT_PUBLIC_APP_URL=http://localhost:3005
NEXT_PUBLIC_SUPPORT_EMAIL=${admin_email}
EOF

  success "web/.env written"
}

# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
generate_env_files() {
  section "Generating configuration files"
  write_root_env
  write_api_env
  write_web_env
  success "All .env files generated"
}
