"""
Annual Holiday Events
Date-specific holiday celebrations

Events from dayEvents.py:
- christmas: Christmas celebration (12-25)
- newYear: New Year celebration (01-01)
- thanksgiving: Thanksgiving celebration (11-23)
- blackfriday: Black Friday (11-24)
- independenceday: Independence Day (07-04)
- birthday: Player's birthday
- immunizations: Childhood immunizations
- vacation: Family vacation
- newFood: Trying new foods

New holiday events:
- halloween: Halloween costume and trick-or-treating (10-31)
- valentinesDay: Valentine's Day celebration (02-14)
- easterEggHunt: Easter egg hunting (04-10)
- backToSchoolShopping: Back-to-school shopping (08-20 to 08-31)
- springCleaning: Spring cleaning task (03-15 to 04-15)
- mothersDayForgot: Forgetting Mother's Day (05-08 to 05-14)
- summerFirstDayPool: First day at pool/beach (06-01 to 06-07)
- snowDay: School/work cancelled due to snow (12-01 to 02-28)
- newYearsResolution: New Year's resolutions (01-01)
- blackFridayChaos: Black Friday shopping (11-24)
"""

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


def christmas(player, type='message'):
    fname = f'christmas_{player.c.ageYears}'  # Year-specific event ID
    check = fname not in player.events and player.date == '12-25'
    if (check):
        player.dayEvent = 'christmas'
        return messageFunction(fname,'You have celebrated Christmas!',player,check)


def newYear(player, type='message'):
    fname = f'newyear_{player.c.ageYears}'  # Year-specific event ID
    check = fname not in player.events and player.date == '01-01'
    if (check):
        player.dayEvent = 'newyear'
        return messageFunction(fname,'You have celebrated New Years!',player,check)


def thanksgiving(player, type='message'):
    fname = f'thanksgiving_{player.c.ageYears}'  # Year-specific event ID
    check = fname not in player.events and player.date == '11-23'
    if (check):
        player.dayEvent = 'thanksgiving'
        return messageFunction(fname,'You have celebrated Thanksgiving!',player,check)


def blackfriday(player, type='message'):
    fname = f'blackfriday_{player.c.ageYears}'  # Year-specific event ID
    check = fname not in player.events and player.date == '11-24'
    if (check):
        player.dayEvent = 'blackfriday'
        return messageFunction(fname,'It is Black Friday',player,check)


def independenceday(player, type='message'):
    fname = f'independenceday_{player.c.ageYears}'  # Year-specific event ID
    check = fname not in player.events and player.date == '07-04'
    if (check):
        player.dayEvent = 'independenceday'
        return messageFunction(fname,'You have celebrated Independence Day',player,check)


def birthday(player, type='message', message=False, response=False):
    fname = f'birthday_{player.c.ageYears}'  # Year-specific event ID

    check = fname not in player.askedQuestions and player.c.ageDays > 0 and player.c.ageDays % 365 == 0
    if (check and type != 'answer'):
        message = "It's your birthday! How would you like to spend it?"
        from functions import get_random_friend,get_random_family
        answerOptions = []
        if (get_random_family(player)):
            answerOptions.append("Spend it with family.")
        if (get_random_friend(player)):
            answerOptions.append("Spend it with friends.")
        answerOptions.append("Spend it alone, doing what you enjoy.")
        return questionFunction(fname,message,player,True,answerOptions)
    elif (type == 'answer'):
        player.askedQuestions.add(fname)
        if (response['option'] == 'Spend it with family.'):
            player.c.happiness += 15
            for p in player.r:
                if (p.familyLevel == 1):
                    p.affinity += 15
                elif (p.familyLevel == 2):
                    p.affinity += 5
        if (response['option'] == 'Spend it with friends.'):
            player.c.happiness += 15
            for p in player.r:
                if ("friend" in p.relationships):
                    p.affinity += 15
        if (response['option'] == 'Spend it alone, doing what you enjoy.'):
            player.c.happiness += 15
            player.c.stress -= 15


def immunizations(player, type='message'):
    fname = 'immunizations'
    check = fname not in player.events and player.c.ageYears >= 4 and player.c.ageYears <= 6 and random.random() < .01
    if (check):
        player.events.add(fname)
        player.c.immunizations = True
        return messageFunction(fname,'You have received your immunizations',player,check)


