#!/usr/bin/env python
"""
Education Management Module for BaoLife

This module contains all education-related classes and functions including:
- School classes (Elementary, High School, College)
- Education record management
- Focus and extracurricular activities
- College major definitions

Classes:
    - ElementarySchoolClass: Elementary school location class
    - HighSchoolClass: High school location class
    - CollegeClass: College/university location class
    - CollegeMajorClass: College major definitions
    - FocusClass: Focus types for activities (Work Hard, Slack Off, etc.)
    - ExtraCurricular: Extracurricular activity definitions

Functions:
    - getSchools: Returns lists of elementary and high schools
    - getColleges: Returns list of colleges
    - getMajors: Returns list of college majors
    - getFocuses: Returns list of focus types
    - randomFocus: Returns random focus
    - update_focus: Updates focus for an activity
    - getFocus: Gets focus object by name
    - getExtraCurriculars: Returns list of extracurricular activities
    - randomExtraCurricular: Returns random extracurricular
    - setEducation: Sets up education for a person based on age
    - handleEducation: Handles GPA updates based on focus
    - setExtracurricular: Assigns extracurricular to person
    - applyForExtracurricular: Apply for an extracurricular activity
    - quitExtraCurricular: Quit an extracurricular activity
"""

import random
import uuid


# ============================================================
# Base Classes (imported from parent module)
# ============================================================
# These will be imported from functions.py:
# - locationClass
# - ActivityRecord
# - EducationRecord
# - getPeakEnergy


# ============================================================
# School Location Classes
# ============================================================

class ElementarySchoolClass:
    """
    Elementary School location class (inherits from locationClass)

    Attributes:
        id: Unique identifier
        type: Location type ('elementary_school')
        title: School name
        public_private: 'Public' or 'Private'
        student_count: Number of students
        teacher_student_ratio: Teacher to student ratio
        description: Generated description
        energyModifier: Energy cost (15)
        image: Optional image URL
    """
    def __init__(self, type, school_name, public_private, student_count, teacher_student_ratio, image=None):
        # Import here to avoid circular dependency
        from core.models import locationClass

        self.id = uuid.uuid4().hex
        # Initialize locationClass attributes
        locationClass.__init__(self, self.id, type, image)

        self.title = school_name
        self.public_private = public_private
        self.student_count = student_count
        self.teacher_student_ratio = teacher_student_ratio
        self.type = "elementary_school"
        self.description = "A " + self.public_private + " elementary school with " + str(self.student_count) + " students and a teacher-student ratio of " + str(self.teacher_student_ratio) + "."
        self.energyModifier = 15


class HighSchoolClass:
    """
    High School location class (inherits from locationClass)

    Attributes:
        id: Unique identifier
        type: Location type ('high_school')
        title: School name
        public_private: 'Public' or 'Private'
        student_count: Number of students
        teacher_student_ratio: Teacher to student ratio
        GPA_avg: Average GPA at the school
        description: Generated description
        energyModifier: Energy cost (20)
        image: Optional image URL
    """
    def __init__(self, type, school_name, public_private, student_count, teacher_student_ratio, GPA_avg, image=None):
        # Import here to avoid circular dependency
        from core.models import locationClass

        self.id = uuid.uuid4().hex
        # Initialize locationClass attributes
        locationClass.__init__(self, self.id, type, image)

        self.title = school_name
        self.public_private = public_private
        self.student_count = student_count
        self.teacher_student_ratio = teacher_student_ratio
        self.GPA_avg = GPA_avg
        self.type = "high_school"
        self.description = "A " + self.public_private + " high school with " + str(self.student_count) + " students, a teacher-student ratio of " + str(self.teacher_student_ratio) + ", and an average GPA of " + str(self.GPA_avg) + "."
        self.energyModifier = 20


