"""Interactive password rotation for an existing user."""
import getpass
from lic_webapp.auth import hash_password
from lic_webapp.database import get_db_connection


def main() -> None:
    username = input('Existing username: ').strip()
    password = getpass.getpass('New password (12–128 characters): ')
    if not 12 <= len(password) <= 128:
        raise SystemExit('Password must contain 12–128 characters.')
    if password != getpass.getpass('Confirm password: '):
        raise SystemExit('Passwords do not match.')
    conn = get_db_connection()
    try:
        with conn:
            user = conn.execute('SELECT id FROM users WHERE username = ?', (username,)).fetchone()
            if user is None:
                raise SystemExit('User not found.')
            conn.execute('UPDATE users SET password_hash = ? WHERE id = ?', (hash_password(password), user['id']))
            conn.execute('DELETE FROM sessions WHERE user_id = ?', (user['id'],))
    finally:
        conn.close()
    print('Password updated; existing sessions revoked.')


if __name__ == '__main__':
    main()
