"""
fix_staff_names.py
==================
Precise one-off fix for all 25 staff records based on exact admin export.
Separates title from first_name, normalises last_name, updates usernames.

HOW TO RUN (from the DEV folder, with venv active):
    python manage.py shell < scripts/fix_staff_names.py

OR on Windows PowerShell:
    Get-Content scripts\fix_staff_names.py | python manage.py shell

Set DRY_RUN = False in this file before running to actually save changes.
After running: notify staff of their new login usernames.
"""
import os, sys, django

# ── Bootstrap Django so this file can also be run standalone ──────────────
# (manage.py shell already does this, but this guard makes it work either way)
if not os.environ.get('DJANGO_SETTINGS_MODULE'):
    # Adjust the path if your settings module is different
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.insert(0, BASE_DIR)
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
    django.setup()

from django.contrib.auth import get_user_model
from staff.models import Staff

User = get_user_model()

DRY_RUN = False   # ← set to False to save changes

# (current_username, title, correct_first, correct_last, new_username)
FIXES = [
    ('MankaN',               'Mme', 'Nchotu',    'Manka',           'nchotu.manka'),
    ('SuperAdmin',           '',    'Super',     'Admin',           'super.admin'),
    ('VitusDk',              '',    'Vitus',     'Dk',              'vitus.dk'),
    ('amadouT',              'Mr',  'Amadou',    'Tijani',          'amadou.tijani'),
    ('carolineA',            'Mme', 'Caroline',  'Ayuk',            'caroline.ayuk'),
    ('chesiL',               'Mme', 'Chesi',     'Landry',          'chesi.landry'),
    ('christelleE',          'Mme', 'Christelle','Ekosso',          'christelle.ekosso'),
    ('ferdinandS',           'Mr',  'Ferdinand', 'Sunyin',          'ferdinand.sunyin'),
    ('ireneM',               'Mme', 'Irene',     'Madjague Toubet', 'irene.madjague_toubet'),
    ('mme.charlottemouil',   'Mme', 'Charlotte', 'Mouil',           'charlotte.mouil'),
    ('mme.dongmoevine',      'Mme', 'Evine',     'Dongmo',          'evine.dongmo'),
    ('mme.epiezita',         'Mme', 'Zita',      'Epie',            'zita.epie'),
    ('mme.fongangnoella',    'Mme', 'Noella',    'Fongang',         'noella.fongang'),
    ('mme.fossemalice',      'Mme', 'Alice',     'Fossem',          'alice.fossem'),
    ('mme.labolongpajosiane','Mme', 'Josiane',   'Labo Longpa',     'josiane.labo_longpa'),
    ('mme.leudjeuliliane',   'Mme', 'Liliane',   'Leudjeu',         'liliane.leudjeu'),
    ('mme.mbachangmelanie',  'Mme', 'Melanie',   'Mbachang',        'melanie.mbachang'),
    ('mme.ngakwenaomi',      'Mme', 'Naomi',     'Ngakwe',          'naomi.ngakwe'),
    ('mme.nguvehacecil',     'Mme', 'Cecil',     'Nguveha',         'cecil.nguveha'),
    ('mme.nkayengamaminatou','Mme', 'Aminatou',  'Nkayengam',       'aminatou.nkayengam'),
    ('mme.nkwainprisca',     'Mme', 'Prisca',    'Nkwain',          'prisca.nkwain'),
    ('mme.tabicynthia',      'Mme', 'Cynthia',   'Tabi',            'cynthia.tabi'),
    ('mr.ndemgordon',        'Mr',  'Gordon',    'Ndem',            'gordon.ndem'),
    ('mr.nebongocelestine',  'Mr',  'Celestine', 'Nebongo',         'celestine.nebongo'),
    ('sheyA',                'Mme', 'Annie',     'Shey',            'annie.shey'),
]

print(f"\n{'='*60}")
print(f"  {'DRY RUN — no changes saved' if DRY_RUN else 'LIVE — SAVING CHANGES'}")
print(f"  Staff Name Fix ({len(FIXES)} records)")
print(f"{'='*60}\n")

ok = skipped = 0
errors = []

for old_un, title, first, last, new_un in FIXES:
    try:
        user = User.objects.get(username=old_un)
    except User.DoesNotExist:
        if User.objects.filter(username=new_un).exists():
            print(f"  ✓ Already fixed: {new_un}")
            skipped += 1
            continue
        errors.append(f"NOT FOUND: {old_un!r}")
        continue

    try:
        staff = user.staff_profile
    except Exception:
        errors.append(f"No staff profile for: {old_un!r}")
        continue

    changes = []
    if user.first_name != first:     changes.append(f"  first:    {user.first_name!r:22} → {first!r}")
    if user.last_name  != last:      changes.append(f"  last:     {user.last_name!r:22} → {last!r}")
    if user.username   != new_un:    changes.append(f"  username: {user.username!r:22} → {new_un!r}")
    if (staff.title or '') != title: changes.append(f"  title:    {staff.title!r:22} → {title!r}")

    if not changes:
        print(f"  — No change needed: {old_un}")
        skipped += 1
        continue

    print(f"\n  {old_un}")
    for c in changes:
        print(c)

    if not DRY_RUN:
        if new_un != old_un and User.objects.filter(username=new_un).exists():
            errors.append(f"Username collision: {new_un!r} — skipped {old_un}")
            continue
        user.first_name = first
        user.last_name  = last
        user.username   = new_un
        user.save()
        staff.title = title
        staff.save()
        print("  ✓ Saved")

    ok += 1

print(f"\n{'='*60}")
if DRY_RUN:
    print(f"  Dry run complete — {ok} would be updated, {skipped} already correct")
    print(f"  To apply: set DRY_RUN = False then re-run")
else:
    print(f"  Done — {ok} updated, {skipped} already correct")
if errors:
    print(f"\n  Errors ({len(errors)}):")
    for e in errors:
        print(f"    ✗ {e}")
print(f"{'='*60}\n")