class CollegeClass:
    """
    College/University location class (inherits from locationClass)

    Attributes:
        id: Unique identifier
        type: Location type ('college')
        title: College name
        public_private: 'Public' or 'Private'
        attendance: Number of students
        GPA_req: Required GPA for admission
        ACT_req: Required ACT score for admission
        specialization: Area of focus
        cost: Annual cost of attendance
        description: Generated description
        energyModifier: Energy cost (20)
        image: Optional image URL
    """
    def __init__(self, type, title, public_private, attendance, GPA_req, ACT_req, specialization, cost, image=None):
        # Import here to avoid circular dependency
        from core.models import locationClass

        self.id = uuid.uuid4().hex
        # Initialize locationClass attributes
        locationClass.__init__(self, self.id, type, image)

        self.title = title
        self.public_private = public_private
        self.attendance = attendance
        self.GPA_req = GPA_req
        self.ACT_req = ACT_req
        self.specialization = specialization
        self.cost = cost
        self.type = "college"
        self.description = "A " + self.public_private + " college with a focus on " + self.specialization + ". The cost of attendance is $" + str(self.attendance) + " per year."
        self.energyModifier = 20


class CollegeMajorClass:
    """
    College Major definition class

    Attributes:
        id: Unique identifier
        title: Major name
        related_jobs: List of job titles related to this major
        colleges: List of college IDs offering this major
    """
    def __init__(self, title, related_jobs, colleges):
        self.id = uuid.uuid4().hex
        self.title = title
        self.related_jobs = related_jobs
        # Store the UUIDs of the colleges
        self.colleges = [college.id for college in colleges]


class FocusClass:
    """
    Focus type for activities (work/study approach)

    Attributes:
        id: Focus ID number
        focus_name: Name of the focus type
        description: Description of the focus
        energyModifier: Energy cost modifier (positive = more energy used)

    Focus Types:
        - Work Hard: +10 energy, improves performance/GPA
        - Slack Off: -10 energy, reduces performance/GPA
        - Socialize: +10 energy, builds relationships
        - Balanced: 0 energy, neutral approach
    """
    def __init__(self, id, focus_name, description, energyModifier):
        self.id = id
        self.focus_name = focus_name
        self.description = description
        self.energyModifier = energyModifier  # Energy cost modifier


class ExtraCurricular:
    """
    Extracurricular activity definition

    Attributes:
        id: Unique identifier
        title: Activity name
        type: Activity type ('extracurricular')
        focus: Default focus type for this activity
        description: Description of the activity
        energyModifier: Energy cost
        image: Optional image URL
    """
    def __init__(self, title, focus, description, energyModifier, image=None):
        self.id = uuid.uuid4().hex
        self.title = title
        self.image = image
        self.type = 'extracurricular'
        self.focus = focus
        self.description = description
        self.energyModifier = energyModifier


# ============================================================
# School Generation Functions
# ============================================================

