"""
Health Events
Health-related events, injuries, illnesses, and conditions

Events:
- minorInjury: Minor scrapes and injuries
- minorSickness: Common colds and illnesses
- breakArm: Breaking an arm
- healthCondition: Developing a health condition
- lowEnergyEvent: Low energy consequences
- negativeHabitEvent: Negative habit manifestations
"""

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


def minorInjury(player, type='message', message=False, response=False):
    """Minor scrapes and injuries"""
    fname = 'minorInjury'
    check = fname not in player.askedQuestions and player.c.ageYears > 5 and player.c.ageYears < 15 and random.random() < 1/1000000
    message = "You are playing outside with your friends and you fall down. You scrape your knee and it is bleeding. What do you do?"
    if (type != 'answer'):
        answerOptions = ['Go home and tell your parents', 'Ignore it and keep playing']
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response ['option'] == 'Go home and tell your parents'):
            player.messageQueue.append('You walk home and show your parents your knee. They clean it up and put a bandaid on it. You are good to go!')
        else:
            player.messageQueue.append('You ignore the pain and keep playing')
            player.c.social += 5


def minorSickness(player, type='message', message=False, response=False):
    """Common colds and illnesses"""
    fname = 'sicnkess'
    check = fname not in player.askedQuestions and player.c.ageYears > 5 and player.c.ageYears < 15 and random.random() < 1/1000000
    message = "You have caught a pretty bad cold, you feel weak are coughing and sneezing."
    if (type != 'answer' and check):
        answerOptions = ['Stay home and rest', 'Go to school anyways']
        player.c.energy -= random.randint(1,10)
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response ['option'] == 'Stay home and rest'):
            player.messageQueue.append('You stay home and rest. You feel a bit better the next day.')
            player.c.energy += random.randint(1,3)
        else:
            player.messageQueue.append('You go to school anyways and spread your germs to everyone')
            player.c.social -= 5


def breakArm(player, type='message'):
    """Breaking an arm"""
    fname = 'breakArm'
    check = fname not in player.events and player.c.ageYears >= 6 and random.random() < 1/10000
    message = "You fell and broke your arm"
    return messageFunction(fname,message,player,check)


def healthCondition(player, type='message', message=False, response=False):
    """Developing a health condition"""
    # Set a base chance and increment it based on player's age
    base_chance = 0.0000001  # .001% base chance to trigger
    age_multiplier = 0.00000001  # increase chance by 0.0001% for each year of age
    trigger_chance = base_chance + (player.c.ageYears * age_multiplier)

    # Only trigger health check with the given chance
    if random.random() <= trigger_chance and len(player.c.healthConditions) == 0:
        conditions = getattr(player, 'healthConditions', None)
        if conditions and len(conditions) > 0:
            # Sort the conditions based on healthPenalty in descending order
            conditions.sort(key=lambda x: x.healthModifier, reverse=True)
            
            # Determine the max index for condition selection based on player's age
            ageIndex = min(player.c.ageYears, len(conditions) - 1)
            
            # Select the condition randomly from the available range
            condition = random.choice(conditions[:ageIndex + 1])
            condition.date = player.date
            player.c.healthConditions.append(condition)
            message = "You have been diagnosed with " + condition.title + "."
            return messageFunction(type, message, player, True)


def lowEnergyEvent(player, type='message', message=False, response=False):
    """Low energy consequences"""
    fname = 'lowEnergyEvent'
    if random.random() < 1/10 and player.c.energy < 10 and player.hourOfDay > 18 and player.hourOfDay < 23:
        message = "After a long day, you're feeling exhausted."
        appendOptions = [" To cope you end up scrolling through social media for hours.", " To cope you end up watching TV for hours.", " To cope you end up playing video games for hours.", " To cope you end up eating junk food for hours.", " To cope you end up drinking too much alcohol", " To cope you end up lighting a cigarette."]
        message += random.choice(appendOptions)
        return messageFunction(fname, message, player, True)


