"""
Django integration example for Kilit.

This example shows how to use Kilit to manage encrypted secrets
in a Django application.
"""

from pathlib import Path
from kilit import Credentials

# Load credentials once at startup
BASE_DIR = Path(__file__).resolve().parent.parent
creds = Credentials(BASE_DIR / "config" / "credentials.json.enc")

# Django settings.py
# ==================

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = creds.require("django.secret_key")

# Database configuration
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": creds.get("database.name", "myapp_db"),
        "USER": creds.get("database.user", "postgres"),
        "PASSWORD": creds.require("database.password"),
        "HOST": creds.get("database.host", "localhost"),
        "PORT": creds.get("database.port", 5432),
    }
}

# Email configuration
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = creds.get("email.host", "smtp.gmail.com")
EMAIL_PORT = creds.get("email.port", 587)
EMAIL_USE_TLS = True
EMAIL_HOST_USER = creds.require("email.user")
EMAIL_HOST_PASSWORD = creds.require("email.password")

# Third-party API keys
STRIPE_SECRET_KEY = creds.require("stripe.secret_key")
STRIPE_PUBLISHABLE_KEY = creds.require("stripe.publishable_key")

AWS_ACCESS_KEY_ID = creds.require("aws.access_key_id")
AWS_SECRET_ACCESS_KEY = creds.require("aws.secret_access_key")
AWS_STORAGE_BUCKET_NAME = creds.get("aws.bucket_name", "my-bucket")

# Redis configuration
REDIS_URL = creds.get("redis.url", "redis://localhost:6379/0")

# Celery configuration
CELERY_BROKER_URL = REDIS_URL
CELERY_RESULT_BACKEND = REDIS_URL


# Example credentials.json structure:
# ====================================
"""
{
  "django": {
    "secret_key": "your-secret-key-here"
  },
  "database": {
    "name": "myapp_production",
    "user": "myapp_user",
    "password": "super-secret-password",
    "host": "db.example.com",
    "port": 5432
  },
  "email": {
    "host": "smtp.gmail.com",
    "port": 587,
    "user": "noreply@example.com",
    "password": "email-password"
  },
  "stripe": {
    "secret_key": "sk_live_...",
    "publishable_key": "pk_live_..."
  },
  "aws": {
    "access_key_id": "AKIAIOSFODNN7EXAMPLE",
    "secret_access_key": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
    "bucket_name": "my-production-bucket"
  },
  "redis": {
    "url": "redis://redis.example.com:6379/0"
  }
}
"""


# Setup instructions:
# ===================
"""
1. Initialize encrypted credentials:
   $ kilit init --path config/credentials.json.enc

2. Edit credentials:
   $ kilit edit --path config/credentials.json.enc

3. Add to .gitignore:
   config/master.key

4. In production, set environment variable:
   export KILIT_MASTER_KEY="your-master-key"

5. Or use a secure key management service:
   - AWS Secrets Manager
   - HashiCorp Vault
   - Google Secret Manager
"""
