"""
Administrative CLI script to securely reset a user's password.

Usage:
    python -m scripts.reset_admin_password --phone <PHONE> [--password <PASSWORD>]

If --password is not provided, the script will securely prompt for it via getpass.
"""

import argparse
import asyncio
import getpass
import sys

from sqlalchemy import text

from app.core.security import hash_password, verify_password
from app.database import AsyncSessionLocal


async def reset_password(phone: str, new_password: str) -> bool:
    hashed = hash_password(new_password)
    async with AsyncSessionLocal() as session:
        query = text(
            'UPDATE "user" SET hashed_password = :hp, is_active = true WHERE phone = :ph RETURNING id, name'
        )
        res = await session.execute(query, {"hp": hashed, "ph": phone})
        updated_row = res.fetchone()
        if not updated_row:
            print(f"Error: No user found with phone '{phone}'.")
            return False

        await session.commit()

        # Verify hash match
        verify_res = await session.execute(
            text('SELECT hashed_password FROM "user" WHERE phone = :ph'),
            {"ph": phone},
        )
        user_row = verify_res.fetchone()
        if user_row and verify_password(new_password, user_row.hashed_password):
            print(f"Success: Password for '{updated_row.name}' ({phone}) has been updated and verified.")
            return True

        print("Error: Password verification failed after update.")
        return False


def main() -> None:
    parser = argparse.ArgumentParser(description="Securely reset user password in database.")
    parser.add_argument("--phone", required=True, help="Registered mobile number of the user")
    parser.add_argument("--password", help="New password (if omitted, an interactive prompt is shown)")
    args = parser.parse_args()

    password = args.password
    if not password:
        password = getpass.getpass("Enter new password: ")
        confirm = getpass.getpass("Confirm new password: ")
        if password != confirm:
            print("Error: Passwords do not match.")
            sys.exit(1)

    if len(password) < 8:
        print("Error: Password must be at least 8 characters.")
        sys.exit(1)

    success = asyncio.run(reset_password(args.phone, password))
    if not success:
        sys.exit(1)


if __name__ == "__main__":
    main()