def getSchools():
    """
    Generate lists of elementary and high schools

    Returns:
        tuple: (elementary_schools, high_schools) lists

    Elementary Schools (6):
        - Maple Elementary School (Public, 350 students)
        - Eagle Private Academy (Private, 200 students)
        - Greenwood Elementary (Public, 400 students)
        - Bright Stars School (Private, 150 students)
        - Lakeview Elementary (Public, 320 students)
        - Grand Oak Elementary (Public, 500 students)

    High Schools (6):
        - Valley High School (Public, 1200 students, 3.2 GPA avg)
        - Prestige Prep School (Private, 600 students, 3.8 GPA avg)
        - Northview High (Public, 1500 students, 2.8 GPA avg)
        - Academic Excellence Institute (Private, 450 students, 4.0 GPA avg)
        - Harmony High (Public, 1400 students, 3.0 GPA avg)
        - Mountain Ridge High (Public, 1300 students, 3.4 GPA avg)
    """
    elementary_schools = []
    high_schools = []

    # Creating 6 elementary schools
    elementary_schools.append(ElementarySchoolClass('Elementary', 'Maple Elementary School', 'Public', 350, 20, 'https://v3b.fal.media/files/b/lion/CpB2aNqv0hZSAt6LAXMPc_output.png'))
    elementary_schools.append(ElementarySchoolClass('Elementary', 'Eagle Private Academy', 'Private', 200, 15, 'https://v3b.fal.media/files/b/zebra/5XWdF5HbjNA-9b4ywu4AZ_output.png'))
    elementary_schools.append(ElementarySchoolClass('Elementary', 'Greenwood Elementary', 'Public', 400, 22, 'https://v3b.fal.media/files/b/koala/AIsZQawDL7vB7Jknjpo9Y_output.png'))
    elementary_schools.append(ElementarySchoolClass('Elementary', 'Bright Stars School', 'Private', 150, 12, 'https://v3b.fal.media/files/b/lion/Bh0Hd9irvCMROr-p_G-84_output.png'))
    elementary_schools.append(ElementarySchoolClass('Elementary', 'Lakeview Elementary', 'Public', 320, 18, 'https://v3b.fal.media/files/b/zebra/IeYo5Q6UCJVUxrgQGLYZL_output.png'))
    elementary_schools.append(ElementarySchoolClass('Elementary', 'Grand Oak Elementary', 'Public', 500, 25, 'https://v3b.fal.media/files/b/kangaroo/NnrqQFCtX_r5TIaqzcicC_output.png'))

    # Creating 6 high schools
    high_schools.append(HighSchoolClass('High', 'Valley High School', 'Public', 1200, 25, 3.2, 'https://v3b.fal.media/files/b/zebra/-KUYF_m7ogEpGacZpibpE_output.png'))
    high_schools.append(HighSchoolClass('High', 'Prestige Prep School', 'Private', 600, 10, 3.8, 'https://v3b.fal.media/files/b/zebra/xnj1-iTDaxz9WJEuiovrV_output.png'))
    high_schools.append(HighSchoolClass('High', 'Northview High', 'Public', 1500, 28, 2.8, 'https://v3b.fal.media/files/b/koala/okbmoh_kANj1YeEDdDfso_output.png'))
    high_schools.append(HighSchoolClass('High', 'Academic Excellence Institute', 'Private', 450, 8, 4.0, 'https://v3b.fal.media/files/b/tiger/PLKjjZXyeUCPu37Ys-YVx_output.png'))
    high_schools.append(HighSchoolClass('High', 'Harmony High', 'Public', 1400, 27, 3.0, 'https://v3b.fal.media/files/b/panda/DcGawkSRWjfBC7Vvzg7r__output.png'))
    high_schools.append(HighSchoolClass('High', 'Mountain Ridge High', 'Public', 1300, 24, 3.4, 'https://v3b.fal.media/files/b/rabbit/MEKUq9oBoHDLVlkyUFaQs_output.png'))

    return elementary_schools, high_schools


