#!/usr/bin/env python3
# Copyright (c) 2025 Patrick Motsch
# All rights reserved.
"""
Generate secure master keys for all environments.

This tool generates cryptographically secure 256-bit master keys for all environments
and updates the key.txt file with the new keys.

Usage:
    python script_security_generate_master_keys.py
    python script_security_generate_master_keys.py --output "path/to/key.txt"
"""

import sys
import os
import secrets
import base64
import argparse
from pathlib import Path

scriptPath = Path(__file__).resolve()
gatewayPath = scriptPath.parent.parent
projectRoot = gatewayPath.parent

def generate_master_key():
    """Generate a secure 256-bit master key."""
    # Generate 32 random bytes (256 bits)
    key_bytes = secrets.token_bytes(32)
    # Encode as base64 for easy storage
    return base64.urlsafe_b64encode(key_bytes).decode('utf-8')

def main():
    parser = argparse.ArgumentParser(description='Generate secure master keys for all environments')
    parser.add_argument('--output', '-o', 
                       default=str(projectRoot / "local" / "key.txt"),
                       help='Output file path (default: poweron/local/key.txt)')
    parser.add_argument('--force', '-f', action='store_true',
                       help='Overwrite existing key file without confirmation')
    
    args = parser.parse_args()
    
    # Convert to absolute path
    output_path = Path(args.output).resolve()
    
    # Check if file exists and get confirmation
    if output_path.exists() and not args.force:
        response = input(f"File {output_path} already exists. Overwrite? (y/N): ")
        if response.lower() != 'y':
            print("Operation cancelled.")
            return
    
    try:
        # Generate keys for all environments
        keys = {
            'prod': generate_master_key(),
            'int': generate_master_key(),
            'dev': generate_master_key()
        }
        
        # Create output content
        content = []
        content.append("# PowerOn Master Keys")
        content.append("# Generated on: " + str(Path(__file__).stat().st_mtime))
        content.append("# WARNING: Keep this file secure and never commit to version control!")
        content.append("")
        
        for env, key in keys.items():
            content.append(f"{env} = {key}")
        
        # Ensure output directory exists
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        # Write to file
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write('\n'.join(content))
        
        print("✓ Master keys generated successfully!")
        print(f"Output file: {output_path}")
        print("\nGenerated keys:")
        for env, key in keys.items():
            print(f"  {env}: {key[:20]}...")
        
        print(f"\n⚠️  IMPORTANT SECURITY NOTES:")
        print(f"   - Keep this file secure and never commit to version control")
        print(f"   - Store production keys in Azure environment variables")
        print(f"   - Share development keys securely with team members")
        print(f"   - Consider rotating keys regularly")
        
    except Exception as e:
        print(f"Error generating keys: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()
