"""
Seasonal & Outdoor Activity Events
Seasonal and outdoor recreational activities (ages 5-100)

Events:
- campingTrip: Friends planning camping trip (ages 8-70)
- skiingVacation: Skiing/snowboarding vacation - Winter only (ages 10-60)
- beachDay: Perfect day for the beach - Summer only (ages 5-100)
- hikingAdventure: Weekend hiking adventure (ages 10-70)
- autumnActivities: Apple picking and pumpkin patch - Fall only (ages 5-100)
"""

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


def get_allFriends(player):
    """Get all friends from player relationships"""
    friends = []
    for person in player.r:
        if 'friend' in person.relationships:
            friends.append(person)
    return friends


def campingTrip(player, type='message', message=False, response=False):
    """Friends planning camping trip - weekend event"""
    fname = 'campingTrip'

    # Get friends to check if player has any
    friends = get_allFriends(player)

    # Check: weekend event, has friends, good energy, appropriate age
    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 8 and player.c.ageYears <= 70 and
             len(friends) > 0 and
             player.weekend and
             player.c.energy >= 30 and
             1 >= random.random()*2000)

    message = "Friends are planning a camping trip this weekend. Join them?"

    if type != 'answer':
        answerOptions = [
            answerOption('Yes, love camping!', 'camping', energyCost=20),
            answerOption('Go but stay in cabin', 'cabin', moneyCost=100),
            answerOption('Not outdoorsy', 'no')
        ]
        return questionFunction(fname, message, player, check, answerOptions)

    elif type == 'answer':
        from functions import oneTimeEvent, upcoming_saturday

        if response['data'] == 'camping':
            # Schedule the camping trip for next weekend
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Camping Trip",
                    message="You're heading out on your camping trip with friends!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=7 if not player.weekend else 14,
                    hour=10,
                    location="campground" + player.c.id
                )
            )
            player.c.energy -= 20
            player.c.happiness += 30
            player.c.social += 20

            # Increase affinity with all friends
            for friend in friends:
                friend.affinity = min(100, friend.affinity + 25)

            player.messageQueue.append("You're going camping! Sleeping under the stars, telling stories around the campfire, and hiking during the day. Your friends are excited!")

        elif response['data'] == 'cabin':
            # Schedule cabin trip for next weekend
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Cabin Camping Trip",
                    message="You're heading to the cabin with friends!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=7 if not player.weekend else 14,
                    hour=10,
                    location="campground" + player.c.id
                )
            )
            player.c.money -= 100
            player.c.happiness += 20
            player.c.social += 15

            # Increase affinity with all friends
            for friend in friends:
                friend.affinity = min(100, friend.affinity + 20)

            player.messageQueue.append("You're joining your friends but staying in a cozy cabin. The best of both worlds!")

        elif response['data'] == 'no':
            player.c.happiness -= 10

            # Decrease affinity with friends
            for friend in friends:
                friend.affinity = max(0, friend.affinity - 15)

            player.messageQueue.append("You decline the camping trip. Your friends are disappointed you won't be joining them.")


