"""
Social Activity Events
Activity events focused on social engagement and community (ages 8-100)

Events:
- joinClub: Join a club for one of your interests (ages 12-100)
- volunteerWork: Volunteer for a local organization (ages 14-100)
- bookClub: Join a book club with friends (ages 16-100)
- gamingGroup: Join regular gaming nights (ages 10-100)
- communityEvent: Attend or help organize community events (ages 8-100)
"""

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


# ============================================================
# Social Activity Class Definition
# ============================================================

class SocialActivity:
    """
    Social activity definition (clubs, volunteer work, etc.)

    Attributes:
        id: Unique identifier
        title: Activity name
        type: Activity type ('social')
        focus: Default focus type for this activity
        description: Description of the activity
        energyModifier: Energy cost
        performanceTracking: Whether to track performance/hours
    """
    def __init__(self, title, focus, description, energyModifier, performanceTracking=False):
        self.id = uuid.uuid4().hex
        self.title = title
        self.type = 'social'
        self.focus = focus
        self.description = description
        self.energyModifier = energyModifier
        self.performanceTracking = performanceTracking


# ============================================================
# Helper Functions
# ============================================================

def hasActivity(person, activityTitle):
    """Check if person already has an activity with given title"""
    return any(activity.title == activityTitle for activity in person.activities)


def addSocialActivity(person, activityTitle, focus, description, date, performanceTracking=False):
    """
    Add a social activity to a person

    Args:
        person: Person object to assign activity to
        activityTitle: Name of the activity
        focus: Focus type ('Socialize', 'Balanced', etc.)
        description: Activity description
        date: Date the activity was started
        performanceTracking: Whether to track performance

    Returns:
        SocialActivity: The created activity object
    """
    from core.models import ActivityRecord

    activity = SocialActivity(activityTitle, focus, description, 15, performanceTracking)
    person.activities.append(activity)

    # Create activity record for tracking
    record = ActivityRecord(activity.id, activity.type, date)
    record.focus = focus
    if performanceTracking:
        record.performance = 0  # Start at 0 for volunteer hours, club participation, etc.
    person.activityRecords.append(record)

    return activity


def getActivityRecord(person, activityId):
    """Get activity record for a given activity ID"""
    for record in person.activityRecords:
        if record.id == activityId:
            return record
    return None


def incrementActivityPerformance(person, activityId, amount=1):
    """Increment performance tracking for an activity (e.g., volunteer hours)"""
    record = getActivityRecord(person, activityId)
    if record:
        record.performance += amount


def buildRelationshipsAtActivity(player, activity_name, affinity_boost=5):
    """
    Build relationships with people who share this social activity
    Boosts affinity with relationship characters who have the same activity
    """
    relationships_built = 0
    for rel_person in player.r:
        if hasActivity(rel_person, activity_name):
            rel_person.affinity += affinity_boost
            relationships_built += 1
    return relationships_built


def joinClub(player, type='message', message=False, response=False):
    """Join a club for one of your interests (ages 12-100)"""
    from functions import scheduler, locationClass, find_by_id

    fname = 'joinClub'

    # Generate random club type
    club_types = [
        ("Photography Club", "Share your passion for photography"),
        ("Hiking Club", "Explore nature trails with others"),
        ("Cooking Club", "Learn new recipes together"),
        ("Art Club", "Express creativity through art"),
        ("Music Club", "Share your love of music"),
        ("Film Club", "Watch and discuss movies"),
        ("Tech Club", "Learn about technology together"),
        ("Gardening Club", "Grow plants and share gardening tips")
    ]
    club_name, club_desc = random.choice(club_types)

    # Check if already in this club
    already_member = hasActivity(player.c, club_name)

    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 12 and
             player.c.ageYears <= 100 and
             not already_member and
             1 >= random.random() * 1000)

    message = f"There's a {club_name} in your area. Join?"

    if type != 'answer':
        answerOptions = [
            answerOption("Yes, become a member!", data="join"),
            answerOption("Attend as guest first", data="guest"),
            answerOption("Not interested", data="no")
        ]
        return questionFunction(fname, message, player, check, answerOptions)

    elif type == 'answer':
        if response['data'] == 'join':
            # Add activity with performance tracking
            activity = addSocialActivity(
                player.c,
                club_name,
                "Socialize",
                club_desc,
                player.date,
                performanceTracking=True
            )

            # Create community location if it doesn't exist
            community_id = "community-" + player.c.id
            if not find_by_id(player.l, community_id):
                player.l.append(locationClass(community_id, 'community'))

            # Create recurring club meeting schedule (8-12 weeks)
            duration_weeks = random.randint(8, 12)
            player.c.schedules.append(
                scheduler(
                    player.c,
                    club_name,
                    ["weekly", "evening"],
                    location=community_id,
                    duration=duration_weeks
                )
            )

            # Stat bonuses
            player.c.social += 25
            player.c.happiness += 15

            # Build relationships with others in similar activities
            relationships_count = buildRelationshipsAtActivity(player, club_name, 3)

            player.messageQueue.append(f"You joined {club_name}! Meetings are weekly for {duration_weeks} weeks.")
            if relationships_count > 0:
                player.messageQueue.append(f"You're getting closer to {relationships_count} club member(s)!")

        elif response['data'] == 'guest':
            player.c.social += 10
            player.c.happiness += 10
            player.messageQueue.append(f"You attended {club_name} as a guest and enjoyed it!")

        else:  # no
            player.c.happiness -= 5
            player.messageQueue.append("You decided not to join the club.")


