"""
Family Activity Events
Family bonding and interaction activities (ages 5-100)

These events focus on relationship building with family members rather than
tracked activities. They check for family member existence, modify affinity,
and create appropriate schedules or one-time events.

Integration Approach:
- All events check for family members (get_allFamily) before triggering
- Events modify family member affinity appropriately based on player choices
- Recurring activities (game night) create schedules via scheduler()
- Planned events (vacation, photos) create oneTimeEvents with future dates
- Events that reference specific family members store IDs between question/answer phases
- Probabilities adjusted for reasonable trigger rates (1/500 to 1/800)
- Energy costs and social stat changes reflect the nature of the interaction

Events:
- familyGameNight: Weekly/monthly family game night tradition (ages 8+)
- familyVacation: Planning a family vacation with oneTimeEvent (ages 8-65)
- teachSiblingSkill: Teaching a younger sibling (ages 10-30, requires younger siblings)
- helpParentProject: Helping parent with home projects (ages 10-45, requires parents)
- familyPhoto: Professional family photo session with oneTimeEvent (ages 5+)
"""

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


def familyGameNight(player, type='message', message=False, response=False):
    """Start a weekly family game night tradition"""
    fname = 'familyGameNight'

    # Check for family members first
    from functions import get_allFamily
    family = get_allFamily(player)

    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 8 and player.c.ageYears <= 100 and
             len(family) > 0 and
             1 >= random.random() * 500)

    message = "Your family suggests starting a regular game night tradition. How often?"

    if (type != 'answer'):
        answerOptions = [
            "Yes, every week!",
            "Once a month",
            "Too busy"
        ]
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        from functions import scheduler, oneTimeEvent

        if (response['option'] == "Yes, every week!"):
            # Create weekly schedule for game night (Friday evenings)
            player.c.schedules.append(scheduler(player.c, "Family Game Night", ["weekly", "evening", "weekend"], location="home"+player.c.id, duration=2))
            player.c.happiness += 25
            player.c.social += 10

            # Increase affinity with all family members
            for member in family:
                member.affinity += 20

            player.messageQueue.append("You've started a weekly family game night tradition! Every Friday evening, the family gathers for board games and fun.")
        elif (response['option'] == "Once a month"):
            # Create a one-time event for the first game night, which will recur monthly
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Family Game Night",
                    message="It's time for your monthly family game night! Everyone's excited to play together.",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=7,  # First one in a week
                    hour=19,
                    location="home"+player.c.id
                )
            )
            player.c.happiness += 15
            player.c.social += 5

            # Increase affinity with all family members
            for member in family:
                member.affinity += 10

            player.messageQueue.append("You've decided to have family game night once a month. It's a nice tradition!")
        else:
            player.c.happiness -= 10

            # Decrease affinity with all family members
            for member in family:
                member.affinity -= 5

            player.messageQueue.append("You're too busy for family game night. Your family seems disappointed.")


def familyVacation(player, type='message', message=False, response=False):
    """Plan a family vacation this year"""
    fname = 'familyVacation'

    # Check for family members first
    from functions import get_allFamily
    family = get_allFamily(player)

    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 8 and player.c.ageYears <= 65 and
             len(family) > 0 and
             player.c.money >= 500 and  # Must have at least enough for weekend getaway
             1 >= random.random() * 800)

    message = "Your family wants to plan a vacation together. What sounds good?"

    if (type != 'answer'):
        answerOptions = [
            answerOption("Yes, big trip!", moneyCost=2000),
            answerOption("Weekend getaway", moneyCost=500),
            "Staycation at home",
            "Can't afford it"
        ]
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        from functions import oneTimeEvent

        if (response['option'] == "Yes, big trip!"):
            # Create a one-time event for the vacation in the future
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Family Vacation",
                    message="Your big family vacation has arrived! Everyone's excited for this amazing trip together.",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=random.randint(30, 90),  # Vacation in 1-3 months
                    hour=8,
                    location="vacation"
                )
            )
            player.c.money -= 2000
            player.c.happiness += 30

            # Increase affinity with all family members (immediate excitement)
            for member in family:
                member.affinity += 20

            player.messageQueue.append("You've planned an amazing family vacation! Everyone is excited about the trip. You'll leave in a few months.")
        elif (response['option'] == "Weekend getaway"):
            # Create a one-time event for the getaway
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Family Weekend Getaway",
                    message="Time for your family weekend getaway! A nice break from the routine.",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=random.randint(7, 21),  # Getaway in 1-3 weeks
                    hour=8,
                    location="vacation"
                )
            )
            player.c.money -= 500
            player.c.happiness += 20

            # Increase affinity with all family members
            for member in family:
                member.affinity += 15

            player.messageQueue.append("A weekend getaway with the family sounds perfect! You've booked it for a few weeks from now.")
        elif (response['option'] == "Staycation at home"):
            # Create a one-time event for the staycation
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Family Staycation",
                    message="Your family staycation week begins! Time to relax at home and enjoy quality family time.",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=random.randint(7, 14),  # Staycation in 1-2 weeks
                    hour=8,
                    location="home"+player.c.id
                )
            )
            player.c.happiness += 15

            # Increase affinity with all family members
            for member in family:
                member.affinity += 10

            player.messageQueue.append("You've planned a staycation at home. It'll be relaxing and the family will enjoy quality time together.")
        else:
            player.c.happiness -= 15
            player.messageQueue.append("You can't afford a vacation right now. Maybe next year.")