def skiingVacation(player, type='message', message=False, response=False):
    """Skiing/snowboarding vacation - Winter only, weekend trip"""
    fname = 'skiingVacation'

    # Check: winter season, has money for trip, appropriate age, weekend availability
    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 10 and player.c.ageYears <= 60 and
             player.season == "Winter" and
             player.c.money >= 300 and
             player.c.energy >= 30 and
             1 >= random.random()*3000)

    message = "There's a ski resort offering winter vacation packages. Interested?"

    if type != 'answer':
        answerOptions = [
            answerOption('Yes, hit the slopes!', 'expert', moneyCost=800, energyCost=30),
            answerOption('Learn to ski', 'beginner', moneyCost=500, energyCost=20),
            answerOption('Stay in lodge', 'lodge', moneyCost=300),
            answerOption('Too expensive', 'no')
        ]
        return questionFunction(fname, message, player, check, answerOptions)

    elif type == 'answer':
        from functions import oneTimeEvent

        if response['data'] == 'expert':
            # Schedule ski trip for next weekend (3-4 days from now)
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Ski Vacation",
                    message="You're at the ski resort! Time to hit the slopes!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=random.randint(5, 10),
                    hour=8,
                    location="ski_resort" + player.c.id
                )
            )
            player.c.money -= 800
            player.c.energy -= 30
            player.c.happiness += 35
            player.c.health += 15
            player.c.stress -= 20
            player.messageQueue.append("Ski vacation booked! You'll hit the slopes soon. The fresh mountain air and thrill of skiing await!")

        elif response['data'] == 'beginner':
            # Schedule ski lesson trip
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Ski Lessons Vacation",
                    message="Your ski lessons begin today! Time to learn a new skill!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=random.randint(5, 10),
                    hour=9,
                    location="ski_resort" + player.c.id
                )
            )
            player.c.money -= 500
            player.c.energy -= 20
            player.c.happiness += 25
            player.c.health += 10
            player.messageQueue.append("Ski lessons booked! You'll learn to ski and have a great time on the slopes!")

        elif response['data'] == 'lodge':
            # Schedule relaxing lodge stay
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Mountain Lodge Getaway",
                    message="You arrive at the cozy mountain lodge. Time to relax!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=random.randint(3, 7),
                    hour=14,
                    location="ski_resort" + player.c.id
                )
            )
            player.c.money -= 300
            player.c.happiness += 20
            player.c.stress -= 25
            player.messageQueue.append("Lodge getaway booked! Sipping hot cocoa by the fireplace with beautiful mountain views sounds perfect!")

        elif response['data'] == 'no':
            player.c.happiness -= 15
            player.messageQueue.append("You skip the ski vacation due to the cost. Maybe next year when you've saved up more.")


def beachDay(player, type='message', message=False, response=False):
    """Perfect day for the beach - Summer only, weekend/free day activity"""
    fname = 'beachDay'

    # Get friends and family
    friends = get_allFriends(player)
    from functions import get_allFamily
    family = get_allFamily(player)
    has_companions = len(friends) > 0 or len(family) > 0

    # Check: summer season, weekend or free time, good energy
    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 5 and
             player.season == "Summer" and
             player.weekend and
             player.c.energy >= 20 and
             1 >= random.random()*1500)

    message = "It's a perfect summer day! " + ("Friends and family want to go to the beach." if has_companions else "Go to the beach?")

    if type != 'answer':
        answerOptions = [
            answerOption('Yes, all day!', 'all_day', energyCost=15),
            answerOption('Quick visit', 'quick'),
            answerOption('Too hot, stay home', 'no')
        ]
        return questionFunction(fname, message, player, check, answerOptions)

    elif type == 'answer':
        from functions import oneTimeEvent

        if response['data'] == 'all_day':
            # Schedule beach day for today or tomorrow
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Beach Day",
                    message="You're at the beach! Time to enjoy the sun and surf!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=0 if player.hourOfDay < 14 else 1,
                    hour=11,
                    location="beach" + player.c.id
                )
            )
            player.c.energy -= 15
            player.c.happiness += 25
            player.c.stress -= 15
            player.c.health += 10

            # Increase affinity with companions
            if has_companions:
                companions = friends + family
                for person in companions:
                    person.affinity = min(100, person.affinity + 20)
                player.c.social += 20
                player.messageQueue.append("You're heading to the beach! Swimming, building sandcastles, and soaking up the sun with friends and family. A perfect summer day!")
            else:
                player.messageQueue.append("You're going to the beach! Swimming and soaking up the sun. A perfect day to relax!")

        elif response['data'] == 'quick':
            player.c.happiness += 15
            player.c.stress -= 10
            player.c.energy -= 5

            # Small affinity boost if with companions
            if has_companions and random.random() < 0.5:
                companion = random.choice(friends + family)
                companion.affinity = min(100, companion.affinity + 10)
                player.c.social += 10
                player.messageQueue.append(f"You make a quick trip to the beach with {companion.firstname}. A refreshing swim and some sun - just what you needed!")
            else:
                player.messageQueue.append("You make a quick trip to the beach for a refreshing swim and some sun. Just what you needed!")

        elif response['data'] == 'no':
            player.c.happiness -= 5
            # Small affinity decrease if declining companions
            if has_companions:
                player.c.social -= 5
                player.messageQueue.append("You stay home in the air conditioning instead. Your friends and family are disappointed but understand.")
            else:
                player.messageQueue.append("You stay home in the air conditioning instead. The beach can wait for a cooler day.")


