"""
Adulthood Life Events
Everyday adult experiences, challenges, and milestones (ages 18+)

Events:
- firstApartment: Moving into first apartment alone (ages 18-25)
- workLifeBalance: Choosing between career and personal life (ages 25-50)
- forgotBirthdayCall: Forgot to call family on important day (ages 22-65)
- friendsDrifting: Realizing you've lost touch with friends (ages 25-40)
- unexpectedBill: Surprise expensive bill arrives (ages 20-65)
- promotionOpportunity: Job promotion offered with tradeoffs (ages 25-55)
- agingParent: Parent needs more help with daily tasks (ages 35-60)
- careerChangeDesire: Thinking about switching careers (ages 30-50)
- coworkerRivalry: Competitive relationship with colleague (ages 25-60)
- divorceConsideration: Serious relationship problems (ages 25-65)
"""

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


def firstApartment(player, type='message', message=False, response=False):
    """Moving into first apartment alone"""
    fname = 'firstApartment'
    check = fname not in player.askedQuestions and player.c.ageYears >= 18 and player.c.ageYears <= 25 and 1 >= random.random()*2000
    message = "You're looking at your first apartment. It's small and needs work, but it's yours. Do you take it?"
    answerOptions = [
        answerOption('Sign the lease!', moneyCost=500),
        answerOption('Keep looking'),
        answerOption('Find a roommate first', moneyCost=250),
        answerOption('Stay with parents longer')
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == answerOptions[0].option):
            player.messageQueue.append("You signed the lease! It's expensive, but you have your own place now. Welcome to independence!")
            player.c.happiness += 20
        elif (response['option'] == answerOptions[1].option):
            player.messageQueue.append("You decide to keep looking for something better. The search continues.")
            player.c.happiness -= 5
        elif (response['option'] == answerOptions[2].option):
            player.messageQueue.append("You find a roommate to split the costs. It's not quite living alone, but it's a good compromise!")
            player.c.happiness += 10
            # Could create a roommate NPC here in future
        elif (response['option'] == answerOptions[3].option):
            player.messageQueue.append("You decide to stay with your parents a bit longer and save more money. It's practical, even if it's not exciting.")
            player.c.happiness -= 10
            player.c.money += 100


def workLifeBalance(player, type='message', message=False, response=False):
    """Choosing between career and personal life"""
    fname = 'workLifeBalance'
    check = fname not in player.askedQuestions and player.c.ageYears >= 25 and player.c.ageYears <= 50 and player.c.occupation == 'work' and getattr(player.c, 'job', False) and 1 >= random.random()*3000
    message = "Your boss offers overtime pay, but you have plans with friends. What do you choose?"
    answerOptions = [
        answerOption('Take the overtime', energyCost=20),
        answerOption('Keep your plans'),
        answerOption('Split the difference', energyCost=10)
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == answerOptions[0].option):
            player.messageQueue.append("You take the overtime and cancel your plans. The extra money is nice, but your friends are disappointed.")
            player.c.money += 200
            player.c.happiness -= 10
            # Reduce affinity with friends
            for person in player.r:
                if hasattr(person, 'relationship') and person.relationship == 'friend':
                    person.affinity = max(0, person.affinity - 10)
                    break
        elif (response['option'] == answerOptions[1].option):
            player.messageQueue.append("You keep your plans with friends. Work can wait - memories are more important!")
            player.c.happiness += 10
            # Increase affinity with friends
            for person in player.r:
                if hasattr(person, 'relationship') and person.relationship == 'friend':
                    person.affinity = min(100, person.affinity + 10)
                    break
        elif (response['option'] == answerOptions[2].option):
            player.messageQueue.append("You work a few extra hours then meet your friends late. Not perfect, but you made it work!")
            player.c.money += 100
            player.c.happiness += 5


def forgotBirthdayCall(player, type='message'):
    """Forgot to call family on important day"""
    fname = 'forgotBirthdayCall'
    check = fname not in player.events and player.c.ageYears >= 22 and player.c.ageYears <= 65 and 1 >= random.random()*5000
    message = "You realize you forgot to call your mom on her birthday. You feel terrible and quickly send a late message."

    if check:
        # Reduce affinity with a random family member
        family_members = [p for p in player.r if hasattr(p, 'relationship') and p.relationship in ['parent', 'mother', 'father', 'sibling']]
        if family_members:
            family_member = random.choice(family_members)
            family_member.affinity = max(0, family_member.affinity - 10)

        return messageFunction(fname, message, player, check)


