#!/usr/bin/env python3
"""
Configuration Management Utility for Sharey
"""
import sys
import json
import hashlib
import getpass
from config import config

def show_config():
    """Display current configuration"""
    config.print_config(hide_secrets=False)

def validate_config():
    """Validate current configuration"""
    print("🔧 Validating configuration...")
    
    # Check storage configuration
    if config.validate_storage_config():
        storage_config = config.get_storage_config()
        backend = storage_config.get('backend', 'unknown')
        print(f"✅ Storage configuration is valid (backend: {backend})")
        
        if backend == 'b2':
            b2_config = config.get_b2_config()
            print(f"   → B2 bucket: {b2_config.get('bucket_name', 'unknown')}")
        elif backend == 'local':
            local_path = storage_config.get('local_path', 'storage')
            print(f"   → Local path: {local_path}")
    else:
        print("❌ Storage configuration is invalid")
        return False
    
    # Check other configurations
    max_size = config.get('upload.max_file_size_mb')
    if max_size and max_size > 0:
        print(f"✅ Upload max size: {max_size} MB")
    else:
        print("⚠️  Upload max size not configured")
    
    max_length = config.get('paste.max_length')
    if max_length and max_length > 0:
        print(f"✅ Paste max length: {max_length:,} characters")
    else:
        print("⚠️  Paste max length not configured")
    
    print("✅ Configuration validation complete")
    return True

def set_config():
    """Interactively set configuration values"""
    print("🔧 Interactive Configuration Setup")
    print("=" * 50)
    
    current_config = config.config.copy()
    
    # Storage Configuration
    print("\n💾 Storage Configuration:")
    storage_backend = input(f"Storage backend (b2/local) [{current_config.get('storage', {}).get('backend', 'b2')}]: ").strip().lower()
    if storage_backend in ['b2', 'local']:
        if 'storage' not in current_config:
            current_config['storage'] = {}
        current_config['storage']['backend'] = storage_backend
        
        if storage_backend == 'local':
            local_path = input(f"Local storage path [{current_config.get('storage', {}).get('local_path', 'storage')}]: ").strip()
            if local_path:
                current_config['storage']['local_path'] = local_path
    
    # B2 Configuration (only if using B2 backend)
    if current_config.get('storage', {}).get('backend', 'b2') == 'b2':
        print("\n📦 Backblaze B2 Configuration:")
        current_config['b2']['application_key_id'] = input(f"Application Key ID [{current_config['b2'].get('application_key_id', '')}]: ").strip() or current_config['b2'].get('application_key_id', '')
        current_config['b2']['application_key'] = input(f"Application Key [{current_config['b2'].get('application_key', '')}]: ").strip() or current_config['b2'].get('application_key', '')
        current_config['b2']['bucket_name'] = input(f"Bucket Name [{current_config['b2'].get('bucket_name', '')}]: ").strip() or current_config['b2'].get('bucket_name', '')
    
    # Flask Configuration
    print("\n🌐 Flask Configuration:")
    current_config['flask']['host'] = input(f"Host [{current_config['flask'].get('host', '127.0.0.1')}]: ").strip() or current_config['flask'].get('host', '127.0.0.1')
    port_input = input(f"Port [{current_config['flask'].get('port', 8866)}]: ").strip()
    if port_input:
        try:
            current_config['flask']['port'] = int(port_input)
        except ValueError:
            print("⚠️  Invalid port, keeping current value")
    
    debug_input = input(f"Debug mode (true/false) [{current_config['flask'].get('debug', True)}]: ").strip().lower()
    if debug_input in ['true', 'false']:
        current_config['flask']['debug'] = debug_input == 'true'
    
    # Upload Configuration
    print("\n📁 Upload Configuration:")
    size_input = input(f"Max file size (MB) [{current_config['upload'].get('max_file_size_mb', 100)}]: ").strip()
    if size_input:
        try:
            current_config['upload']['max_file_size_mb'] = int(size_input)
        except ValueError:
            print("⚠️  Invalid size, keeping current value")
    
    # Paste Configuration
    print("\n📝 Paste Configuration:")
    length_input = input(f"Max paste length [{current_config['paste'].get('max_length', 1000000)}]: ").strip()
    if length_input:
        try:
            current_config['paste']['max_length'] = int(length_input)
        except ValueError:
            print("⚠️  Invalid length, keeping current value")
    
    # Save configuration
    if config.save_config(current_config):
        print("\n✅ Configuration saved successfully!")
        return True
    else:
        print("\n❌ Failed to save configuration")
        return False

def reset_config():
    """Reset configuration to defaults"""
    print("🔄 Resetting configuration to defaults...")
    
    default_config = {
        "b2": {
            "application_key_id": "your_key_id_here",
            "application_key": "your_application_key_here",
            "bucket_name": "your_bucket_name_here"
        },
        "flask": {
            "host": "127.0.0.1",
            "port": 8866,
            "debug": True
        },
        "upload": {
            "max_file_size_mb": 100
        },
        "paste": {
            "max_length": 1000000
        },
        "security": {
            "rate_limit_enabled": False,
            "max_uploads_per_hour": 50
        }
    }
    
    if config.save_config(default_config):
        print("✅ Configuration reset to defaults")
        return True
    else:
        print("❌ Failed to reset configuration")
        return False