def vacation(player, type='message'):
    fname = 'vacation'
    check = fname not in player.events and player.c.ageYears >= 4 and player.c.ageYears <= 6 and random.random() < .01
    if (check):
        player.events.add(fname)
        destination = random.choice(['the beach','the mountains','another country','a theme park','a cruise','a national park','a lake','a cabin','a resort','a city'])
        return messageFunction(fname,'You have gone on vacation to '+destination,player,check)


def newFood(player, type='message', message=False, response=False):
    fname = 'newFood'

    check = player.c.ageDays > 0 and fname not in player.askedQuestions and player.c.ageYears >= 2 and player.c.ageYears <= 6 and random.random() < .01
    if (check and type != 'answer'):
        food = random.choice(['Broccoli','Celery','Mushrooms','Brussels sprouts','Onions','Tomatoes'])
        message = "Today at dinner your parents have you try "+food+". Do you like it?"
        answerOptions = [answerOption("Yes, yum!",food),answerOption('No, gross!',food)]
        return questionFunction(fname,message,player,True,answerOptions)
    elif (type == 'answer'):
        player.askedQuestions.add(response['data'])
        if (response['option'] == 'Yes, yum!'):
            player.c.happiness += 5
            player.c.likes.append(response['data'])
        if (response['option'] == 'No, gross!'):
            player.c.happiness -= 5
            player.c.dislikes.append(response['data'])


def halloween(player, type='message', message=False, response=False):
    """Halloween costume and trick-or-treating event"""
    fname = f'halloween_{player.c.ageYears}'

    # Check conditions: age 3-16, date 10-31, not already answered
    check = (fname not in player.askedQuestions and
             player.date == '10-31' and
             player.c.ageYears >= 3 and
             player.c.ageYears <= 16)

    if check and type != 'answer':
        message = "It's Halloween! What costume do you wear?"

        # Age-dependent costume options
        if player.c.ageYears <= 10:
            answerOptions = [
                "Princess/Superhero",
                "Scary Monster",
                "Funny Character",
                "No costume"
            ]
        else:  # Ages 11-16
            answerOptions = [
                "Group costume with friends",
                "Ironically cute",
                "Too cool for costumes",
                "Hand out candy instead"
            ]

        return questionFunction(fname, message, player, True, answerOptions)

    elif type == 'answer':
        player.askedQuestions.add(fname)

        # Handle responses
        if response['option'] in ['Princess/Superhero', 'Scary Monster', 'Funny Character']:
            player.c.happiness += 15
            player.messageQueue.append("You had a great time trick-or-treating!")
        elif response['option'] == 'Group costume with friends':
            player.c.happiness += 20
            player.c.social += 10
            player.messageQueue.append("Your group costume was a hit!")
        elif response['option'] == 'Ironically cute':
            player.c.happiness += 10
            player.c.social += 5
        elif response['option'] == 'Too cool for costumes':
            player.c.happiness -= 5
            player.c.social -= 5
        elif response['option'] == 'Hand out candy instead':
            player.c.happiness += 5
        elif response['option'] == 'No costume':
            player.c.happiness -= 10


def valentinesDay(player, type='message', message=False, response=False):
    """Valentine's Day celebration or anxiety"""
    fname = f'valentinesDay_{player.c.ageYears}'

    # Check conditions: age 10+, date 02-14, not already answered
    check = (fname not in player.askedQuestions and
             player.date == '02-14' and
             player.c.ageYears >= 10)

    if check and type != 'answer':
        message = "It's Valentine's Day! How do you spend it?"

        # Check if player has a partner
        from character.character_manager import get_partner
        partner = get_partner(player)

        if partner:
            answerOptions = [
                answerOption("Romantic dinner", moneyCost=100),
                "Stay in and cook",
                "Exchange small gifts"
            ]
        else:
            answerOptions = [
                "Galentine's/Palentine's with friends",
                answerOption("Treat yourself", moneyCost=50),
                "Ignore it completely"
            ]

        return questionFunction(fname, message, player, True, answerOptions)

    elif type == 'answer':
        player.askedQuestions.add(fname)

        # Handle responses
        if response['option'] == 'Romantic dinner':
            player.c.money -= 100
            player.c.happiness += 20
            from character.character_manager import get_partner
            partner = get_partner(player)
            if partner:
                partner.affinity += 15
            player.messageQueue.append("You had a wonderful romantic dinner!")
        elif response['option'] == 'Stay in and cook':
            player.c.happiness += 15
            from character.character_manager import get_partner
            partner = get_partner(player)
            if partner:
                partner.affinity += 10
        elif response['option'] == 'Exchange small gifts':
            player.c.happiness += 10
        elif response['option'] == "Galentine's/Palentine's with friends":
            player.c.happiness += 15
            player.c.social += 15
        elif response['option'] == 'Treat yourself':
            player.c.money -= 50
            player.c.happiness += 10
        elif response['option'] == 'Ignore it completely':
            player.c.happiness += 5