def friendsDrifting(player, type='message'):
    """Realizing you've lost touch with friends"""
    fname = 'friendsDrifting'
    check = fname not in player.events and player.c.ageYears >= 25 and player.c.ageYears <= 40 and 1 >= random.random()*4000
    message = "You scroll through your phone and realize you haven't talked to your best friend from college in over a year. When did you get so busy?"

    return messageFunction(fname, message, player, check)


def unexpectedBill(player, type='message'):
    """Surprise expensive bill arrives"""
    fname = 'unexpectedBill'
    check = fname not in player.events and player.c.ageYears >= 20 and player.c.ageYears <= 65 and 1 >= random.random()*3000

    if check:
        # Random bill messages
        messages = [
            "Your car needs $800 in repairs. Ouch.",
            "The medical bill is way higher than expected. There goes your savings.",
            "You forgot to pay insurance and now there's a late fee plus penalties.",
            "Your laptop died and needs replacing. Why does this always happen at the worst time?"
        ]
        message = random.choice(messages)

        # Random cost between 200 and 800
        cost = random.randint(200, 800)
        player.c.money = max(0, player.c.money - cost)
        player.c.happiness -= 15

        return messageFunction(fname, message, player, check)


def promotionOpportunity(player, type='message', message=False, response=False):
    """Job promotion offered with tradeoffs"""
    fname = 'promotionOpportunity'
    check = fname not in player.askedQuestions and player.c.ageYears >= 25 and player.c.ageYears <= 55 and player.c.occupation == 'work' and getattr(player.c, 'job', False) and 1 >= random.random()*4000
    message = "You're offered a promotion with more money but longer hours. Accept?"
    answerOptions = [
        answerOption('Yes, take promotion', energyCost=30),
        answerOption('No, stay where you are'),
        answerOption('Negotiate better terms', diamondCost=10, energyCost=20)
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == answerOptions[0].option):
            player.messageQueue.append("You accept the promotion! More money, more responsibility, more hours. Your work-life balance suffers.")
            player.c.money += 500
            player.c.happiness -= 10
            # Could increase job performance/title here in future
        elif (response['option'] == answerOptions[1].option):
            player.messageQueue.append("You decline the promotion. Your boss is surprised, but you value your free time more than money.")
            player.c.happiness += 10
        elif (response['option'] == answerOptions[2].option):
            player.messageQueue.append("You successfully negotiate better terms! More money with reasonable hours. Best of both worlds!")
            player.c.money += 400
            player.c.happiness += 5


def agingParent(player, type='message', message=False, response=False):
    """Parent needs more help with daily tasks"""
    fname = 'agingParent'
    # Check if player has living parents
    has_parent = False
    for person in player.r:
        if hasattr(person, 'relationship') and person.relationship in ['parent', 'mother', 'father'] and getattr(person, 'alive', True):
            has_parent = True
            break

    check = fname not in player.askedQuestions and player.c.ageYears >= 35 and player.c.ageYears <= 60 and has_parent and 1 >= random.random()*5000
    message = "Your parent is getting older and needs help. How do you support them?"
    answerOptions = [
        answerOption('Visit more often', energyCost=10),
        answerOption('Hire outside help', moneyCost=500),
        answerOption('Move them in with you', energyCost=20, moneyCost=200),
        answerOption('Encourage siblings to help', diamondCost=5)
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == answerOptions[0].option):
            player.messageQueue.append("You start visiting your parent more often. It's tiring but you're glad to spend time together.")
            player.c.happiness += 5
            # Increase parent affinity
            for person in player.r:
                if hasattr(person, 'relationship') and person.relationship in ['parent', 'mother', 'father']:
                    person.affinity = min(100, person.affinity + 10)
                    break
        elif (response['option'] == answerOptions[1].option):
            player.messageQueue.append("You hire a home care aide for your parent. It's expensive but gives everyone peace of mind.")
            player.c.happiness += 10
        elif (response['option'] == answerOptions[2].option):
            player.messageQueue.append("Your parent moves in with you. It's a big adjustment for everyone, but you're there for each other.")
            player.c.happiness -= 10
            # Increase parent affinity significantly
            for person in player.r:
                if hasattr(person, 'relationship') and person.relationship in ['parent', 'mother', 'father']:
                    person.affinity = min(100, person.affinity + 20)
                    break
        elif (response['option'] == answerOptions[3].option):
            player.messageQueue.append("You coordinate with your siblings to share the caregiving. Teamwork makes it easier for everyone.")
            player.c.happiness += 15