def negativeHabitEvent(player, type='message', message=False, response=False):
    """Negative habit manifestations"""
    fname = 'negativeHabitEvent'
    if random.random() < 1/1000:
        negative_habits = [habit for habit in player.c.habits if habit.habitType == 'negative']
        
        # Check for age and occupation constraints
        if player.c.ageYears < 18:
            negative_habits = [habit for habit in negative_habits if habit.name not in ["excessive_alcohol_consumption", "smoking"]]
        if player.c.occupation != "student":
            negative_habits = [habit for habit in negative_habits if habit.name != "tardiness"]
        
        if negative_habits:
            habit = random.choice(negative_habits)
            
            # Define multiple messages for each habit
            habit_messages = {
                "tardiness": [
                    "You are late for school again. Your teacher gives you a warning.",
                    "You missed the start of the movie due to your tardiness."
                ],
                "nail_biting": [
                    "You've been biting your nails again. Your fingers are sore.",
                    "Your friends notice your nail biting habit.",
                    "You've bitten your nails to the quick, causing discomfort."
                ],
                "overthinking": [
                    "You spend hours overthinking a decision and end up feeling exhausted.",
                    "Your overthinking is causing you sleepless nights.",
                    "You overthink a situation to the point where it paralyzes you from taking action."
                ],
                "procrastination": [
                    "You procrastinate on an important task and now have to rush to complete it.",
                    "Your procrastination has resulted in a late fee on a bill.",
                    "You procrastinated and now you're stuck with the least desirable options."
                ],
                "negative_thinking": [
                    "You find yourself dwelling on negative thoughts, affecting your mood.",
                    "Your negative thinking is affecting your relationships.",
                    "You're caught in a loop of negative thinking, making it hard to see the positive."
                ],
                "overeating": [
                    "You give in to emotional eating and feel guilty afterward.",
                    "You overeat at dinner and feel uncomfortably full.",
                    "You keep eating past the point of fullness out of boredom."
                ],
                "under_exercising": [
                    "You haven't been getting much exercise lately, and you're starting to feel the effects.",
                    "You've been missing your exercise routine, and your energy levels are suffering.",
                    "Your lack of exercise is affecting your mood and overall health."
                ],
                "excessive_screen_time": [
                    "Your eyes are tired from too much screen time.",
                    "You've been on screens all day, causing headaches.",
                    "Your excessive screen time is affecting your sleep pattern."
                ],
                "impulsiveness": [
                    "Your impulsive action had unintended consequences.",
                    "Your impulsiveness led to a poor purchase decision.",
                    "Your impulsive behavior led to a risky situation."
                ],
                "indecisiveness": [
                    "You've spent all day trying to make a decision, and it's causing stress.",
                    "Your indecisiveness is causing delays and missed opportunities.",
                    "Your indecisiveness made others make the decision for you."
                ],
                "neglecting_self_care": [
                    "You've been neglecting your self-care routine and it's starting to show.",
                    "Your lack of self-care is affecting your energy and mood.",
                    "You feel rundown from neglecting basic self-care."
                ],
                "poor_time_management": [
                    "You're scrambling to finish a project due to poor time management.",
                    "Your leisure time is cut short due to your poor time management."
                ],
                "overeating_when_stressed": [
                    "You've been stress eating, and it's making you feel uncomfortable.",
                    "You eat more than usual when you're stressed, and it's affecting your health.",
                    "Your stress eating is leading to discomfort and guilt."
                ],
                "excessive_caffeine_intake": [
                    "The excessive caffeine is making it hard for you to sleep at night.",
                    "You're feeling jittery from excessive caffeine intake.",
                    "You have a caffeine crash from consuming too much."
                ],
                "smoking": [
                    "You notice a smoker's cough developing. It's a reminder of your habit.",
                    "You're short of breath during physical activities, a result of your smoking habit.",
                    "Your sense of taste and smell are compromised due to smoking."
                ],
                "excessive_alcohol_consumption": [
                    "Your frequent alcohol consumption is leading to regular morning hangovers.",
                    "You're using alcohol as a crutch to deal with stress.",
                    "Your excessive drinking is leading to forgetfulness and regret."
                ]
            }
            
            if habit.name in habit_messages.keys():
                message = random.choice(habit_messages[habit.name])
            else:
                message = "Your habit is causing some issues."
            
            # Adjust player attributes depending on the habit
            if habit.name in ["nail_biting", "negative_thinking"]:
                player.c.happiness -= 5
            elif habit.name in ["overthinking", "procrastination","excessive_screen_time", "impulsiveness", "indecisiveness", "neglecting_self_care", "poor_time_management", "excessive_caffeine_intake"]:
                player.c.energy -= 5
                player.c.happiness -= 5
            elif habit.name in ["overeating", "overeating_when_stressed", "excessive_alcohol_consumption", "smoking"]:
                player.c.health -= 5
                player.c.happiness -= 5
            return messageFunction(fname, message, player, True)


