# -*- coding: utf-8 -*-
"""
Reset the platform admin login (local / dev). Does not run automatically.

Usage (from project root):
  python scripts/reset_admin_login.py

Optional env:
  ADMIN_EMAIL     default: admin@quickcare.pk
  ADMIN_PASSWORD  default: admin123
"""
import os
import sys

# Project root = parent of scripts/
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT not in sys.path:
    sys.path.insert(0, ROOT)

from app import create_app, db  # noqa: E402
from app.models import User  # noqa: E402


def main():
    email = (os.environ.get("ADMIN_EMAIL") or "admin@quickcare.pk").strip().lower()
    password = os.environ.get("ADMIN_PASSWORD") or "admin123"

    app = create_app()
    with app.app_context():
        user = User.query.filter_by(role="admin").order_by(User.id.asc()).first()
        if not user:
            print("No user with role 'admin' found. Create one via Flask shell or DB seed.")
            sys.exit(1)

        user.email = email
        user.is_active = True
        user.set_password(password)
        db.session.commit()

        if not user.check_password(password):
            print("ERROR: Password check failed after set.")
            sys.exit(1)

        assert User.query.filter_by(email=email, role="admin").first() is not None
        print(f"Admin login updated: {email}")
        print("Password has been set from ADMIN_PASSWORD or default (admin123).")


if __name__ == "__main__":
    main()