def hikingAdventure(player, type='message', message=False, response=False):
    """Weekend hiking adventure - good for spring, summer, fall"""
    fname = 'hikingAdventure'

    # Get friends who might join
    friends = get_allFriends(player)
    has_hiking_buddy = len(friends) > 0 and random.random() < 0.4

    # Check: not winter (too cold), weekend, good energy, appropriate age
    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 10 and player.c.ageYears <= 70 and
             player.season != "Winter" and
             player.weekend and
             player.c.energy >= 40 and
             1 >= random.random()*2000)

    message = "Plan a hiking adventure this weekend?" + (f" {random.choice(friends).firstname} wants to join!" if has_hiking_buddy else "")

    if type != 'answer':
        answerOptions = [
            answerOption('Yes, challenging trail!', 'challenging', energyCost=30),
            answerOption('Easy nature walk', 'easy', energyCost=10),
            answerOption('Not interested', 'no')
        ]
        return questionFunction(fname, message, player, check, answerOptions)

    elif type == 'answer':
        from functions import oneTimeEvent

        if response['data'] == 'challenging':
            # Schedule challenging hike for weekend
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Mountain Hike",
                    message="Time for your challenging mountain hike!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=1 if player.weekend else random.randint(5, 7),
                    hour=7,
                    location="mountain_trail" + player.c.id
                )
            )
            player.c.energy -= 30
            player.c.happiness += 30
            player.c.health += 20
            player.c.stress -= 20

            # Affinity boost if hiking with friend
            if has_hiking_buddy:
                hiking_buddy = random.choice(friends)
                hiking_buddy.affinity = min(100, hiking_buddy.affinity + 25)
                player.c.social += 15
                player.messageQueue.append(f"You and {hiking_buddy.firstname} are tackling a challenging mountain trail! The steep climbs will test your endurance, but the summit view will be worth it!")
            else:
                player.messageQueue.append("You're tackling a challenging mountain trail! The steep climbs will test your endurance, but reaching the summit will be worth it!")

        elif response['data'] == 'easy':
            # Schedule easy nature walk
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Nature Walk",
                    message="Time for your peaceful nature walk!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=0 if player.hourOfDay < 16 else 1,
                    hour=9,
                    location="nature_trail" + player.c.id
                )
            )
            player.c.energy -= 10
            player.c.happiness += 20
            player.c.health += 10
            player.c.stress -= 15

            # Affinity boost if with friend
            if has_hiking_buddy:
                hiking_buddy = random.choice(friends)
                hiking_buddy.affinity = min(100, hiking_buddy.affinity + 15)
                player.c.social += 10
                player.messageQueue.append(f"You and {hiking_buddy.firstname} are going on a peaceful nature walk! Fresh air, beautiful scenery, and gentle exercise - perfect!")
            else:
                player.messageQueue.append("You're going on a peaceful nature walk! The fresh air and beautiful scenery will be refreshing!")

        elif response['data'] == 'no':
            player.c.happiness -= 5
            # Small affinity decrease if declining friend
            if has_hiking_buddy:
                hiking_buddy = random.choice(friends)
                hiking_buddy.affinity = max(0, hiking_buddy.affinity - 10)
                player.c.social -= 5
                player.messageQueue.append(f"You decline the hiking invitation. {hiking_buddy.firstname} is disappointed but understands.")
            else:
                player.messageQueue.append("You skip the hiking adventure and stay home instead. Maybe another time.")


