"""Reset (or create) an admin account's password from the command line.

Writes a fresh bcrypt hash through the normal `crud` code path, so the new
password is guaranteed to verify at login. Useful when the stored hash no longer
matches the password you expect (e.g. the bootstrap admin was seeded with an old
`ADMIN_BOOTSTRAP_PASSWORD`).

Run from the `backend/` directory with the venv active:

    python -m scripts.reset_admin_password admin@example.com
    python -m scripts.reset_admin_password admin@example.com --password 'NewSecret123'
    python -m scripts.reset_admin_password admin@example.com --create --role superadmin

If `--password` is omitted you are prompted for it (input hidden).
"""

from __future__ import annotations

import argparse
import getpass
import sys

from app import crud, schemas, security
from app.database import SessionLocal


def main() -> int:
    parser = argparse.ArgumentParser(description="Reset or create an admin password.")
    parser.add_argument("email", help="Admin email address.")
    parser.add_argument(
        "--password",
        help="New password (prompted securely if omitted).",
    )
    parser.add_argument(
        "--create",
        action="store_true",
        help="Create the admin if it does not already exist.",
    )
    parser.add_argument(
        "--name",
        default="Admin",
        help="Name to use when creating a new admin (default: %(default)s).",
    )
    parser.add_argument(
        "--role",
        default=security.ROLE_SUPERADMIN,
        choices=[security.ROLE_SUPERADMIN, security.ROLE_ADMIN, security.ROLE_VIEWER],
        help="Role to use when creating a new admin (default: %(default)s).",
    )
    args = parser.parse_args()

    password = args.password or getpass.getpass("New password: ")
    if len(password) < 8:
        print("Password must be at least 8 characters.", file=sys.stderr)
        return 1

    db = SessionLocal()
    try:
        admin = crud.get_admin_by_email(db, args.email)
        if admin is None:
            if not args.create:
                print(
                    f"No admin found for {args.email!r}. "
                    "Pass --create to create one.",
                    file=sys.stderr,
                )
                return 1
            crud.create_admin(
                db,
                schemas.AdminUserCreate(
                    email=args.email,
                    name=args.name,
                    password=password,
                    role=args.role,
                ),
            )
            print(f"Created admin {args.email} (role: {args.role}).")
        else:
            crud.update_admin(
                db, admin, schemas.AdminUserUpdate(password=password)
            )
            print(f"Reset password for {args.email}.")
        return 0
    finally:
        db.close()


if __name__ == "__main__":
    raise SystemExit(main())