def enable_maintenance():
    """Enable maintenance mode"""
    print("🔧 Enabling maintenance mode...")
    
    current_config = config.config.copy()
    
    # Ensure maintenance section exists
    if 'maintenance' not in current_config:
        current_config['maintenance'] = {}
    
    current_config['maintenance']['enabled'] = True
    
    # Ask for custom message
    message = input("Maintenance message [Sharey is currently under maintenance. Please check back later!]: ").strip()
    if message:
        current_config['maintenance']['message'] = message
    
    # Ask for estimated return time
    return_time = input("Estimated return time (optional): ").strip()
    if return_time:
        current_config['maintenance']['estimated_return'] = return_time
    
    # Save configuration
    if config.save_config(current_config):
        print("✅ Maintenance mode enabled!")
        print("💡 Users will now see the maintenance page")
        print("💡 To disable: python config_util.py maintenance disable")
    else:
        print("❌ Failed to enable maintenance mode")

def disable_maintenance():
    """Disable maintenance mode"""
    print("🔧 Disabling maintenance mode...")
    
    current_config = config.config.copy()
    
    # Ensure maintenance section exists
    if 'maintenance' not in current_config:
        current_config['maintenance'] = {}
    
    current_config['maintenance']['enabled'] = False
    
    # Save configuration
    if config.save_config(current_config):
        print("✅ Maintenance mode disabled!")
        print("💡 Sharey is now accessible to users")
    else:
        print("❌ Failed to disable maintenance mode")

def maintenance_status():
    """Show maintenance mode status"""
    maintenance_config = config.get('maintenance', {})
    enabled = maintenance_config.get('enabled', False)
    
    print("🔧 Maintenance Mode Status")
    print("=" * 30)
    
    if enabled:
        print("🟠 Status: ENABLED")
        print(f"📝 Message: {maintenance_config.get('message', 'Default message')}")
        if maintenance_config.get('estimated_return'):
            print(f"⏰ Estimated return: {maintenance_config['estimated_return']}")
        print("\n💡 To disable: python config_util.py maintenance disable")
    else:
        print("🟢 Status: DISABLED")
        print("💡 Sharey is accessible to users")
        print("💡 To enable: python config_util.py maintenance enable")

def handle_maintenance_command():
    """Handle maintenance mode subcommands"""
    if len(sys.argv) < 3:
        print("Usage: python config_util.py maintenance <enable|disable|status>")
        print("Commands:")
        print("  enable  - Enable maintenance mode")
        print("  disable - Disable maintenance mode") 
        print("  status  - Show current maintenance status")
        return
    
    subcommand = sys.argv[2].lower()
    
    if subcommand == 'enable':
        enable_maintenance()
    elif subcommand == 'disable':
        disable_maintenance()
    elif subcommand == 'status':
        maintenance_status()
    else:
        print(f"Unknown maintenance command: {subcommand}")

def set_admin_password():
    """Set admin panel password"""
    print("🔐 Setting Admin Panel Password")
    print("=" * 35)
    
    # Get password with confirmation
    while True:
        password = getpass.getpass("Enter admin password: ")
        if len(password) < 6:
            print("❌ Password must be at least 6 characters long")
            continue
            
        confirm = getpass.getpass("Confirm admin password: ")
        if password != confirm:
            print("❌ Passwords don't match")
            continue
            
        break
    
    # Hash the password
    password_hash = hashlib.sha256(password.encode()).hexdigest()
    
    # Update config
    current_config = config.config.copy()
    
    # Ensure admin section exists
    if 'admin' not in current_config:
        current_config['admin'] = {}
    
    current_config['admin']['password_hash'] = password_hash
    current_config['admin']['session_timeout_minutes'] = current_config['admin'].get('session_timeout_minutes', 30)
    
    # Save configuration
    if config.save_config(current_config):
        print("✅ Admin password set successfully!")
        print("💡 You can now access the admin panel at /admin")
    else:
        print("❌ Failed to save admin password")

def admin_status():
    """Show admin panel configuration status"""
    admin_config = config.get('admin', {})
    
    print("🔐 Admin Panel Status")
    print("=" * 25)
    
    if admin_config.get('password_hash'):
        print("🟢 Status: CONFIGURED")
        print(f"⏰ Session timeout: {admin_config.get('session_timeout_minutes', 30)} minutes")
        print("💡 Access at: /admin")
        print("💡 To change password: python config_util.py admin password")
    else:
        print("🟠 Status: NOT CONFIGURED")
        print("💡 To set password: python config_util.py admin password")

def handle_admin_command():
    """Handle admin panel subcommands"""
    if len(sys.argv) < 3:
        print("Usage: python config_util.py admin <password|status>")
        print("Commands:")
        print("  password - Set admin panel password")
        print("  status   - Show admin panel configuration status")
        return
    
    subcommand = sys.argv[2].lower()
    
    if subcommand == 'password':
        set_admin_password()
    elif subcommand == 'status':
        admin_status()
    else:
        print(f"Unknown admin command: {subcommand}")

def main():
    """Main configuration utility"""
    if len(sys.argv) < 2:
        print("Sharey Configuration Utility")
        print("Usage: python config_util.py <command>")
        print("\nCommands:")
        print("  show        - Display current configuration")
        print("  validate    - Validate configuration")
        print("  set         - Interactively set configuration")
        print("  reset       - Reset configuration to defaults")
        print("  maintenance - Manage maintenance mode (enable/disable/status)")
        print("  admin       - Manage admin panel (password/status)")
        sys.exit(1)
    
    command = sys.argv[1].lower()
    
    if command == 'show':
        show_config()
    elif command == 'validate':
        validate_config()
    elif command == 'set':
        set_config()
    elif command == 'reset':
        reset_config()
    elif command == 'maintenance':
        handle_maintenance_command()
    elif command == 'admin':
        handle_admin_command()
    else:
        print(f"Unknown command: {command}")
        sys.exit(1)

if __name__ == "__main__":
    main()