def teachSiblingSkill(player, type='message', message=False, response=False):
    """Your younger sibling wants you to teach them something"""
    fname = 'teachSiblingSkill'

    # Find younger siblings
    younger_siblings = []
    for person in player.r:
        if 'sibling' in person.relationships and person.ageYears < player.c.ageYears:
            younger_siblings.append(person)

    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 10 and player.c.ageYears <= 30 and
             len(younger_siblings) > 0 and
             player.c.energy >= 10 and  # Must have enough energy to teach
             1 >= random.random() * 600)

    if not check:
        return None

    # Pick a random younger sibling and store their ID
    sibling = random.choice(younger_siblings)

    # Store sibling ID in player for retrieval in answer phase
    if type != 'answer':
        player._temp_sibling_id = sibling.id

    message = f"Your younger sibling {sibling.firstname} wants you to teach them something. Help?"

    if (type != 'answer'):
        answerOptions = [
            answerOption("Yes, spend time teaching!", energyCost=10),
            "Quick lesson only",
            "Too busy"
        ]
        return questionFunction(fname, message, player, check, answerOptions, characters=[sibling])
    elif (type == 'answer'):
        from functions import get_person

        # Get the specific sibling from the question phase
        sibling = get_person(player, getattr(player, '_temp_sibling_id', None))

        # Fallback to random sibling if ID not found
        if not sibling and younger_siblings:
            sibling = random.choice(younger_siblings)

        if sibling:
            if (response['option'] == "Yes, spend time teaching!"):
                player.c.energy -= 10
                player.c.happiness += 20
                player.c.social += 10
                sibling.affinity += 25
                player.messageQueue.append(f"You spent quality time teaching {sibling.firstname}. They really appreciated it and learned a lot!")
            elif (response['option'] == "Quick lesson only"):
                player.c.happiness += 10
                player.c.social += 5
                sibling.affinity += 10
                player.messageQueue.append(f"You gave {sibling.firstname} a quick lesson. They learned something new!")
            else:
                player.c.happiness -= 5
                sibling.affinity -= 15
                player.messageQueue.append(f"{sibling.firstname} seems disappointed that you're too busy to help them.")

        # Clean up temp variable
        if hasattr(player, '_temp_sibling_id'):
            delattr(player, '_temp_sibling_id')