def autumnActivities(player, type='message', message=False, response=False):
    """Apple picking and pumpkin patch - Fall only, family-friendly weekend activity"""
    fname = 'autumnActivities'

    # Get family and friends - this is especially good with family
    from functions import get_allFamily
    family = get_allFamily(player)
    friends = get_allFriends(player)
    has_family = len(family) > 0
    has_companions = has_family or len(friends) > 0

    # Check: autumn season, weekend, has money, appropriate age
    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 5 and
             player.season == "Autumn" and
             player.weekend and
             player.c.money >= 20 and
             player.c.energy >= 15 and
             1 >= random.random()*2000)

    if has_family:
        message = "The family wants to go apple picking and visit the pumpkin patch! Join them?"
    elif len(friends) > 0:
        message = "Friends are organizing an autumn outing to go apple picking and visit a pumpkin patch. Interested?"
    else:
        message = "There's an apple orchard and pumpkin patch nearby. Visit today?"

    if type != 'answer':
        answerOptions = [
            answerOption('Yes, full autumn day!', 'full_day', moneyCost=50, energyCost=15),
            answerOption('Just pumpkin patch', 'pumpkins', moneyCost=20),
            answerOption('Not interested', 'no')
        ]
        return questionFunction(fname, message, player, check, answerOptions)

    elif type == 'answer':
        from functions import oneTimeEvent

        if response['data'] == 'full_day':
            # Schedule full autumn day for this weekend
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Autumn Day Out",
                    message="Time for apple picking and pumpkin patch fun!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=0 if player.hourOfDay < 13 else 1,
                    hour=10,
                    location="apple_orchard" + player.c.id
                )
            )
            player.c.money -= 50
            player.c.energy -= 15
            player.c.happiness += 25
            player.c.stress -= 15

            # Increase affinity with family/friends
            if has_family:
                for member in family:
                    member.affinity = min(100, member.affinity + 25)
                player.c.social += 20
                player.messageQueue.append("Perfect autumn day planned! Apple picking, pumpkin patch, hay rides, and fresh cider with the family. Fall memories in the making!")
            elif len(friends) > 0:
                for friend in friends:
                    friend.affinity = min(100, friend.affinity + 20)
                player.c.social += 15
                player.messageQueue.append("Autumn outing planned! Apple picking and pumpkin patch with friends. You'll come home with fresh apples, perfect pumpkins, and great memories!")
            else:
                player.messageQueue.append("Autumn day planned! Apple picking and exploring the pumpkin patch. You'll enjoy the crisp fall air and seasonal fun!")

        elif response['data'] == 'pumpkins':
            # Quick pumpkin patch visit
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Pumpkin Patch Visit",
                    message="Time to pick out the perfect pumpkin!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=0,
                    hour=14,
                    location="pumpkin_patch" + player.c.id
                )
            )
            player.c.money -= 20
            player.c.happiness += 15
            player.c.stress -= 10

            # Small affinity boost if with companions
            if has_companions:
                companions = family + friends
                for person in companions[:2]:  # Just a couple companions for quick visit
                    person.affinity = min(100, person.affinity + 10)
                player.c.social += 10
                player.messageQueue.append("Quick pumpkin patch visit planned! You'll pick out perfect pumpkins and enjoy the autumn atmosphere!")
            else:
                player.messageQueue.append("Pumpkin patch visit planned! You'll pick out the perfect pumpkin for fall decorating!")

        elif response['data'] == 'no':
            player.c.happiness -= 5
            # Affinity impact if declining family/friends
            if has_family:
                for member in family[:2]:  # A couple family members affected
                    member.affinity = max(0, member.affinity - 10)
                player.c.social -= 10
                player.messageQueue.append("You skip the autumn activities. The family is disappointed but understands.")
            elif len(friends) > 0:
                friend = random.choice(friends)
                friend.affinity = max(0, friend.affinity - 5)
                player.c.social -= 5
                player.messageQueue.append("You skip the autumn outing. Your friends wish you'd join but understand.")
            else:
                player.messageQueue.append("You skip the autumn activities. Fall will come again next year.")


__all__ = [
    'campingTrip',
    'skiingVacation',
    'beachDay',
    'hikingAdventure',
    'autumnActivities',
]