def getColleges():
    """
    Generate list of colleges and universities

    Returns:
        list: List of CollegeClass objects

    Colleges (10):
        - University of Science (Public, $10k/yr)
        - Artistic Minds University (Private, $20k/yr)
        - Eastern Commerce College (Public, $8k/yr)
        - Law and Governance University (Private, $25k/yr)
        - Institute of Tech Innovation (Public, $15k/yr)
        - Liberal Arts Academy (Private, $18k/yr)
        - Northern Agriculture College (Public, $12k/yr)
        - Health and Medicine University (Private, $30k/yr)
        - Oceanography Institute (Public, $9k/yr)
        - Performing Arts School (Private, $22k/yr)
    """
    colleges = []

    # Creating 10 colleges with cost
    colleges.append(CollegeClass('College', 'University of Science', 'Public', 15000, 3.5, 28, 'Science and Engineering', 10000, 'https://v3b.fal.media/files/b/tiger/RZeOANHNvGzGJo63zWZii_output.png'))
    colleges.append(CollegeClass('College', 'Artistic Minds University', 'Private', 6000, 3.2, 24, 'Arts and Humanities', 20000, 'https://v3b.fal.media/files/b/zebra/3pim3xDjmslzE5G3tmpPB_output.png'))
    colleges.append(CollegeClass('College', 'Eastern Commerce College', 'Public', 20000, 3.1, 23, 'Business and Economics', 8000, 'https://v3b.fal.media/files/b/monkey/m6iy3jaNX4QQQ1fc8t6uq_output.png'))
    colleges.append(CollegeClass('College', 'Law and Governance University', 'Private', 7000, 3.6, 30, 'Law and Politics', 25000, 'https://v3b.fal.media/files/b/kangaroo/xwKoxESWFmglFxTzHryfn_output.png'))
    colleges.append(CollegeClass('College', 'Institute of Tech Innovation', 'Public', 12000, 3.7, 29, 'Technology and Computer Science', 15000, 'https://v3b.fal.media/files/b/panda/u6oYxXNtV9YzEW3dj-eu3_output.png'))
    colleges.append(CollegeClass('College', 'Liberal Arts Academy', 'Private', 4000, 3.3, 25, 'Liberal Arts', 18000, 'https://v3b.fal.media/files/b/zebra/3pim3xDjmslzE5G3tmpPB_output.png'))
    colleges.append(CollegeClass('College', 'Northern Agriculture College', 'Public', 14000, 3.0, 22, 'Agriculture and Environmental Science', 12000, 'https://v3b.fal.media/files/b/rabbit/zaYHyx9Odqx_n3nNmd0NS_output.png'))
    colleges.append(CollegeClass('College', 'Health and Medicine University', 'Private', 8000, 3.7, 31, 'Health and Medicine', 30000, 'https://v3b.fal.media/files/b/kangaroo/9ZXtAvZoy1qhbdPU91GqE_output.png'))
    colleges.append(CollegeClass('College', 'Oceanography Institute', 'Public', 10000, 3.4, 26, 'Marine Science', 9000, 'https://v3b.fal.media/files/b/monkey/Vn-IR_yaQ9tk2iQzQa5-s_output.png'))
    colleges.append(CollegeClass('College', 'Performing Arts School', 'Private', 5000, 3.2, 24, 'Performing Arts', 22000, 'https://v3b.fal.media/files/b/koala/q8_eoVhSeDNGyCk8kyFzY_output.png'))

    return colleges


def getMajors(colleges):
    """
    Generate list of college majors with associated colleges and careers

    Args:
        colleges (list): List of CollegeClass objects

    Returns:
        list: List of CollegeMajorClass objects

    Majors (15):
        - Computer Science → Software Engineer
        - Nursing → Registered Nurse
        - Education → Teachers, Counselor
        - Criminal Justice → Police Officer
        - Accounting → Accountant
        - Culinary Arts → Chef
        - Law → Lawyer
        - Automotive Technology → Automotive Mechanic
        - Business → Sales Rep, Real Estate Agent
        - Architecture → Architect
        - Medicine → Physician, Dentist, Pharmacist
        - Library Science → Librarian
        - Journalism → Journalist
        - Psychology → Counselor
        - Veterinary Medicine → Veterinarian
    """
    majors = []

    # Associate majors with colleges using the colleges' UUIDs
    majors.append(CollegeMajorClass('Computer Science', ['Software Engineer'], [colleges[0], colleges[4]]))
    majors.append(CollegeMajorClass('Nursing', ['Registered Nurse'], [colleges[7]]))
    majors.append(CollegeMajorClass('Education', ['High School Teacher', 'Elementary School Teacher', 'Counselor'], [colleges[5]]))
    majors.append(CollegeMajorClass('Criminal Justice', ['Police Officer'], [colleges[3]]))
    majors.append(CollegeMajorClass('Accounting', ['Accountant'], [colleges[2]]))
    majors.append(CollegeMajorClass('Culinary Arts', ['Chef'], [colleges[1], colleges[9]]))
    majors.append(CollegeMajorClass('Law', ['Lawyer'], [colleges[3]]))
    majors.append(CollegeMajorClass('Automotive Technology', ['Automotive Mechanic'], [colleges[0]]))
    majors.append(CollegeMajorClass('Business', ['Sales Representative', 'Real Estate Agent'], [colleges[2]]))
    majors.append(CollegeMajorClass('Architecture', ['Architect'], [colleges[0], colleges[4]]))
    majors.append(CollegeMajorClass('Medicine', ['Physician', 'Dentist', 'Pharmacist'], [colleges[7]]))
    majors.append(CollegeMajorClass('Library Science', ['Librarian'], [colleges[5]]))
    majors.append(CollegeMajorClass('Journalism', ['Journalist'], [colleges[1]]))
    majors.append(CollegeMajorClass('Psychology', ['Counselor'], [colleges[5], colleges[7]]))
    majors.append(CollegeMajorClass('Veterinary Medicine', ['Veterinarian'], [colleges[6]]))

    return majors