def volunteerWork(player, type='message', message=False, response=False):
    """Volunteer for a local organization (ages 14-100)"""
    from functions import scheduler, locationClass, find_by_id

    fname = 'volunteerWork'

    # Generate random volunteer opportunity
    volunteer_types = [
        ("Animal Shelter", "Help care for animals in need"),
        ("Food Bank", "Sort and distribute food to those in need"),
        ("Elderly Care", "Visit and assist elderly community members"),
        ("Environmental Cleanup", "Help clean parks and public spaces"),
        ("Youth Mentoring", "Guide and inspire young people"),
        ("Homeless Outreach", "Provide support to homeless individuals"),
        ("Library Assistance", "Help organize and run library programs")
    ]
    volunteer_name, volunteer_desc = random.choice(volunteer_types)

    # Check if already volunteering
    already_volunteering = hasActivity(player.c, f"{volunteer_name} Volunteer")

    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 14 and
             player.c.ageYears <= 100 and
             not already_volunteering and
             1 >= random.random() * 1000)

    message = f"A local {volunteer_name} needs volunteers. Help out?"

    if type != 'answer':
        answerOptions = [
            answerOption("Yes, volunteer regularly!", data="regular"),
            answerOption("Volunteer occasionally", data="occasional"),
            answerOption("Donate money instead", data="donate", moneyCost=50),
            answerOption("Not right now", data="no")
        ]
        return questionFunction(fname, message, player, check, answerOptions)

    elif type == 'answer':
        if response['data'] == 'regular':
            # Add activity with performance tracking (tracks volunteer hours)
            activity_title = f"{volunteer_name} Volunteer"
            activity = addSocialActivity(
                player.c,
                activity_title,
                "Balanced",
                volunteer_desc,
                player.date,
                performanceTracking=True  # Track volunteer hours
            )

            # Create community location if it doesn't exist
            community_id = "community-" + player.c.id
            if not find_by_id(player.l, community_id):
                player.l.append(locationClass(community_id, 'community'))

            # Create volunteer schedule (12-24 weeks, weekend mornings)
            duration_weeks = random.randint(12, 24)
            player.c.schedules.append(
                scheduler(
                    player.c,
                    activity_title,
                    ["weekly", "weekend", "morning"],
                    location=community_id,
                    duration=duration_weeks
                )
            )

            # Stat bonuses
            player.c.social += 20
            player.c.happiness += 25
            player.c.prestige += 5  # Volunteering builds prestige

            # Build relationships with other volunteers
            relationships_count = buildRelationshipsAtActivity(player, activity_title, 4)

            player.messageQueue.append(f"You signed up to volunteer at {volunteer_name} regularly!")
            player.messageQueue.append(f"You'll volunteer for {duration_weeks} weeks. Your work helps the community.")
            if relationships_count > 0:
                player.messageQueue.append(f"You bonded with {relationships_count} fellow volunteer(s)!")

        elif response['data'] == 'occasional':
            player.c.social += 15
            player.c.happiness += 20
            player.c.prestige += 2
            player.messageQueue.append(f"You'll volunteer at {volunteer_name} when you have time. Every bit helps!")

        elif response['data'] == 'donate':
            player.c.money -= 50
            player.c.happiness += 15
            player.c.prestige += 3
            player.messageQueue.append(f"You made a $50 donation to {volunteer_name} to support the cause!")

        else:  # no
            player.c.happiness -= 10
            player.messageQueue.append("You decided not to volunteer right now.")


