"""Daily per-subject test code management.

Teacher writes codes on board (e.g., PH3 = Physics Question 3).Students must enter the correct code to upload their answer."""
import random
import re
from django.utils import timezone
from exams.models import StudentDailyCode

# MUST match BOOK_ABBR in exams/views.py
BOOK_ABBR = {
    'Urdu': 'UR', 'English': 'EN', 'Islamiyat': 'IS',
    'Mathematics': 'MA', 'Chemistry': 'CH', 'Physics': 'PH',
    'Tarjumatul Quran': 'TQ', 'Computer Science': 'CS',
    'Biology': 'BI', 'Bio': 'BI', 'Computer': 'CS',
    'Pak Study': 'PS',
    'Economics': 'EC', 'Civics': 'CV', 'Islamiyat Optional': 'IO',
    # Aliases for lenient matching
    'TA': 'TQ', 'TARJUMA': 'TQ', 'TARJUMATUL': 'TQ',
    'BIO': 'BI', 'BIOLOGY': 'BI',
    'COMP': 'CS', 'COMPUTER': 'CS',
    'MATH': 'MA', 'MATHS': 'MA',
    'ISLAMIAT': 'IS', 'PAKSTUDY': 'PS',
}

# Canonical session per subject.
SUBJECT_SESSION = {
    'Physics': 'morning', 'Chemistry': 'morning', 'Computer Science': 'morning', 'Tarjumatul Quran': 'morning',
    'Biology': 'morning', 'Bio': 'morning', 'Computer': 'morning',
    'Mathematics': 'evening', 'English': 'evening', 'Urdu': 'evening', 'Islamiyat': 'evening',
    'Pak Study': 'evening', 'Economics': 'morning', 'Civics': 'evening', 'Islamiyat Optional': 'morning',
}

def _get_row(student, for_date=None):
    target = for_date or timezone.now().date()
    return StudentDailyCode.objects.filter(student=student, date=target).first()

def get_or_create_row(student, for_date=None):
    target = for_date or timezone.now().date()
    row = _get_row(student, target)
    if row:
        return row
    from exams.management.commands.assign_daily_codes import build_per_book_codes, ALL_SUBJECTS
    pace = student.daily_question_count or 1
    code = random.randint(1, pace)
    subj_codes = {subj: random.randint(1, pace) for subj in ALL_SUBJECTS}
    pbc = build_per_book_codes(student, subj_codes)
    return StudentDailyCode.objects.create(
        student=student, date=target, code=code, per_book_codes=pbc)

def get_subject_code(student, subject, for_date=None):
    """Returns the numeric question number for the subject (or None)."""
    row = get_or_create_row(student, for_date)
    codes = row.per_book_codes or {}
    if not isinstance(codes, dict):
        return None
    abbr = BOOK_ABBR.get(subject, subject[:2].upper() if len(subject) >= 2 else subject.upper())
    morning = codes.get('morning', {})
    evening = codes.get('evening', {})
    return morning.get(abbr) or evening.get(abbr)

def parse_code(code_str):
    """Extract question number from a code like 'PH3', '3', 'Physics3'."""
    if not code_str:
        return None
    m = re.search(r'(\d+)$', str(code_str).strip())
    return int(m.group(1)) if m else None

def verify_code(student, subject, submitted_code, for_date=None):
    """True if submitted_code correctly identifies the question for this subject.

    Accepts formats: 'PH3', 'Physics3', '3', 'P-H-3', 'bio3', 'TA3'.
    """
    if not submitted_code:
        return False, "Test code required."

    stored_num = get_subject_code(student, subject, for_date)
    if stored_num is None:
        return False, f"Code not set by teacher for {subject}."

    abbr = BOOK_ABBR.get(subject, subject[:2].upper() if len(subject) >= 2 else subject.upper())
    
    # Strip all non-alphanumeric characters (spaces, hyphens, etc.)
    submitted_str = re.sub(r'[^A-Z0-9]', '', str(submitted_code).upper())

    m = re.match(r'^([A-Z]*)(\d+)$', submitted_str)
    if not m:
        return False, f"Invalid format. Expected {abbr}3 or the number 3."

    sub_abbr, sub_num = m.groups()
    try:
        sub_num = int(sub_num)
    except ValueError:
        return False, "Invalid code number."

    if sub_num != stored_num:
        return False, f"Wrong question number. Expected {abbr}{stored_num}."

    if sub_abbr:
        # Build a list of acceptable aliases
        aliases = [abbr, subject.upper().replace(' ', '')]
        if 'TARJUMATUL' in subject.upper():
            aliases.extend(['TA', 'TARJUMA', 'TQ'])
        if 'BIOLOGY' in subject.upper():
            aliases.extend(['BIO', 'BI'])
        if 'COMPUTER' in subject.upper():
            aliases.extend(['COMP', 'CS'])
        
        # Check if user's abbreviation matches any acceptable alias
        if sub_abbr not in aliases and not any(a.startswith(sub_abbr) for a in aliases if a):
            return False, f"Code '{submitted_code}' is for a different subject, not {subject}."

    return True, "Code verified."