def easterEggHunt(player, type='message'):
    """Easter egg hunting as a child"""
    fname = f'easterEggHunt_{player.c.ageYears}'

    # Check conditions: age 2-10, early April (around 04-10)
    check = (fname not in player.events and
             player.date == '04-10' and
             player.c.ageYears >= 2 and
             player.c.ageYears <= 10)

    if check:
        player.dayEvent = 'easter'
        message = "You find a basket full of candy and colorful eggs! Easter is so fun!"
        player.c.happiness += 15
        return messageFunction(fname, message, player, check)


def backToSchoolShopping(player, type='message', message=False, response=False):
    """Shopping for school supplies"""
    fname = f'backToSchoolShopping_{player.c.ageYears}'

    # Check conditions: age 5-18, late August (08-20 to 08-31)
    check = (fname not in player.askedQuestions and
             player.date >= '08-20' and
             player.date <= '08-31' and
             player.c.ageYears >= 5 and
             player.c.ageYears <= 18)

    if check and type != 'answer':
        message = "It's time for back-to-school shopping! What's your style?"
        answerOptions = [
            answerOption("Cool new backpack", moneyCost=50),
            answerOption("Fancy notebooks", moneyCost=30),
            answerOption("Just the basics", moneyCost=20),
            "Use last year's stuff"
        ]

        return questionFunction(fname, message, player, True, answerOptions)

    elif type == 'answer':
        player.askedQuestions.add(fname)

        # Handle responses
        if response['option'] == 'Cool new backpack':
            player.c.money -= 50
            player.c.happiness += 10
            player.c.social += 5
            player.messageQueue.append("Your new backpack is awesome!")
        elif response['option'] == 'Fancy notebooks':
            player.c.money -= 30
            player.c.happiness += 5
        elif response['option'] == 'Just the basics':
            player.c.money -= 20
        elif response['option'] == "Use last year's stuff":
            player.c.happiness -= 5
            player.c.social -= 5


def springCleaning(player, type='message', message=False, response=False):
    """Annual spring cleaning task"""
    fname = f'springCleaning_{player.c.ageYears}'

    # Check conditions: age 18+, March-April (03-15 to 04-15)
    check = (fname not in player.askedQuestions and
             player.date >= '03-15' and
             player.date <= '04-15' and
             player.c.ageYears >= 18)

    if check and type != 'answer':
        message = "It's time for spring cleaning! How thorough are you?"
        answerOptions = [
            answerOption("Deep clean everything", energyCost=30),
            answerOption("Just the visible areas", energyCost=15),
            answerOption("Hire a cleaner", moneyCost=200),
            "Ignore it"
        ]

        return questionFunction(fname, message, player, True, answerOptions)

    elif type == 'answer':
        player.askedQuestions.add(fname)

        # Handle responses
        if response['option'] == 'Deep clean everything':
            player.c.energy -= 30
            player.c.happiness += 15
            player.messageQueue.append("Your home is spotless!")
        elif response['option'] == 'Just the visible areas':
            player.c.energy -= 15
            player.c.happiness += 5
        elif response['option'] == 'Hire a cleaner':
            player.c.money -= 200
            player.c.happiness += 10
        elif response['option'] == 'Ignore it':
            player.c.happiness -= 10


def mothersDayForgot(player, type='message'):
    """Forgetting Mother's Day"""
    fname = f'mothersDayForgot_{player.c.ageYears}'

    # Check conditions: age 12+, Mother's Day range (05-08 to 05-14)
    check = (fname not in player.events and
             player.date >= '05-08' and
             player.date <= '05-14' and
             player.c.ageYears >= 12 and
             random.random() < 0.3)  # 30% chance to trigger

    if check:
        message = "You forgot it was Mother's Day! You scramble to call your mom and feel guilty."

        # Find mother and reduce affinity
        from character.character_manager import get_relationship
        mother = get_relationship(player, "mother")
        if mother:
            mother.affinity -= 15

        player.c.happiness -= 10
        return messageFunction(fname, message, player, check)


