#!/usr/bin/env python3
"""
Create or reset the Grazuri admin user.
Run on server: python create_admin.py

You can customise the credentials below before running.
"""
import os
import sys

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')

try:
    from dotenv import load_dotenv
    load_dotenv(os.path.join(os.path.dirname(os.path.abspath(__file__)), '.env'), override=True)
except ImportError:
    pass

import django
django.setup()

from django.contrib.auth import get_user_model

# ── Credentials — change these before running ─────────────────
FIRST_NAME  = 'Haven'
LAST_NAME   = 'Grazuri'
EMAIL       = 'admin@havengrazuri.co.ke'
USERNAME    = 'admin'
PASSWORD    = 'Grazuri@2026'          # Change after first login
PHONE       = '+254112941830'
# ──────────────────────────────────────────────────────────────

User = get_user_model()

print(f"\n{'='*50}")
print(f"  Grazuri Admin User Setup")
print(f"{'='*50}\n")

try:
    user = User.objects.get(email=EMAIL)
    print(f"  User '{EMAIL}' already exists — resetting password and permissions...")
    action = 'updated'
except User.DoesNotExist:
    print(f"  Creating new admin user '{EMAIL}'...")
    user = User(email=EMAIL, username=USERNAME)
    action = 'created'

# Set all required fields
user.first_name        = FIRST_NAME
user.last_name         = LAST_NAME
user.username          = USERNAME
user.role              = 'admin'
user.status            = 'active'
user.is_staff          = True
user.is_superuser      = True
user.is_active         = True
user.is_phone_verified = True
user.is_email_verified = True
user.is_verified       = True

# Set phone if the field exists
try:
    user.phone_number = PHONE
except Exception:
    pass

user.set_password(PASSWORD)

try:
    user.save()
    print(f"\n  Admin user {action} successfully!")
    print(f"\n  {'─'*40}")
    print(f"  Login URL : https://uzuriapps.xyz/login/")
    print(f"  Email     : {EMAIL}")
    print(f"  Password  : {PASSWORD}")
    print(f"  Role      : Admin (full access)")
    print(f"  {'─'*40}")
    print(f"\n  IMPORTANT: Change the password after first login.")
    print(f"{'='*50}\n")
except Exception as e:
    print(f"\n  ERROR: Could not save user: {e}")
    import traceback
    traceback.print_exc()
    sys.exit(1)
