"""Script to reset admin user password."""

import sys
from pathlib import Path

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from sqlalchemy.orm import Session

from app.database import SessionLocal
from app.models.admin_user import AdminUser
from app.utils.security import get_password_hash


def reset_admin_password(
    username: str = "admin",
    new_password: str = "admin123",
):
    """Reset admin user password."""
    db: Session = SessionLocal()
    try:
        # Find user by username or email
        user = db.query(AdminUser).filter(
            (AdminUser.username == username) | (AdminUser.email == username)
        ).first()
        
        if not user:
            print(f"Admin user with username or email '{username}' not found.")
            return None
        
        # Update password
        user.password_hash = get_password_hash(new_password)
        user.is_active = True
        db.commit()
        db.refresh(user)
        
        print(f"Admin password reset successfully!")
        print(f"  Username: {user.username}")
        print(f"  Email: {user.email}")
        print(f"  New Password: {new_password}")
        print(f"  Role: {user.role.value}")
        print(f"  Is Active: {user.is_active}")
        
        return user
    except Exception as e:
        db.rollback()
        print(f"Error resetting admin password: {e}")
        raise
    finally:
        db.close()


if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description="Reset admin user password")
    parser.add_argument("--username", default="admin", help="Admin username or email")
    parser.add_argument("--password", default="admin123", help="New password")
    
    args = parser.parse_args()
    
    reset_admin_password(
        username=args.username,
        new_password=args.password,
    )
