#!/usr/bin/env python3
"""Reset user password"""

import asyncio
import sys
from app.database import async_session
from app.auth import get_password_hash
from app.models import User
from sqlalchemy import select

async def reset_password(username: str, new_password: str):
    """Reset password for a user"""
    async with async_session() as db:
        # Find user
        result = await db.execute(
            select(User).where(User.username == username)
        )
        user = result.scalar_one_or_none()

        if not user:
            print(f"✗ User '{username}' not found")
            return

        # Update password
        user.hashed_password = get_password_hash(new_password)
        await db.commit()

        print(f"✓ Password reset successful for user: {username}")
        print(f"  User ID: {user.id}")
        print(f"  Email: {user.email}")

async def list_users():
    """List all users"""
    async with async_session() as db:
        result = await db.execute(select(User))
        users = result.scalars().all()

        if not users:
            print("No users found in database")
            return

        print("Users in database:")
        print("-" * 70)
        for user in users:
            print(f"  ID: {user.id}")
            print(f"  Username: {user.username}")
            print(f"  Email: {user.email}")
            print(f"  Active: {user.is_active}")
            print(f"  Created: {user.created_at}")
            print("-" * 70)

if __name__ == "__main__":
    if len(sys.argv) == 1 or sys.argv[1] == "list":
        print("Listing all users...")
        print("=" * 70)
        asyncio.run(list_users())
    elif len(sys.argv) == 3:
        username = sys.argv[1]
        new_password = sys.argv[2]
        print(f"Resetting password for user: {username}")
        print("=" * 70)
        asyncio.run(reset_password(username, new_password))
    else:
        print("Usage:")
        print("  List users:        ./reset-password.py list")
        print("  Reset password:    ./reset-password.py <username> <new_password>")
        print("")
        print("Examples:")
        print("  ./reset-password.py list")
        print("  ./reset-password.py Blance newpassword123")
        sys.exit(1)
