#!/usr/bin/env python3
"""
rename_student_ids.py
=====================
One-time script — renames all existing IMP-XXXX student IDs
to the new RB-YY-NNNN format.

Run on the server:
    OPENBLAS_NUM_THREADS=1 python rename_student_ids.py [--dry-run]
"""

import os, sys, argparse
from pathlib import Path

parser = argparse.ArgumentParser()
parser.add_argument('--dry-run', action='store_true')
parser.add_argument('--settings', default='backend.settings_production')
args = parser.parse_args()

sys.path.insert(0, str(Path(__file__).resolve().parent))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', args.settings)
os.environ.setdefault('OPENBLAS_NUM_THREADS', '1')

import django
django.setup()

from students.models import Student
from django.db import transaction

DRY = args.dry_run
if DRY:
    print("DRY RUN — no changes written\n")

# ── Gather all students ordered by current ID to keep sequence stable ─────────
students = list(Student.objects.all().order_by('student_id'))

print(f"Total students: {len(students)}")
print()

# ── Determine admission year per student ─────────────────────────────────────
# Use admission_date if set, else fall back to 2026 (this academic year)
from datetime import date

def get_yy(student):
    if student.admission_date:
        return str(student.admission_date.year)[-2:]
    return '26'   # default for all current students

# ── Build rename map: old_id -> new_id ───────────────────────────────────────
# Sequence is GLOBAL — just counts 1, 2, 3… regardless of year
rename_map = {}
seq = 1
for s in students:
    yy     = get_yy(s)
    new_id = f'RB-{yy}-{seq:04d}'
    rename_map[s.student_id] = new_id
    seq += 1

# ── Preview ───────────────────────────────────────────────────────────────────
print(f"{'OLD ID':<15}  {'NEW ID':<15}  {'NAME'}")
print("-" * 55)
for s in students:
    old = s.student_id
    new = rename_map[old]
    print(f"  {old:<15}  {new:<15}  {s.first_name} {s.last_name}")

print()

if DRY:
    print("Dry run complete — run without --dry-run to apply.")
    sys.exit(0)

# ── Apply — use a temp prefix first to avoid unique constraint mid-rename ─────
confirm = input("Apply these renames? (yes/no): ").strip().lower()
if confirm != 'yes':
    print("Aborted.")
    sys.exit(0)

print("\nRenaming...")
with transaction.atomic():
    # Pass 1: rename to TEMP-N to free up all old IDs
    for i, s in enumerate(students):
        s.student_id = f'TEMP-{i+1:04d}'
        s.save(update_fields=['student_id'])

    # Pass 2: rename to final RB-YY-NNNN
    for s in students:
        old_id = [k for k, v in rename_map.items()][students.index(s)]
        s.student_id = rename_map[old_id]
        s.save(update_fields=['student_id'])
        print(f"  {old_id:<15} -> {s.student_id}")

print(f"\nDone. {len(students)} students renamed to RB-YY-NNNN format.")
print("Next new student will be assigned RB-26-{seq:04d}".format(seq=len(students)+1))