def bookClub(player, type='message', message=False, response=False):
    """Join a book club with friends (ages 16-100)"""
    from functions import scheduler, locationClass, find_by_id

    fname = 'bookClub'

    # Generate random book club type
    book_genres = [
        ("Mystery Book Club", "Solve mysteries together through reading"),
        ("Sci-Fi Book Club", "Explore futuristic worlds and ideas"),
        ("Romance Book Club", "Discuss love stories and relationships"),
        ("Classic Literature Club", "Dive into timeless literary works"),
        ("Biography Book Club", "Learn from real people's lives"),
        ("Fantasy Book Club", "Escape to magical worlds together")
    ]
    club_name, club_desc = random.choice(book_genres)

    # Check if already in a book club
    already_member = hasActivity(player.c, club_name)

    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 16 and
             player.c.ageYears <= 100 and
             not already_member and
             1 >= random.random() * 1000)

    message = f"Friends are starting a {club_name}. Join them?"

    if type != 'answer':
        answerOptions = [
            answerOption("Yes, sounds fun!", data="join"),
            answerOption("Read books but skip meetings", data="read"),
            answerOption("Not interested", data="no")
        ]
        return questionFunction(fname, message, player, check, answerOptions)

    elif type == 'answer':
        if response['data'] == 'join':
            # Add activity with performance tracking (books read)
            activity = addSocialActivity(
                player.c,
                club_name,
                "Socialize",
                club_desc,
                player.date,
                performanceTracking=True  # Track books read
            )

            # Create friend location or community location
            friend_id = "friend-" + player.c.id
            if not find_by_id(player.l, friend_id):
                player.l.append(locationClass(friend_id, 'friend'))

            # Create book club schedule (monthly meetings for 6-10 months)
            duration_months = random.randint(6, 10)
            # Monthly = every 4 weeks, so duration in weeks
            player.c.schedules.append(
                scheduler(
                    player.c,
                    club_name,
                    ["weekly", "evening"],  # Meet once a week
                    location=friend_id,
                    duration=duration_months * 4  # Convert months to weeks
                )
            )

            # Stat bonuses - both social and intelligence!
            player.c.social += 20
            player.c.intelligence += 15
            player.c.happiness += 15

            # Build relationships with book club members
            relationships_count = buildRelationshipsAtActivity(player, club_name, 5)

            player.messageQueue.append(f"You joined {club_name}! Time to start reading.")
            player.messageQueue.append(f"The club will meet for {duration_months} months. Enjoy the discussions!")
            if relationships_count > 0:
                player.messageQueue.append(f"You're getting closer to {relationships_count} fellow reader(s)!")

        elif response['data'] == 'read':
            player.c.intelligence += 10
            player.c.happiness += 5
            player.messageQueue.append("You'll read the books but skip the social meetings.")

        else:  # no
            player.c.social -= 10
            player.messageQueue.append("You decided not to join the book club.")


def gamingGroup(player, type='message', message=False, response=False):
    """Join regular gaming nights (ages 10-100)"""
    from functions import scheduler, locationClass, find_by_id

    fname = 'gamingGroup'

    # Generate random gaming type
    gaming_types = [
        ("Board Game Night", "Play board games with friends"),
        ("Video Game Night", "Team up for multiplayer gaming"),
        ("Tabletop RPG Group", "Create epic adventures together"),
        ("Card Game Night", "Master strategy card games"),
        ("Retro Gaming Club", "Relive classic video games"),
        ("Party Game Night", "Fun social party games")
    ]
    group_name, group_desc = random.choice(gaming_types)

    # Check if already in this gaming group
    already_member = hasActivity(player.c, group_name)

    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 10 and
             player.c.ageYears <= 100 and
             not already_member and
             1 >= random.random() * 1000)

    message = f"Friends invite you to a regular {group_name}. Join?"

    if type != 'answer':
        answerOptions = [
            answerOption("Yes, weekly gaming!", data="weekly"),
            answerOption("Join occasionally", data="occasional"),
            answerOption("Not my thing", data="no")
        ]
        return questionFunction(fname, message, player, check, answerOptions)

    elif type == 'answer':
        if response['data'] == 'weekly':
            # Add activity with performance tracking (games played, sessions attended)
            activity = addSocialActivity(
                player.c,
                group_name,
                "Socialize",
                group_desc,
                player.date,
                performanceTracking=True
            )

            # Create friend location if it doesn't exist
            friend_id = "friend-" + player.c.id
            if not find_by_id(player.l, friend_id):
                player.l.append(locationClass(friend_id, 'friend'))

            # Create gaming night schedule (weekly for 16-24 weeks)
            duration_weeks = random.randint(16, 24)
            player.c.schedules.append(
                scheduler(
                    player.c,
                    group_name,
                    ["weekly", "evening", "weekend"],
                    location=friend_id,
                    duration=duration_weeks
                )
            )

            # Stat bonuses
            player.c.social += 25
            player.c.happiness += 20
            player.c.stress -= 10  # Gaming is stress relief!

            # Build relationships with gaming buddies
            relationships_count = buildRelationshipsAtActivity(player, group_name, 6)

            player.messageQueue.append(f"You joined {group_name}! See you at the next session.")
            player.messageQueue.append(f"The group will meet weekly for {duration_weeks} weeks. Have fun!")
            if relationships_count > 0:
                player.messageQueue.append(f"You're bonding with {relationships_count} gaming friend(s)!")

        elif response['data'] == 'occasional':
            player.c.social += 15
            player.c.happiness += 15
            player.c.stress -= 5
            player.messageQueue.append(f"You'll join {group_name} when you can make it!")

        else:  # no
            player.c.social -= 10
            player.messageQueue.append("You decided gaming nights aren't for you.")


