#!/bin/bash
# Generate secure secrets for AI Tax Agent deployment

set -euo pipefail

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Function to generate random string
generate_secret() {
    local length=${1:-32}
    openssl rand -base64 $length | tr -d "=+/" | cut -c1-$length
}

# Function to generate UUID
generate_uuid() {
    python3 -c "import uuid; print(uuid.uuid4())"
}

echo -e "${BLUE}🔐 Generating secure secrets for AI Tax Agent...${NC}"
echo

# Generate secrets
AUTHENTIK_SECRET_KEY=$(generate_secret 50)
AUTHENTIK_OUTPOST_TOKEN=$(generate_secret 64)
AUTHENTIK_API_CLIENT_SECRET=$(generate_secret 32)
AUTHENTIK_GRAFANA_CLIENT_SECRET=$(generate_secret 32)
GRAFANA_OAUTH_CLIENT_SECRET=$(generate_secret 32)
NEXTAUTH_SECRET=$(generate_secret 32)
VAULT_DEV_ROOT_TOKEN_ID=$(generate_uuid)
POSTGRES_PASSWORD=$(generate_secret 16)
NEO4J_PASSWORD=$(generate_secret 16)
AUTHENTIK_DB_PASSWORD=$(generate_secret 16)
MINIO_ROOT_PASSWORD=$(generate_secret 16)
GRAFANA_PASSWORD=$(generate_secret 16)

# Create .env file with generated secrets
ENV_FILE="infra/compose/.env"
BACKUP_FILE="infra/compose/.env.backup.$(date +%Y%m%d_%H%M%S)"

# Backup existing .env if it exists
if [ -f "$ENV_FILE" ]; then
    echo -e "${YELLOW}📋 Backing up existing .env to $BACKUP_FILE${NC}"
    cp "$ENV_FILE" "$BACKUP_FILE"
fi

echo -e "${GREEN}🔑 Generating new .env file with secure secrets...${NC}"

cat > "$ENV_FILE" << EOF
# AI Tax Agent Environment Configuration
# Generated on $(date)
# IMPORTANT: Keep these secrets secure and never commit to version control

# Domain Configuration
DOMAIN=local
EMAIL=admin@local

# Database Passwords
POSTGRES_PASSWORD=$POSTGRES_PASSWORD
NEO4J_PASSWORD=$NEO4J_PASSWORD
AUTHENTIK_DB_PASSWORD=$AUTHENTIK_DB_PASSWORD

# Object Storage
MINIO_ROOT_USER=minio
MINIO_ROOT_PASSWORD=$MINIO_ROOT_PASSWORD

# Vector Database
QDRANT__SERVICE__GRPC_PORT=6334

# Secrets Management
VAULT_DEV_ROOT_TOKEN_ID=$VAULT_DEV_ROOT_TOKEN_ID

# Identity & SSO
AUTHENTIK_SECRET_KEY=$AUTHENTIK_SECRET_KEY
AUTHENTIK_OUTPOST_TOKEN=$AUTHENTIK_OUTPOST_TOKEN
AUTHENTIK_BOOTSTRAP_EMAIL=admin@local.lan
AUTHENTIK_BOOTSTRAP_PASSWORD=admin123
AUTHENTIK_BOOTSTRAP_TOKEN=ak-bootstrap-token
AUTHENTIK_API_CLIENT_SECRET=$AUTHENTIK_API_CLIENT_SECRET
AUTHENTIK_GRAFANA_CLIENT_SECRET=$AUTHENTIK_GRAFANA_CLIENT_SECRET

# OAuth Client Secrets
GRAFANA_OAUTH_CLIENT_ID=grafana
GRAFANA_OAUTH_CLIENT_SECRET=$GRAFANA_OAUTH_CLIENT_SECRET

# Monitoring
GRAFANA_PASSWORD=$GRAFANA_PASSWORD

# Feature Flags
UNLEASH_ADMIN_TOKEN=admin:development.unleash-insecure-admin-api-token

# Application Configuration
NEXTAUTH_SECRET=$NEXTAUTH_SECRET

# RAG & ML Models
RAG_EMBEDDING_MODEL=bge-small-en-v1.5
RAG_RERANKER_MODEL=cross-encoder/ms-marco-MiniLM-L-6-v2
RAG_ALPHA_BETA_GAMMA=0.5,0.3,0.2

# HMRC Integration
HMRC_MTD_ITSA_MODE=sandbox

# Rate Limits
RATE_LIMITS_HMRC_API_RPS=3
RATE_LIMITS_HMRC_API_BURST=6
RATE_LIMITS_LLM_API_RPS=10
RATE_LIMITS_LLM_API_BURST=20

# Confidence Thresholds
CONFIDENCE_AUTO_SUBMIT=0.95
CONFIDENCE_HUMAN_REVIEW=0.85
CONFIDENCE_REJECT=0.50

# Logging
LOG_LEVEL=INFO
LOG_FORMAT=json

# Development Settings
DEBUG=false
DEVELOPMENT_MODE=true

# Security
ENCRYPTION_KEY_ID=default
AUDIT_LOG_RETENTION_DAYS=90
PII_LOG_RETENTION_DAYS=30

# Backup & DR
BACKUP_ENABLED=true
BACKUP_SCHEDULE=0 2 * * *
BACKUP_RETENTION_DAYS=30

# Performance Tuning
MAX_WORKERS=4
BATCH_SIZE=100
CACHE_TTL_SECONDS=3600
CONNECTION_POOL_SIZE=20

# Feature Flags
FEATURE_RAG_ENABLED=true
FEATURE_FIRM_CONNECTORS_ENABLED=false
FEATURE_HMRC_SUBMISSION_ENABLED=false
FEATURE_ADVANCED_CALCULATIONS_ENABLED=true
EOF

# Set secure permissions
chmod 600 "$ENV_FILE"

echo -e "${GREEN}✅ Secrets generated successfully!${NC}"
echo
echo -e "${YELLOW}📝 Important credentials:${NC}"
echo -e "  ${BLUE}Grafana Admin:${NC} admin / $GRAFANA_PASSWORD"
echo -e "  ${BLUE}Authentik Admin:${NC} admin@local (set password on first login)"
echo -e "  ${BLUE}Vault Root Token:${NC} $VAULT_DEV_ROOT_TOKEN_ID"
echo -e "  ${BLUE}MinIO Admin:${NC} minio / $MINIO_ROOT_PASSWORD"
echo
echo -e "${RED}⚠️  SECURITY WARNING:${NC}"
echo -e "  • Keep the .env file secure and never commit it to version control"
echo -e "  • Change default passwords on first login"
echo -e "  • Use proper secrets management in production"
echo -e "  • Regularly rotate secrets"
echo
echo -e "${GREEN}🚀 Ready to deploy with: make deploy-infra${NC}"