# ============================================================
# Focus Management Functions
# ============================================================

def getFocuses():
    """
    Get list of available focus types for activities

    Returns:
        list: List of FocusClass objects

    Focus Types:
        1. Work Hard: +10 energy cost, improves performance/GPA
        2. Slack Off: -10 energy cost, reduces performance/GPA
        3. Socialize: +10 energy cost, builds relationships
        4. Balanced: 0 energy cost, neutral approach
    """
    focuses = []
    focuses.append(FocusClass(1, 'Work Hard', 'Work hard to get ahead', 10))
    focuses.append(FocusClass(2, 'Slack Off', 'Slack off at work to avoid stress', -10))
    focuses.append(FocusClass(3, 'Socialize', 'Socialize with others to build relationships', 10))
    focuses.append(FocusClass(4, 'Balanced', 'Balance work and socializing', 0))
    return focuses


def randomFocus():
    """
    Get a random focus type

    Returns:
        FocusClass: Random focus object
    """
    return random.choice(getFocuses())


def getFocus(focusName):
    """
    Get focus object by name

    Args:
        focusName (str): Name of the focus type

    Returns:
        FocusClass: Matching focus object or None
    """
    for focus in getFocuses():
        if focus.focus_name == focusName:
            return focus
    return None


def update_focus(player, activity_id, new_focus):
    """
    Update the focus for a specific activity

    Args:
        player: Player object containing character
        activity_id (str): ID of the activity to update
        new_focus (str): Name of the new focus type

    Updates:
        - Changes the focus in the activity record
        - Recalculates peak energy for the character
    """
    # Import here to avoid circular dependency
    from stats.stats_manager import getPeakEnergy

    for activityRecord in player.c.activityRecords:
        if str(activityRecord.id).strip() == str(activity_id).strip():
            print(activityRecord.focus + " -> " + new_focus)
            new_focus = getFocus(new_focus)
            print("peak energy change " + str(player.c.peakEnergy) + " + " + str(new_focus.energyModifier) + " -> " + str(player.c.peakEnergy + new_focus.energyModifier))
            activityRecord.focus = new_focus.focus_name
            getPeakEnergy(player.c)
            break
    else:
        print("No matching activity found.")


# ============================================================
# Extracurricular Management Functions
# ============================================================

