#!/usr/bin/env python3
"""
Password hashing utility for ACWS Web Client authentication
Generates bcrypt password hashes for use in auth.ini
"""

import sys
import getpass

def hash_password_bcrypt(password):
    """Hash password using bcrypt"""
    try:
        import bcrypt
        # Generate salt and hash password
        salt = bcrypt.gensalt(rounds=12)
        password_hash = bcrypt.hashpw(password.encode('utf-8'), salt)
        return password_hash.decode('utf-8')
    except ImportError:
        print("ERROR: bcrypt is not installed.")
        print("Install it with: pip install bcrypt")
        return None

def hash_password_sha256(password):
    """Hash password using SHA256 (less secure, fallback only)"""
    import hashlib
    return hashlib.sha256(password.encode('utf-8')).hexdigest()

def main():
    """Main function to generate password hash"""
    print("=" * 60)
    print("ACWS Web Client - Password Hash Generator")
    print("=" * 60)
    print()
    
    # Try to use bcrypt first
    has_bcrypt = True
    try:
        import bcrypt
        print("Using bcrypt for secure password hashing (recommended)")
    except ImportError:
        has_bcrypt = False
        print("WARNING: bcrypt not installed. Using SHA256 (less secure).")
        print("Install bcrypt for better security: pip install bcrypt")
    
    print()
    
    # Get username
    username = input("Enter username: ").strip()
    if not username:
        print("ERROR: Username cannot be empty")
        sys.exit(1)
    
    # Get password (hidden input)
    password = getpass.getpass("Enter password: ")
    if not password:
        print("ERROR: Password cannot be empty")
        sys.exit(1)
    
    password_confirm = getpass.getpass("Confirm password: ")
    if password != password_confirm:
        print("ERROR: Passwords do not match")
        sys.exit(1)
    
    print()
    print("Generating password hash...")
    
    # Generate hash
    if has_bcrypt:
        password_hash = hash_password_bcrypt(password)
        if not password_hash:
            sys.exit(1)
    else:
        password_hash = hash_password_sha256(password)
    
    # Display result
    print()
    print("=" * 60)
    print("Add this to your auth.ini file:")
    print("=" * 60)
    print()
    print(f"[{username}]")
    print(f"password_hash={password_hash}")
    print()
    print("=" * 60)
    print()
    print("Copy the lines above and add them to your auth.ini file.")
    if not has_bcrypt:
        print()
        print("NOTE: You used SHA256 hashing. For better security, install bcrypt:")
        print("  pip install bcrypt")
        print("  Then re-run this script to generate a bcrypt hash.")
    print()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\nCancelled by user")
        sys.exit(0)
    except Exception as e:
        print(f"\nERROR: {e}")
        sys.exit(1)