def annualCheckup(player, type='message', message=False, response=False):
    """Routine annual doctor's appointment"""
    fname = 'annualCheckup'
    check = fname not in player.askedQuestions and player.c.ageYears >= 18 and random.random() < 1/50000
    message = "It's time for your annual checkup. Do you go?"
    if (type != 'answer'):
        answerOptions = [
            answerOption('Yes, schedule it', moneyCost=100),
            answerOption('No, skip it'),
            answerOption('Go only if sick')
        ]
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == 'Yes, schedule it'):
            player.messageQueue.append('You schedule your annual checkup. The doctor says everything looks good!')
            player.c.health += 5
            player.c.happiness += 5
        elif (response['option'] == 'No, skip it'):
            player.messageQueue.append('You decide to skip your checkup this year. You hope everything is fine.')
            player.c.health -= 10
            player.c.happiness -= 5
        else:  # Go only if sick
            player.messageQueue.append('You decide to only go to the doctor when you feel sick.')
            player.c.health -= 5


def allergySymptoms(player, type='message'):
    """Discovering seasonal allergies"""
    fname = 'allergySymptoms'
    # Check for spring months (March-May, months 3-5)
    current_month = int(player.date.split('-')[0])
    is_spring = current_month >= 3 and current_month <= 5
    check = fname not in player.events and player.c.ageYears >= 10 and is_spring and random.random() < 1/100000
    message = "Your eyes are itchy and you can't stop sneezing. Looks like you have seasonal allergies."
    if check:
        player.c.energy -= 5
    return messageFunction(fname, message, player, check)


def dentalCavity(player, type='message', message=False, response=False):
    """Dentist finds a cavity"""
    fname = 'dentalCavity'
    check = fname not in player.askedQuestions and player.c.ageYears >= 8 and random.random() < 1/100000
    message = "The dentist found a cavity. You need a filling."
    if (type != 'answer'):
        answerOptions = [
            answerOption('Get it filled now', moneyCost=200),
            answerOption('Schedule for later', moneyCost=200),
            answerOption('Ignore it')
        ]
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == 'Get it filled now'):
            player.c.money -= 200
            player.messageQueue.append('You get the cavity filled. It was uncomfortable but now your tooth is fixed.')
            player.c.happiness -= 10
        elif (response['option'] == 'Schedule for later'):
            player.c.money -= 200
            player.messageQueue.append('You schedule the filling for next week. At least you have some time to mentally prepare.')
            player.c.happiness -= 5
        else:  # Ignore it
            player.messageQueue.append('You decide to ignore the cavity. This might cause bigger problems later...')
            player.c.health -= 15
            player.c.happiness -= 10


def mentalHealthDay(player, type='message', message=False, response=False):
    """Recognizing need for mental health break"""
    fname = 'mentalHealthDay'
    check = fname not in player.askedQuestions and player.c.ageYears >= 16 and player.c.ageYears <= 65 and (player.c.happiness < 30 or player.c.energy < 20) and random.random() < 1/10000
    message = "You're feeling overwhelmed and anxious. Take a mental health day?"
    if (type != 'answer'):
        answerOptions = [
            answerOption('Yes, take the day off'),
            answerOption('No, push through'),
            answerOption('Talk to someone', diamondCost=5)
        ]
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == 'Yes, take the day off'):
            player.messageQueue.append('You take a mental health day. You sleep in, relax, and do things you enjoy. You feel so much better.')
            player.c.happiness += 20
            player.c.energy += 20
        elif (response['option'] == 'No, push through'):
            player.messageQueue.append('You force yourself to keep going despite feeling terrible. It makes the day even harder.')
            player.c.energy -= 20
            player.c.happiness -= 10
        else:  # Talk to someone
            player.messageQueue.append('You talk to someone about how you are feeling. They listen and help you feel supported. It really helps.')
            player.c.happiness += 15
            player.c.social += 10


