"""
School Year Events
Specific school year milestones and experiences (from EVENT_IDEAS_QUICK_WINS.md section 6)

Events:
- summerReading: Summer reading assignment for school
- classRankReveal: Finding out class rank
- seniorSurvey: Yearbook survey/superlatives
- finalExamWeek: Stress of finals week
- summerJobSearch: Looking for summer employment
- promInvite: Being asked to prom or asking someone
- dormRoommate: Meeting college roommate for first time
- seniorSkipDay: Participating in senior skip day
- collegeHomesick: Homesickness in first semester
- changeMyMajor: Doubting chosen major
"""

import random
from events.base import messageFunction, questionFunction, answerOption


def summerReading(player, type='message', message=False, response=False):
    """Summer reading assignment for school"""
    fname = 'summerReading'

    # Get current month from player.date (format: MM-DD)
    current_month = int(player.date.split('-')[0])

    # Trigger during June-August (months 6-8) for students ages 10-17
    check = (fname not in player.askedQuestions
             and player.c.occupation == 'student'
             and player.c.ageYears >= 10
             and player.c.ageYears <= 17
             and current_month >= 6
             and current_month <= 8
             and random.random() < 0.1)

    message = "You have to read a book for summer homework. When do you do it?"
    answerOptions = [
        answerOption('Right away in June', energyCost=15),
        answerOption('Throughout the summer'),
        answerOption('Last week of summer', energyCost=30),
        answerOption("Don't read it")
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == answerOptions[0].option):
            # Right away in June - costs 15 energy
            if player.c.energy >= 15:
                player.c.energy -= 15
            else:
                player.c.energy = max(0, player.c.energy)
            player.messageQueue.append("You finish your summer reading right away. Now you can enjoy the rest of your summer worry-free!")
            player.c.happiness -= 10
            player.c.intelligence += 5
        elif (response['option'] == answerOptions[1].option):
            player.messageQueue.append("You pace yourself and read a little bit throughout the summer. Smart approach!")
            player.c.intelligence += 3
        elif (response['option'] == answerOptions[2].option):
            # Last week of summer - costs 30 energy
            if player.c.energy >= 30:
                player.c.energy -= 30
            else:
                player.c.energy = max(0, player.c.energy)
            player.messageQueue.append("You scramble to finish the book in the last week of summer. The stress was intense, but you got it done!")
            player.c.happiness -= 20
            player.c.intelligence += 2
        elif (response['option'] == answerOptions[3].option):
            player.messageQueue.append("You decide not to read the book. The first day back to school is going to be rough...")
            player.c.happiness -= 10


def classRankReveal(player, type='message'):
    """Finding out class rank"""
    fname = 'classRankReveal'
    check = (fname not in player.events
             and player.c.occupation == 'student'
             and player.c.ageYears >= 16
             and player.c.ageYears <= 17
             and player.c.education in ['11th', '12th']
             and random.random() < 0.05)

    if not check:
        return False

    # Determine message based on intelligence level (using as proxy for GPA)
    intelligence = getattr(player.c, 'intelligence', 50)

    if intelligence >= 70:
        message = "You're in the top 10% of your class! You feel proud of your academic achievement."
        player.c.happiness += 15
    elif intelligence >= 40:
        message = "You're in the middle of your class. Not bad! You're doing just fine academically."
        player.c.happiness += 5
    else:
        message = "Your class rank is lower than you hoped. Time to study harder?"
        player.c.happiness -= 5

    return messageFunction(fname, message, player, check)