def summerFirstDayPool(player, type='message'):
    """First day at the pool/beach"""
    fname = f'summerFirstDayPool_{player.c.ageYears}'

    # Check conditions: age 5-30, early June (06-01 to 06-07)
    check = (fname not in player.events and
             player.date >= '06-01' and
             player.date <= '06-07' and
             player.c.ageYears >= 5 and
             player.c.ageYears <= 30)

    if check:
        message = "It's finally warm enough to swim! You spend the whole day at the pool/beach and get totally sunburned."
        player.c.happiness += 15
        player.c.energy -= 10
        return messageFunction(fname, message, player, check)


def snowDay(player, type='message'):
    """School/work cancelled due to snow"""
    fname = f'snowDay_{player.c.ageYears}'

    # Check conditions: age 5-65, winter months (12-01 to 02-28), student or working
    current_month = int(player.date.split('-')[0])
    is_winter = (current_month == 12 or current_month == 1 or current_month == 2)
    is_student_or_work = player.c.occupation in ['student', 'work']

    check = (fname not in player.events and
             is_winter and
             player.c.ageYears >= 5 and
             player.c.ageYears <= 65 and
             is_student_or_work and
             random.random() < 0.05)  # 5% chance on winter days

    if check:
        if player.c.occupation == 'student':
            message = "Heavy snow overnight! School is cancelled and you get an unexpected day off!"
        else:
            message = "Heavy snow overnight! Work is cancelled and you get an unexpected day off!"

        player.c.happiness += 20
        player.c.energy += 10
        return messageFunction(fname, message, player, check)


def newYearsResolution(player, type='message', message=False, response=False):
    """Making New Year's resolutions"""
    fname = f'newYearsResolution_{player.c.ageYears}'

    # Check conditions: age 10+, date 01-01
    check = (fname not in player.askedQuestions and
             player.date == '01-01' and
             player.c.ageYears >= 10)

    if check and type != 'answer':
        message = "What's your New Year's resolution?"
        answerOptions = [
            "Exercise more",
            "Save money",
            "Make new friends",
            "No resolutions"
        ]

        return questionFunction(fname, message, player, True, answerOptions)

    elif type == 'answer':
        player.askedQuestions.add(fname)

        # Handle responses and create effects
        if response['option'] == 'Exercise more':
            # Could add a schedule here for regular exercise
            player.c.happiness += 10
            player.messageQueue.append("You feel motivated to exercise more!")
        elif response['option'] == 'Save money':
            # Add temporary money bonus for a few months
            player.c.happiness += 10
            player.messageQueue.append("You start being more careful with money!")
        elif response['option'] == 'Make new friends':
            player.c.happiness += 10
            player.c.social += 5
            player.messageQueue.append("You resolve to be more social this year!")
        elif response['option'] == 'No resolutions':
            player.c.happiness -= 5


def blackFridayChaos(player, type='message', message=False, response=False):
    """Black Friday shopping decision"""
    fname = f'blackFridayChaos_{player.c.ageYears}'

    # Check conditions: age 16+, date 11-24
    check = (fname not in player.askedQuestions and
             player.date == '11-24' and
             player.c.ageYears >= 16)

    if check and type != 'answer':
        message = "Black Friday is here! Brave the crowds for deals?"
        answerOptions = [
            answerOption("Yes, wake up early!", energyCost=20, moneyCost=200),
            answerOption("Online shopping only", moneyCost=150),
            "Skip it completely",
            answerOption("Just window shop", energyCost=10)
        ]

        return questionFunction(fname, message, player, True, answerOptions)

    elif type == 'answer':
        player.askedQuestions.add(fname)

        # Handle responses
        if response['option'] == 'Yes, wake up early!':
            player.c.energy -= 20
            player.c.money -= 200
            player.c.happiness += 15
            player.messageQueue.append("You got some great deals, but you're exhausted!")
        elif response['option'] == 'Online shopping only':
            player.c.money -= 150
            player.c.happiness += 10
        elif response['option'] == 'Skip it completely':
            player.c.happiness += 5
        elif response['option'] == 'Just window shop':
            player.c.energy -= 10
            player.c.social += 5


__all__ = [
    'christmas',
    'newYear',
    'thanksgiving',
    'blackfriday',
    'independenceday',
    'birthday',
    'immunizations',
    'vacation',
    'newFood',
    'halloween',
    'valentinesDay',
    'easterEggHunt',
    'backToSchoolShopping',
    'springCleaning',
    'mothersDayForgot',
    'summerFirstDayPool',
    'snowDay',
    'newYearsResolution',
    'blackFridayChaos',
]