def careerChangeDesire(player, type='message', message=False, response=False):
    """Thinking about switching careers"""
    fname = 'careerChangeDesire'
    check = fname not in player.askedQuestions and player.c.ageYears >= 30 and player.c.ageYears <= 50 and player.c.occupation == 'work' and getattr(player.c, 'job', False) and 1 >= random.random()*5000
    message = "You're tired of your job and dream of doing something different. Do you make a change?"
    answerOptions = [
        answerOption('Quit and pursue passion', energyCost=50, moneyCost=1000),
        answerOption('Stay in current job'),
        answerOption('Side hustle first', energyCost=20),
        answerOption('Go back to school', moneyCost=5000)
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == answerOptions[0].option):
            player.messageQueue.append("You quit your job to pursue your passion! It's scary and expensive, but you feel alive again!")
            player.c.happiness += 30
            # Could remove current job here in future
        elif (response['option'] == answerOptions[1].option):
            player.messageQueue.append("You decide to stay in your current job. It's safe, but you can't shake the feeling of 'what if?'")
            player.c.happiness -= 10
            player.c.money += 500
        elif (response['option'] == answerOptions[2].option):
            player.messageQueue.append("You start a side hustle while keeping your day job. It's exhausting but exciting!")
            player.c.happiness += 10
        elif (response['option'] == answerOptions[3].option):
            player.messageQueue.append("You enroll in courses to change careers. It's a big investment, but you're hopeful about the future!")
            player.c.happiness += 20


def coworkerRivalry(player, type='message'):
    """Competitive relationship with colleague"""
    fname = 'coworkerRivalry'
    check = fname not in player.events and player.c.ageYears >= 25 and player.c.ageYears <= 60 and player.c.occupation == 'work' and getattr(player.c, 'job', False) and 1 >= random.random()*4000
    message = "A new coworker is getting all the attention. You feel competitive and a little jealous."

    return messageFunction(fname, message, player, check)


def divorceConsideration(player, type='message', message=False, response=False):
    """Serious relationship problems"""
    fname = 'divorceConsideration'
    # Check if player has partner with low affinity
    has_troubled_relationship = False
    partner = None
    if getattr(player.c, 'partner', False):
        from functions import get_person
        partner = get_person(player, player.c.partner)
        if partner and hasattr(partner, 'affinity') and partner.affinity < 20:
            has_troubled_relationship = True

    check = fname not in player.askedQuestions and player.c.ageYears >= 25 and player.c.ageYears <= 65 and has_troubled_relationship and 1 >= random.random()*6000
    message = "Your marriage isn't what it used to be. Do you try to fix it or let go?"
    answerOptions = [
        answerOption('Couples therapy', moneyCost=500, diamondCost=10, energyCost=30),
        answerOption('Separate for now', energyCost=40),
        answerOption('Divorce', moneyCost=2000, energyCost=50),
        answerOption('Keep trying alone', energyCost=20)
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == answerOptions[0].option):
            player.messageQueue.append("You both commit to couples therapy. It's hard work, but you're fighting for your relationship.")
            player.c.happiness -= 5
            # Increase partner affinity somewhat
            if partner:
                partner.affinity = min(100, partner.affinity + 15)
        elif (response['option'] == answerOptions[1].option):
            player.messageQueue.append("You decide to separate temporarily. Maybe some space will help you figure things out.")
            player.c.happiness -= 20
        elif (response['option'] == answerOptions[2].option):
            player.messageQueue.append("You file for divorce. It's painful and expensive, but sometimes relationships can't be saved.")
            player.c.happiness -= 30
            # Could remove partner here in future
            if partner:
                partner.affinity = 0
        elif (response['option'] == answerOptions[3].option):
            player.messageQueue.append("You keep trying to make it work on your own, but it's exhausting when it feels one-sided.")
            player.c.happiness -= 10


__all__ = [
    'firstApartment',
    'workLifeBalance',
    'forgotBirthdayCall',
    'friendsDrifting',
    'unexpectedBill',
    'promotionOpportunity',
    'agingParent',
    'careerChangeDesire',
    'coworkerRivalry',
    'divorceConsideration',
]