def seniorSurvey(player, type='message', message=False, response=False):
    """Yearbook survey/superlatives"""
    fname = 'seniorSurvey'
    check = (fname not in player.askedQuestions
             and player.c.occupation == 'student'
             and player.c.ageYears >= 17
             and player.c.ageYears <= 18
             and player.c.education == '12th'
             and random.random() < 0.1)

    message = "The yearbook committee wants to give you a superlative. Which fits best?"

    # Stat-based options (player can choose what best represents them)
    answerOptions = [
        'Most Likely to Succeed',
        'Class Clown',
        'Most Athletic',
        'Biggest Bookworm',
        'Most Social'
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        choice = response['option']
        player.messageQueue.append(f"'{choice}' - that sounds about right! You're excited to see it in the yearbook.")
        player.c.happiness += 10

        # Small stat boost based on choice
        if choice == 'Most Likely to Succeed':
            player.c.intelligence += 3
        elif choice == 'Class Clown':
            player.c.social += 5
        elif choice == 'Most Athletic':
            player.c.energy += 5
        elif choice == 'Biggest Bookworm':
            player.c.intelligence += 5
        elif choice == 'Most Social':
            player.c.social += 8


def finalExamWeek(player, type='message'):
    """Stress of finals week"""
    fname = 'finalExamWeek'

    # Get current month from player.date (format: MM-DD)
    current_month = int(player.date.split('-')[0])

    # Trigger in May-June (end of spring semester) or December (end of fall semester)
    # For students ages 14-22 (high school and college)
    check = (fname not in player.events
             and player.c.occupation == 'student'
             and player.c.ageYears >= 14
             and player.c.ageYears <= 22
             and (current_month == 5 or current_month == 6 or current_month == 12)
             and random.random() < 0.15)

    if not check:
        return False

    message = "It's finals week. You're surviving on coffee and stress. Almost there!"
    player.c.energy -= 20
    player.c.happiness -= 10

    return messageFunction(fname, message, player, check)


def summerJobSearch(player, type='message', message=False, response=False):
    """Looking for summer employment"""
    fname = 'summerJobSearch'

    # Get current month from player.date (format: MM-DD)
    current_month = int(player.date.split('-')[0])

    # Trigger in April-May for students ages 15-21
    check = (fname not in player.askedQuestions
             and player.c.occupation == 'student'
             and player.c.ageYears >= 15
             and player.c.ageYears <= 21
             and current_month >= 4
             and current_month <= 5
             and random.random() < 0.1)

    message = "Summer is coming. Do you want to get a summer job?"
    answerOptions = [
        'Yes, find a job',
        'Volunteer instead',
        'Focus on summer activities',
        'Take it easy'
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == answerOptions[0]):
            player.messageQueue.append("You decide to look for a summer job. Time to start earning some money!")
            # Could trigger firstJob event if not employed
            player.c.happiness += 5
        elif (response['option'] == answerOptions[1]):
            player.messageQueue.append("You sign up to volunteer over the summer. It feels good to give back to the community!")
            player.c.social += 20
            player.c.happiness += 10
        elif (response['option'] == answerOptions[2]):
            player.messageQueue.append("You focus on summer camps and activities instead. Should be a fun summer!")
            player.c.happiness += 15
        elif (response['option'] == answerOptions[3]):
            player.messageQueue.append("You decide to take it easy this summer. Rest and relaxation sounds perfect!")
            player.c.energy += 20


def promInvite(player, type='message', message=False, response=False):
    """Being asked to prom or asking someone"""
    fname = 'promInvite'

    # Get current month from player.date (format: MM-DD)
    current_month = int(player.date.split('-')[0])

    # Trigger in March-April for 11th-12th graders (ages 16-18)
    check = (fname not in player.askedQuestions
             and player.c.occupation == 'student'
             and player.c.ageYears >= 16
             and player.c.ageYears <= 18
             and player.c.education in ['11th', '12th']
             and current_month >= 3
             and current_month <= 4
             and random.random() < 0.15)

    message = "Prom is coming up! What's your plan?"

    # Check if player has a partner
    from functions import get_partner
    partner = get_partner(player)

    if partner:
        answerOptions = [
            answerOption('Go with partner', moneyCost=200),
            answerOption('Skip it')
        ]
    else:
        answerOptions = [
            answerOption('Ask someone you like', diamondCost=5),
            answerOption('Go with friends', moneyCost=150),
            answerOption('Skip it')
        ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        choice = response['option']

        if 'Go with partner' in choice:
            # Costs 200 money
            if player.c.money >= 200:
                player.c.money -= 200
            else:
                player.c.money = max(0, player.c.money)
                player.c.stress += 10  # Stress from not affording it fully
            player.messageQueue.append("You and your partner have an amazing time at prom! It's a night you'll never forget.")
            player.c.happiness += 20
            if partner:
                from functions import updateAffinity
                updateAffinity(player, partner, 10)
        elif 'Ask someone you like' in choice:
            # Costs 5 diamonds
            if player.c.diamonds >= 5:
                player.c.diamonds -= 5
            else:
                player.c.diamonds = max(0, player.c.diamonds)
            # Random chance they say yes
            if random.random() < 0.7:
                player.messageQueue.append("They said yes! You're so excited for prom night.")
                player.c.happiness += 25
                player.c.social += 10
            else:
                player.messageQueue.append("They politely decline. It stings, but you'll get through it.")
                player.c.happiness -= 15
        elif 'Go with friends' in choice:
            # Costs 150 money
            if player.c.money >= 150:
                player.c.money -= 150
            else:
                player.c.money = max(0, player.c.money)
                player.c.stress += 10  # Stress from not affording it fully
            player.messageQueue.append("You and your friends have a blast at prom! Who needs a date anyway?")
            player.c.happiness += 18
            player.c.social += 15
        elif 'Skip it' in choice:
            player.messageQueue.append("You decide to skip prom. Maybe you'll regret it someday, or maybe not.")
            player.c.happiness -= 5


def dormRoommate(player, type='message', message=False, response=False):
    """Meeting college roommate for first time"""
    fname = 'dormRoommate'

    # Get current month from player.date (format: MM-DD)
    current_month = int(player.date.split('-')[0])

    # Trigger in late August for college year 1, age 18
    check = (fname not in player.askedQuestions
             and player.c.occupation == 'student'
             and player.c.ageYears == 18
             and player.c.education == 'college yr 1'
             and current_month == 8
             and random.random() < 0.2)

    message = "You meet your randomly assigned college roommate for the first time. First impressions?"
    answerOptions = [
        'They seem cool!',
        'Seems awkward...',
        answerOption('Request a room change', moneyCost=100)
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == answerOptions[0].option):
            player.messageQueue.append("Your roommate seems really cool! You think you're going to get along great.")
            player.c.happiness += 10
            player.c.social += 15
            # Could create a roommate NPC here
        elif (response['option'] == answerOptions[1].option):
            player.messageQueue.append("The first meeting is a bit awkward, but maybe it'll get better with time.")
            player.c.happiness -= 5
            player.c.social += 5
        elif (response['option'] == answerOptions[2].option):
            # Request room change - costs 100 money
            if player.c.money >= 100:
                player.c.money -= 100
            else:
                player.c.money = max(0, player.c.money)
                player.c.stress += 10  # Stress from not affording it fully
            player.messageQueue.append("You request a room change. The housing office says they'll see what they can do.")
            player.c.happiness -= 10


def seniorSkipDay(player, type='message', message=False, response=False):
    """Participating in senior skip day"""
    fname = 'seniorSkipDay'

    # Get current month from player.date (format: MM-DD)
    current_month = int(player.date.split('-')[0])

    # Trigger in spring (March-May) for seniors (ages 17-18, 12th grade)
    check = (fname not in player.askedQuestions
             and player.c.occupation == 'student'
             and player.c.ageYears >= 17
             and player.c.ageYears <= 18
             and player.c.education == '12th'
             and current_month >= 3
             and current_month <= 5
             and random.random() < 0.1)

    message = "It's the unofficial senior skip day. Do you skip?"
    answerOptions = [
        'Yes, skip with friends!',
        'No, perfect attendance',
        'Half day compromise'
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == answerOptions[0]):
            player.messageQueue.append("You skip school with your friends and have an amazing day! Senior year memories!")
            player.c.happiness += 15
            player.c.social += 20
        elif (response['option'] == answerOptions[1]):
            player.messageQueue.append("You go to school while most of your class is absent. The teachers appreciate your dedication, but you feel a bit lame.")
            player.c.happiness -= 10
            player.c.social -= 15
            player.c.intelligence += 5
        elif (response['option'] == answerOptions[2]):
            player.messageQueue.append("You attend morning classes then leave early. A reasonable compromise!")
            player.c.happiness += 5
            player.c.social += 10


def collegeHomesick(player, type='message'):
    """Homesickness in first semester"""
    fname = 'collegeHomesick'

    # Get current month from player.date (format: MM-DD)
    current_month = int(player.date.split('-')[0])

    # Trigger in September-October for college year 1, age 18
    check = (fname not in player.events
             and player.c.occupation == 'student'
             and player.c.ageYears == 18
             and player.c.education == 'college yr 1'
             and current_month >= 9
             and current_month <= 10
             and random.random() < 0.15)

    if not check:
        return False

    message = "You're homesick. You miss your family, your room, even your old school. You call home and feel a little better."
    player.c.happiness -= 10

    # Slight affinity boost with family members
    from functions import get_allFamily
    family = get_allFamily(player)
    if family and len(family) > 0:
        # Boost affinity with a random family member
        import random as rand
        family_member = rand.choice(family)
        from functions import updateAffinity
        updateAffinity(player, family_member, 5)

    return messageFunction(fname, message, player, check)


def changeMyMajor(player, type='message', message=False, response=False):
    """Doubting chosen major"""
    fname = 'changeMyMajor'

    # Trigger during college years 1-2 (ages 18-20)
    check = (fname not in player.askedQuestions
             and player.c.occupation == 'student'
             and player.c.ageYears >= 18
             and player.c.ageYears <= 20
             and player.c.education in ['college yr 1', 'college yr 2']
             and hasattr(player.c, 'major')
             and player.c.major
             and random.random() < 0.08)

    message = "You're not sure about your major anymore. Change it?"
    answerOptions = [
        'Yes, switch majors',
        'No, stick with it',
        answerOption('Add a double major', energyCost=40, diamondCost=10),
        'Take time to decide'
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == answerOptions[0].option):
            player.messageQueue.append("You decide to switch your major. It might add time to your degree, but you feel much better about your choice!")
            player.c.happiness += 15
            # Could trigger chooseMajor event here or set a flag
            # For now, just mark that they're reconsidering
            player.c.changingMajor = True
        elif (response['option'] == answerOptions[1].option):
            player.messageQueue.append("You decide to stick with your current major. Sometimes you just have to push through the doubt.")
            player.c.happiness -= 5
        elif (response['option'] == answerOptions[2].option):
            # Add double major - costs 40 energy and 10 diamonds
            if player.c.energy >= 40:
                player.c.energy -= 40
            else:
                player.c.energy = max(0, player.c.energy)
            if player.c.diamonds >= 10:
                player.c.diamonds -= 10
            else:
                player.c.diamonds = max(0, player.c.diamonds)
                player.c.stress += 10  # Stress from not affording it fully
            player.messageQueue.append("You add a double major! It's going to be a lot of work, but you're excited about the challenge.")
            player.c.happiness += 10
            player.c.doubleMajor = True
        elif (response['option'] == answerOptions[3].option):
            player.messageQueue.append("You give yourself time to think it over. No need to rush such an important decision.")
            player.c.happiness += 5


# Export all event functions
__all__ = [
    'summerReading',
    'classRankReveal',
    'seniorSurvey',
    'finalExamWeek',
    'summerJobSearch',
    'promInvite',
    'dormRoommate',
    'seniorSkipDay',
    'collegeHomesick',
    'changeMyMajor',
]