def helpParentProject(player, type='message', message=False, response=False):
    """Your parent needs help with a home project"""
    fname = 'helpParentProject'

    # Find a parent
    from functions import get_relationship
    parent = get_relationship(player, 'mother') or get_relationship(player, 'father')

    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 10 and player.c.ageYears <= 45 and
             parent is not None and
             player.c.energy >= 10 and  # Must have enough energy to help
             1 >= random.random() * 600)

    if not check:
        return None

    # Store parent ID for retrieval in answer phase
    if type != 'answer':
        player._temp_parent_id = parent.id

    parent_title = "parent"
    if 'mother' in parent.relationships:
        parent_title = "mother"
    elif 'father' in parent.relationships:
        parent_title = "father"

    # Randomize project types for variety
    projects = ["gardening", "painting the house", "fixing the fence", "organizing the garage", "remodeling the kitchen"]
    project = random.choice(projects)

    message = f"Your {parent_title} needs help with {project}. Want to assist?"

    if (type != 'answer'):
        answerOptions = [
            answerOption("Yes, help all day!", energyCost=20),
            answerOption("Help for a bit", energyCost=10),
            "Too busy"
        ]
        return questionFunction(fname, message, player, check, answerOptions, characters=[parent])
    elif (type == 'answer'):
        from functions import get_person

        # Get the specific parent from the question phase
        parent = get_person(player, getattr(player, '_temp_parent_id', None))

        # Fallback to finding a parent if ID not found
        if not parent:
            parent = get_relationship(player, 'mother') or get_relationship(player, 'father')

        if parent:
            # Re-determine parent title
            parent_title = "parent"
            if 'mother' in parent.relationships:
                parent_title = "mother"
            elif 'father' in parent.relationships:
                parent_title = "father"

            if (response['option'] == "Yes, help all day!"):
                player.c.energy -= 20
                player.c.happiness += 15
                player.c.social += 10
                parent.affinity += 25
                player.messageQueue.append(f"You helped your {parent_title} all day with the project. They're grateful and you feel accomplished!")
            elif (response['option'] == "Help for a bit"):
                player.c.energy -= 10
                player.c.happiness += 10
                player.c.social += 5
                parent.affinity += 15
                player.messageQueue.append(f"You helped your {parent_title} for a while. They appreciate the assistance!")
            else:
                player.c.happiness -= 10
                parent.affinity -= 20
                player.messageQueue.append(f"Your {parent_title} is disappointed you're too busy to help.")

        # Clean up temp variable
        if hasattr(player, '_temp_parent_id'):
            delattr(player, '_temp_parent_id')


def familyPhoto(player, type='message', message=False, response=False):
    """Family wants to take professional photos"""
    fname = 'familyPhoto'

    # Check for family members first
    from functions import get_allFamily
    family = get_allFamily(player)

    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 5 and player.c.ageYears <= 100 and
             len(family) > 0 and
             player.c.money >= 50 and  # Must be able to afford photo session
             1 >= random.random() * 700)

    message = "Your family wants to schedule a professional photo session together. Are you in?"

    if (type != 'answer'):
        answerOptions = [
            answerOption("Yes, sounds fun!", moneyCost=50),
            answerOption("Okay, if I have to", moneyCost=50),
            "Refuse"
        ]
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        from functions import oneTimeEvent

        if (response['option'] == "Yes, sounds fun!"):
            # Create a one-time event for the photo session
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Family Photo Session",
                    message="Today is the family photo session! Time to smile for the camera and create lasting memories.",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=random.randint(7, 21),  # Photo session in 1-3 weeks
                    hour=14,
                    location="photography_studio"
                )
            )
            player.c.money -= 50
            player.c.happiness += 15
            player.c.social += 5

            # Increase affinity with all family members
            for member in family:
                member.affinity += 15

            player.messageQueue.append("You're excited for the family photo session! It's scheduled for a few weeks from now. Should be fun!")
        elif (response['option'] == "Okay, if I have to"):
            # Create a one-time event for the photo session
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Family Photo Session",
                    message="Today is the family photo session. Time to put on a smile for the camera.",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=random.randint(7, 21),  # Photo session in 1-3 weeks
                    hour=14,
                    location="photography_studio"
                )
            )
            player.c.money -= 50
            player.c.happiness += 5

            # Small increase in affinity with all family members
            for member in family:
                member.affinity += 5

            player.messageQueue.append("You agreed to participate in the family photos. It's scheduled for a few weeks from now.")
        else:
            player.c.happiness -= 10

            # Decrease affinity with all family members
            for member in family:
                member.affinity -= 20

            player.messageQueue.append("You refused to participate in family photos. Your family is really disappointed.")


__all__ = [
    'familyGameNight',
    'familyVacation',
    'teachSiblingSkill',
    'helpParentProject',
    'familyPhoto',
]