def getExtraCurriculars():
    """
    Get list of available extracurricular activities

    Returns:
        list: List of ExtraCurricular objects

    Activities (9):
        - Choir (Work Hard, 20 energy)
        - Musical Theater (Socialize, 30 energy)
        - Debate Team (Work Hard, 20 energy)
        - Writing Club (Balanced, 10 energy)
        - Robotics Team (Work Hard, 40 energy)
        - Baseball (Socialize, 20 energy)
        - Basketball (Socialize, 30 energy)
        - Soccer (Socialize, 30 energy)
        - Football (Socialize, 40 energy)
    """
    extraCurriculars = []
    extraCurriculars.append(ExtraCurricular('Choir', 'Work Hard', 'Perfect your singing skills and perform in concerts', 20, 'https://media.discordapp.net/attachments/1106614533402931284/1122691487180795965/craig_vg_school_choir_class_cute_cartoon_style_ba317c8f-6ed0-4955-84cd-faeeff28ee68.png?ex=6600cb6d&is=65ee566d&hm=4dae9a84443a033d8e62046463f6605ef7d250e83a6333436117c152b9169ece&=&format=png&quality=lossless&width=526&height=526'))
    extraCurriculars.append(ExtraCurricular('Musical Theater', 'Socialize', 'Perform in musicals and bond with the cast', 30, 'https://media.discordapp.net/attachments/1106614533402931284/1122692114644484197/craig_vg_Musical_theater_class_cute_cartoon_style_615a8d72-6c01-445e-b2da-ff0f19ede550.png?ex=6600cc02&is=65ee5702&hm=57b2eddb164479b16e47540ffdadf5f0169d390588d8574db07ef7e0d19fa856&=&format=png&quality=lossless&width=526&height=526'))
    extraCurriculars.append(ExtraCurricular('Debate Team', 'Work Hard', 'Develop your debating skills and compete against other teams', 20, 'https://cdn.discordapp.com/attachments/1106614533402931284/1218745363201134603/craig_vg_debate_team_class_cute_cartoon_style_595c6e7a-b077-47e7-b62c-669464404a69.png?ex=6608c811&is=65f65311&hm=85b9709dcb26d575d301a7f16eaae9cc2795a51ad44f6adc7418b292f77c89ea&'))
    extraCurriculars.append(ExtraCurricular('Writing Club', 'Balanced', 'Improve your writing and share ideas with other members', 10, 'https://media.discordapp.net/attachments/1106614533402931284/1122923754650079362/craig_vg_writing_club_class_school_cute_cartoon_style_aa1e50e1-3d12-45f1-84df-5e2a743b72b9.png?ex=6601a3be&is=65ef2ebe&hm=cfc45cd684013596ab1d56ea8c0d58ddd12572de3062810a617b02ac400935ab&=&format=png&quality=lossless&width=526&height=526'))
    extraCurriculars.append(ExtraCurricular('Robotics Team', 'Work Hard', 'Design and build robots for competitions', 40, 'https://cdn.discordapp.com/attachments/1106614533402931284/1122923789412483123/craig_vg_robotics_team_school_cute_cartoon_style_892517c3-f69a-4748-8d13-44a91809e392.png?ex=6601a3c6&is=65ef2ec6&hm=17c0fe3680c5df5ba682952ba310ce16ce62e7ae3d98b667abe2074e0611822a&'))
    extraCurriculars.append(ExtraCurricular('Baseball', 'Socialize', 'Play baseball and spend time with teammates', 20, 'https://cdn.discordapp.com/attachments/1106614533402931284/1122692176917315595/craig_vg_baseball_team_cute_cartoon_style_941e60c1-1d96-43ef-b6eb-d1e9e3339836.png?ex=6600cc11&is=65ee5711&hm=fdf5b18fb53b4281af65611724565bfd149f63b18d4fa719b91b171ff5d9844c&'))
    extraCurriculars.append(ExtraCurricular('Basketball', 'Socialize', 'Play basketball and bond with teammates', 30, 'https://cdn.discordapp.com/attachments/1106614533402931284/1122924183979040798/craig_vg_basketball_team_kids_cute_cartoon_style_4ce4fddf-4520-40ea-97cc-ddecbac6f7e9.png?ex=6601a424&is=65ef2f24&hm=7bc865567e44ca301b6250a29ddba093b16cdff19c4d6924ecfc5c0e3deee2dd&'))
    extraCurriculars.append(ExtraCurricular('Soccer', 'Socialize', 'Play soccer and spend time with teammates', 30, 'https://cdn.discordapp.com/attachments/1106614533402931284/1122692364624986174/craig_vg_soccer_team_class_cute_cartoon_style_b6f60c0f-36a3-4326-b108-fa7935991cf7.png?ex=6600cc3e&is=65ee573e&hm=a50d45a8bf073dbd1bd0c6005a2781414f87d16d7aa1f60ff2fa0c3eae9139b8&'))
    extraCurriculars.append(ExtraCurricular('Football', 'Socialize', 'Play football and bond with teammates', 40, 'https://cdn.discordapp.com/attachments/1106614533402931284/1122924237175394344/craig_vg_american_football_team_cute_cartoon_style_9dc1adfc-bed7-445c-a7d8-333620f0e91f.png?ex=6601a431&is=65ef2f31&hm=4ebd26a3ba5b24a716dab9e108db8ff9fb037b9a38b74e3faca8f1fc754df8e5&'))

    return extraCurriculars