def communityEvent(player, type='message', message=False, response=False):
    """Attend or help organize community events (ages 8-100)"""
    fname = 'communityEvent'

    # Generate random community event type
    event_types = [
        "Neighborhood Block Party",
        "Community Festival",
        "Farmers Market",
        "Charity Fundraiser",
        "Local Art Fair",
        "Music in the Park",
        "Community Cleanup Day",
        "Holiday Celebration",
        "Sports Tournament",
        "Cultural Festival"
    ]
    event_name = random.choice(event_types)

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

    message = f"There's a {event_name} this weekend. Attend?"

    if type != 'answer':
        answerOptions = [
            answerOption("Yes, participate actively!", data="participate", energyCost=15),
            answerOption("Just attend casually", data="attend"),
            answerOption("Help organize it!", data="organize", energyCost=30, diamondCost=10),
            answerOption("Skip it", data="no")
        ]
        return questionFunction(fname, message, player, check, answerOptions)

    elif type == 'answer':
        if response['data'] == 'participate':
            player.c.social += 20
            player.c.happiness += 15
            player.c.energy -= 15

            # Build relationships with community members
            # Random chance to boost affinity with 1-3 relationship characters
            num_people_met = random.randint(1, min(3, len(player.r))) if player.r else 0
            if num_people_met > 0:
                met_people = random.sample(player.r, num_people_met)
                for person in met_people:
                    person.affinity += random.randint(3, 8)
                    person.familiarity += random.randint(5, 10)

            player.messageQueue.append(f"You actively participated in the {event_name} and had a great time!")
            if num_people_met > 0:
                player.messageQueue.append(f"You met and bonded with {num_people_met} people at the event!")

        elif response['data'] == 'attend':
            player.c.social += 10
            player.c.happiness += 10

            # Lower chance of meeting people
            num_people_met = random.randint(0, min(2, len(player.r))) if player.r else 0
            if num_people_met > 0:
                met_people = random.sample(player.r, num_people_met)
                for person in met_people:
                    person.affinity += random.randint(1, 5)
                    person.familiarity += random.randint(3, 7)

            player.messageQueue.append(f"You casually attended the {event_name}.")
            if num_people_met > 0:
                player.messageQueue.append(f"You ran into {num_people_met} familiar face(s) at the event!")

        elif response['data'] == 'organize':
            player.c.social += 30
            player.c.happiness += 25
            player.c.energy -= 30
            player.c.prestige += 8  # Organizing events builds prestige

            # Higher chance of meeting and bonding with more people
            num_people_met = random.randint(2, min(5, len(player.r))) if player.r else 0
            if num_people_met > 0:
                met_people = random.sample(player.r, num_people_met)
                for person in met_people:
                    person.affinity += random.randint(5, 12)
                    person.familiarity += random.randint(8, 15)

            # Small chance to trigger a follow-up opportunity
            if random.random() < 0.3:  # 30% chance
                player.c.diamonds += 5
                player.messageQueue.append(f"You helped organize the {event_name}! Everyone appreciated your hard work.")
                player.messageQueue.append("The community recognized your leadership and gave you a small reward!")
            else:
                player.messageQueue.append(f"You helped organize the {event_name}! Everyone appreciated your hard work.")

            if num_people_met > 0:
                player.messageQueue.append(f"You connected with {num_people_met} community member(s)!")

        else:  # no
            player.c.happiness -= 5
            player.messageQueue.append(f"You decided to skip the {event_name}.")


__all__ = [
    'joinClub',
    'volunteerWork',
    'bookClub',
    'gamingGroup',
    'communityEvent',
]