def sprainedAnkle(player, type='message'):
    """Minor sports/activity injury"""
    fname = 'sprainedAnkle'
    check = fname not in player.events and player.c.ageYears >= 10 and player.c.ageYears <= 50 and random.random() < 1/100000
    message = "You rolled your ankle. It's not broken, but it hurts to walk for a few days."
    if check:
        player.c.energy -= 15
        player.c.happiness -= 10
    return messageFunction(fname, message, player, check)


def eyeStrain(player, type='message'):
    """Too much screen time effects"""
    fname = 'eyeStrain'
    # Check if player has excessive screen time habit
    has_screen_habit = any(habit.name == 'excessive_screen_time' for habit in player.c.habits)
    check = fname not in player.events and player.c.ageYears >= 10 and has_screen_habit and random.random() < 1/50000
    message = "Your eyes hurt from staring at screens all day. You should probably take more breaks."
    if check:
        player.c.energy -= 5
        player.c.health -= 5
    return messageFunction(fname, message, player, check)


def backPain(player, type='message'):
    """Developing back problems"""
    fname = 'backPain'
    check = fname not in player.events and player.c.ageYears >= 30 and random.random() < 1/100000
    message = "Your back has been hurting lately. Maybe you should exercise more... or sleep on a better mattress."
    if check:
        player.c.energy -= 5
        player.c.health -= 5
    return messageFunction(fname, message, player, check)


def firstGrayHair(player, type='message'):
    """Finding first gray hair"""
    fname = 'firstGrayHair'
    check = fname not in player.events and player.c.ageYears >= 28 and player.c.ageYears <= 45 and random.random() < 1/100000
    message = "You found your first gray hair. When did that happen?!"
    if check:
        player.c.happiness -= 5
    return messageFunction(fname, message, player, check)


def sleepDisorder(player, type='message', message=False, response=False):
    """Struggling with insomnia"""
    fname = 'sleepDisorder'
    check = fname not in player.askedQuestions and player.c.ageYears >= 18 and player.c.energy < 30 and random.random() < 1/50000
    message = "You've been having trouble sleeping. What do you try?"
    if (type != 'answer'):
        answerOptions = [
            answerOption('Melatonin/sleep aids', moneyCost=30),
            answerOption('Better sleep schedule'),
            answerOption('See a doctor', moneyCost=150, diamondCost=5),
            answerOption('Suffer through it')
        ]
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == 'Melatonin/sleep aids'):
            player.c.money -= 30
            player.messageQueue.append('You try melatonin and it helps you sleep better. You feel more rested.')
            player.c.energy += 10
            player.c.happiness += 5
        elif (response['option'] == 'Better sleep schedule'):
            player.messageQueue.append('You commit to a regular sleep schedule. It takes discipline but your sleep improves.')
            player.c.happiness += 5
            player.c.energy += 5
        elif (response['option'] == 'See a doctor'):
            player.c.money -= 150
            player.messageQueue.append('The doctor identifies the root cause and provides treatment. Your sleep quality improves significantly.')
            player.c.energy += 20
            player.c.health += 10
        else:  # Suffer through it
            player.messageQueue.append('You continue struggling with poor sleep. It affects everything in your life.')
            player.c.energy -= 10
            player.c.happiness -= 10


def foodPoisoning(player, type='message'):
    """Getting sick from bad food"""
    fname = 'foodPoisoning'
    check = fname not in player.events and player.c.ageYears >= 10 and random.random() < 1/100000
    message = "Something you ate didn't agree with you. You spend the next 24 hours very sick."
    if check:
        player.c.energy -= 30
        player.c.happiness -= 20
        player.c.health -= 10
    return messageFunction(fname, message, player, check)


__all__ = [
    'minorInjury',
    'minorSickness',
    'breakArm',
    'healthCondition',
    'lowEnergyEvent',
    'negativeHabitEvent',
    'annualCheckup',
    'allergySymptoms',
    'dentalCavity',
    'mentalHealthDay',
    'sprainedAnkle',
    'eyeStrain',
    'backPain',
    'firstGrayHair',
    'sleepDisorder',
    'foodPoisoning',
]