def randomExtraCurricular(player):
    """
    Get a random extracurricular activity from player's list

    Args:
        player: Player object containing extraCurriculars list

    Returns:
        ExtraCurricular: Random extracurricular object
    """
    return random.choice(player.extraCurriculars)


def setExtracurricular(person, extraCurricularClass, date):
    """
    Assign an extracurricular activity to a person

    Args:
        person: Person object to assign activity to
        extraCurricularClass: ExtraCurricular object to assign
        date: Date the activity was started

    Updates:
        - Adds activity to person.activities
        - Creates and adds ActivityRecord
    """
    # Import here to avoid circular dependency
    from core.models import ActivityRecord

    print("setting extracurricular" + extraCurricularClass.title + date)
    person.activities.append(extraCurricularClass)
    person.activityRecords.append(ActivityRecord(extraCurricularClass.id, extraCurricularClass.type, date))


def applyForExtracurricular(player, extracurricularID):
    """
    Apply for an extracurricular activity

    Args:
        player: Player object
        extracurricularID (str): ID of the extracurricular to apply for

    Updates:
        - Assigns extracurricular to player character
        - Creates classmates for the activity
        - Adds message to message queue
    """
    # Import here to avoid circular dependency
    from character.character_manager import create_classmates

    for extracurricular in player.extraCurriculars:
        if (extracurricular.id == extracurricularID):
            setExtracurricular(player.c, extracurricular, player.date)
            player.messageQueue.append("You have applied for " + extracurricular.title + ".")
            player = create_classmates(player, extracurricular)


def quitExtraCurricular(player, extraCurricularID):
    """
    Quit an extracurricular activity

    Args:
        player: Player object
        extraCurricularID (str): ID of the extracurricular to quit

    Updates:
        - Removes activity from player.c.activities
        - Removes activity record from player.c.activityRecords
        - Adds message to message queue
    """
    for extracurricular in player.extraCurriculars:
        if (extracurricular.id == extraCurricularID):
            for activity in player.c.activities:
                if (activity.id == extracurricular.id):
                    player.c.activities.remove(activity)
            for record in player.c.activityRecords:
                if (record.id == extracurricular.id):
                    player.c.activityRecords.remove(record)
            player.messageQueue.append("You have quit " + extracurricular.title + ".")


# ============================================================
# Education Management Functions
# ============================================================

def handleEducation(person):
    """
    Update GPA based on focus and intelligence

    This function is called during the game loop to update a student's
    academic performance based on their current focus.

    Args:
        person: Person object with current_education attribute

    Updates:
        - Modifies GPA in the person's education activity record
        - GPA increases more with 'Work Hard' focus
        - GPA decreases more with 'Slack Off' focus
        - GPA is clamped between 0 and 100
    """
    if (getattr(person, 'current_education', False)):
        # Find activity record and update GPA
        for index, item in enumerate(person.activityRecords):
            if item.id == person.current_education.id:
                GPA_modifier = 0
                if (person.current_education.focus == 'Work Hard'):
                    GPA_modifier = 1
                elif (person.current_education.focus == 'Slack Off'):
                    GPA_modifier = -1
                person.activityRecords[index].GPA += random.randint(-1, 1 + GPA_modifier)
                if (person.activityRecords[index].GPA > 100):
                    person.activityRecords[index].GPA = 100
                if (person.activityRecords[index].GPA < 0):
                    person.activityRecords[index].GPA = 0