def verify_code_with_session(student, subject, submitted_code, for_date=None):
    """Session-aware code verification (Phase 1 - Time Gate)."""
    return True, "Code validation disabled by Command 159"
    if not submitted_code:
        return False, "Test code required. Ask your teacher for today's code."

    abbr = BOOK_ABBR.get(subject, subject[:2].upper() if len(subject) >= 2 else subject.upper())
    submitted_str = str(submitted_code).strip().upper()

    # Dynamic format error message based on the subject
    m = re.match(r'^([A-Z]*)(\d+)$', submitted_str)
    if not m:
        return False, f"Invalid code format. Expected {abbr}3, or just the number (e.g., 3)."

    sub_abbr, sub_num_str = m.groups()
    try:
        sub_num = int(sub_num_str)
    except ValueError:
        return False, "Invalid code number."

    if sub_abbr and sub_abbr != abbr and not subject.upper().startswith(sub_abbr):
        return False, f"Code '{submitted_code}' is for a different subject, not {subject}."

    row = get_or_create_row(student, for_date)
    codes = row.per_book_codes or {}
    
    morning_codes = codes.get('morning', {}) or {}
    evening_codes = codes.get('evening', {}) or {}

    morning_code = morning_codes.get(abbr)
    evening_code = evening_codes.get(abbr)

    # Use SUBJECT_SESSION first, instead of just the clock
    subject_expected_session = SUBJECT_SESSION.get(subject, 'morning')
    # 11/12 OVERRIDE: English is a morning subject for 11/12 ONLY
    if student and subject == 'English':
        _cls = (student.student_class or '').strip().lower()
        if _cls.startswith('11') or _cls.startswith('12'):
            subject_expected_session = 'morning'

    if subject_expected_session == 'morning' and morning_code == sub_num:
        return True, ""
    if subject_expected_session == 'evening' and evening_code == sub_num:
        return True, ""

    now = timezone.localtime()
    hour = now.hour
    current_time_session = 'morning' if 7 <= hour < 14 else 'evening'

    if current_time_session == 'morning' and morning_code == sub_num:
        return True, ""
    if current_time_session == 'evening' and evening_code == sub_num:
        return True, ""

    if morning_code is not None and morning_code == sub_num:
        return False, f"This is a Morning code ({submitted_str}), but {subject} is an Evening subject. Please use your Evening code."
    
    if evening_code is not None and evening_code == sub_num:
        return False, f"This is an Evening code ({submitted_str}), but {subject} is a Morning subject. Please use your Morning code."

    if morning_code is None and evening_code is None:
        return False, f"No code set for {subject} today. Ask your teacher."

    return False, f"The code '{submitted_str}' is incorrect. Please check the board and try again."

def edit_code(student, subject, new_code, teacher, for_date=None):
    # Routes to canonical session based on subject name; falls back to existing codes.
    row = get_or_create_row(student, for_date)
    codes = dict(row.per_book_codes or {})
    abbr = BOOK_ABBR.get(subject, subject[:2].upper() if len(subject) >= 2 else subject.upper())
    # 1. canonical map
    session = SUBJECT_SESSION.get(subject)
    # 2. existing bucket (if the subject is already present)
    if session is None:
        if abbr in (codes.get('morning') or {}):
            session = 'morning'
        elif abbr in (codes.get('evening') or {}):
            session = 'evening'
    # 3. order arrays (per-student override)
    if session is None:
        if abbr in (codes.get('morning_order') or []):
            session = 'morning'
        elif abbr in (codes.get('evening_order') or []):
            session = 'evening'
    # 4. last resort — morning
    if session is None:
        session = 'morning'
    session_dict = dict(codes.get(session) or {})
    session_dict[abbr] = int(new_code)
    codes[session] = session_dict
    row.per_book_codes = codes
    row.edited_by = teacher
    row.edited_at = timezone.now()
    row.save(update_fields=['per_book_codes', 'edited_by', 'edited_at'])
    return row

def lock_code(student, teacher, for_date=None):
    row = get_or_create_row(student, for_date)
    row.is_locked = True
    row.locked_by = teacher
    row.locked_at = timezone.now()
    row.save(update_fields=['is_locked', 'locked_by', 'locked_at'])
    return row

def unlock_code(student, teacher, for_date=None):
    row = get_or_create_row(student, for_date)
    row.is_locked = False
    row.locked_by = None
    row.locked_at = None
    row.edited_by = teacher
    row.edited_at = timezone.now()
    row.save(update_fields=['is_locked', 'locked_by', 'locked_at', 'edited_by', 'edited_at'])
    return row