def setEducation(player, person):
    """
    Set up education for a person based on their age

    This function assigns appropriate education level, school, and creates
    education records for a person. Called during character initialization
    and birthdays.

    Args:
        player: Player object containing schools and colleges lists
        person: Person object to set education for

    Updates:
        - Sets person.education (grade level or degree type)
        - Assigns elementary_school, high_school, or college
        - Adds school to person.activities
        - Creates EducationRecord in person.activityRecords
        - Sets person.current_education
        - Sets person.occupation ('student', 'school', or 'work')

    Education Levels by Age:
        5: kindergarten
        6-11: 1st-6th grade (elementary_school)
        12-14: 7th-9th grade (elementary_school)
        15-17: 10th-12th grade (high_school)
        18+: college (60% chance)
            18: college yr 1
            19+: associate_degree (65% chance)
            20: college yr 3 (35% chance of continuing)
            21+: bachelors_degree
            (20% chance): doctorate_degree

    Returns:
        person: Updated person object
    """
    # Import here to avoid circular dependency
    from core.models import EducationRecord

    school = None

    # Set education level based on age
    if (person.ageYears == 5):
        person.education = "kindergarten"
    if (person.ageYears == 6):
        person.education = "1st"
    if (person.ageYears == 7):
        person.education = "2nd"
    if (person.ageYears == 8):
        person.education = "3rd"
    if (person.ageYears == 9):
        person.education = "4th"
    if (person.ageYears == 10):
        person.education = "5th"
    if (person.ageYears == 11):
        person.education = "6th"
    if (person.ageYears == 12):
        person.education = "7th"
    if (person.ageYears == 13):
        person.education = "8th"
    if (person.ageYears == 14):
        person.education = "9th"
    if (person.ageYears == 15):
        person.education = "10th"
    if (person.ageYears == 16):
        person.education = "11th"
    if (person.ageYears == 17):
        person.education = "high_school"

    # Assign school based on age
    if (person.ageYears < 14):
        person.elementary_school = random.choice(player.elementary_schools)
        person.activities.append(person.elementary_school)
    elif (person.ageYears < 18):
        person.high_school = random.choice(player.high_schools)
        person.activities.append(person.high_school)

    # Determine if person goes to college (60% chance)
    collegeRatio = random.random()
    if person.ageYears >= 18 and collegeRatio >= .6:
        person.occupation = 'school'
        if (person.ageYears == 18):
            person.education = "college yr 1"
        if (person.ageYears >= 19):
            person.education = "associate_degree"
        if (collegeRatio >= .35):
            if (person.ageYears == 20):
                person.education = "college yr 3"
            if (person.ageYears >= 21):
                person.education = "bachelors_degree"
            if (collegeRatio > .2):
                person.education = "doctorate_degree"
        person.college = random.choice(player.colleges)
        person.activities.append(person.college)
    else:
        person.occupation = 'work'

    # Create education records
    if (person.elementary_school):
        person.current_education = EducationRecord(educationLevel=person.education, location=person.elementary_school, date=player.date)
        person.activityRecords.append(person.current_education)
    if (person.high_school):
        person.current_education = EducationRecord(educationLevel=person.education, location=person.high_school, date=player.date)
        person.activityRecords.append(person.current_education)
    if (person.college):
        person.current_education = EducationRecord(educationLevel=person.education, location=person.college, date=player.date)
        person.activityRecords.append(person.current_education)

    # Set occupation for children
    if person.ageYears < 18 and person.ageYears > 4:
        person.occupation = 'student'

    return person
