"""
Career & Work Activity Events
Professional development and work-related activities (ages 18-65)

Events:
- professionalConference: Attend professional conference (ages 22-65, requires work)
- mentorJunior: Mentor a junior colleague (ages 30-65, requires work)
- sideHustle: Start a side business or freelance work (ages 18-65)
- networkingEvent: Attend networking event (ages 22-65, requires work)
- professionalCertification: Get professional certification (ages 22-65, requires work)

These events integrate with the job ActivityRecord system:
- Check player.c.activityRecords for job-type records
- Modify ActivityRecord.performance based on events
- Add certifications to ActivityRecord.achievements
- Side hustles create separate ActivityRecords
"""

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


def professionalConference(player, type='message', message=False, response=False):
    """Attend professional conference in your field"""
    fname = 'professionalConference'
    check = fname not in player.askedQuestions and player.c.ageYears >= 22 and player.c.ageYears <= 65 and player.c.occupation == 'work' and getattr(player.c, 'job', False) and player.c.money >= 100 and 1 >= random.random()*5000
    message = "A professional conference in your field is happening next month. Attend?"
    answerOptions = [
        answerOption('Yes, great networking!', moneyCost=500),
        answerOption('Virtual attendance only', moneyCost=100),
        answerOption('Skip it')
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        # Find job ActivityRecord to update performance
        job_record = None
        for record in player.c.activityRecords:
            if record.type == 'job' and record.id == player.c.job.id:
                job_record = record
                break

        if (response['option'] == answerOptions[0].option):
            player.messageQueue.append("You attend the conference in person. The networking opportunities are amazing, and you learn so much from the keynote speakers!")
            player.c.money -= 500
            player.c.intelligence += 20
            player.c.social += 25
            player.c.happiness += 15

            # Boost job performance - in-person conference has major impact
            if job_record:
                job_record.performance += 15
                if job_record.performance > 100:
                    job_record.performance = 100
                # Add achievement for attending conference
                conference_achievement = f"Attended {player.c.job.title} Professional Conference"
                if conference_achievement not in job_record.achievements:
                    job_record.achievements.append(conference_achievement)

        elif (response['option'] == answerOptions[1].option):
            player.messageQueue.append("You attend the conference virtually. It's not quite the same as being there in person, but you still gain valuable knowledge.")
            player.c.money -= 100
            player.c.intelligence += 15
            player.c.happiness += 10

            # Smaller performance boost for virtual attendance
            if job_record:
                job_record.performance += 8
                if job_record.performance > 100:
                    job_record.performance = 100

        elif (response['option'] == answerOptions[2].option):
            player.messageQueue.append("You decide to skip the conference. You save money, but you might have missed out on some good opportunities.")
            player.c.happiness -= 5

            # Small performance penalty for skipping professional development
            if job_record:
                job_record.performance -= 3
                if job_record.performance < 0:
                    job_record.performance = 0


def mentorJunior(player, type='message', message=False, response=False):
    """A junior colleague asks you to mentor them"""
    fname = 'mentorJunior'

    # Only trigger if player has decent job performance and isn't slacking off
    job_record = None
    for record in player.c.activityRecords:
        if record.type == 'job' and record.id == player.c.job.id:
            job_record = record
            break

    # More likely to be asked if working hard and performing well
    performance_check = (not job_record) or (job_record.performance >= 40 and job_record.focus != 'Slack Off')
    check = fname not in player.askedQuestions and player.c.ageYears >= 30 and player.c.ageYears <= 65 and player.c.occupation == 'work' and getattr(player.c, 'job', False) and performance_check and player.c.energy >= 10 and 1 >= random.random()*4000

    message = "A junior colleague approaches you and asks if you'd be willing to mentor them. Accept?"
    answerOptions = [
        answerOption('Yes, mentor them!', energyCost=10),
        answerOption('Informal help only'),
        answerOption('Too busy')
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['option'] == answerOptions[0].option):
            player.messageQueue.append("You agree to mentor them! It's rewarding to help someone grow in their career. You set up regular meetings and provide guidance.")
            player.c.energy -= 10
            player.c.happiness += 20
            player.c.social += 20

            # Mentoring boosts your own performance through leadership development
            if job_record:
                job_record.performance += 10
                if job_record.performance > 100:
                    job_record.performance = 100
                # Add mentoring achievement
                mentor_achievement = "Mentored junior colleague"
                if mentor_achievement not in job_record.achievements:
                    job_record.achievements.append(mentor_achievement)

        elif (response['option'] == answerOptions[1].option):
            player.messageQueue.append("You tell them you can't commit to formal mentoring, but you're happy to answer questions when they come up. It's a good compromise.")
            player.c.happiness += 10
            player.c.social += 10

            # Small performance boost for being helpful
            if job_record:
                job_record.performance += 5
                if job_record.performance > 100:
                    job_record.performance = 100

        elif (response['option'] == answerOptions[2].option):
            player.messageQueue.append("You politely decline, explaining you're too busy. They understand, but you feel a little guilty about it.")
            player.c.happiness -= 10

            # Small penalty for declining - missed leadership opportunity
            if job_record:
                job_record.performance -= 2
                if job_record.performance < 0:
                    job_record.performance = 0


def sideHustle(player, type='message', message=False, response=False):
    """Start a side business or freelance work"""
    fname = 'sideHustle'
    check = fname not in player.askedQuestions and player.c.ageYears >= 18 and player.c.ageYears <= 65 and player.c.energy >= 15 and 1 >= random.random()*6000
    message = "You've been thinking about starting a side business or doing freelance work to earn extra income. Do it?"
    answerOptions = [
        answerOption('Yes, commit to it!', energyCost=30),
        answerOption('Try it part-time', energyCost=15),
        answerOption('Too risky')
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        from functions import ActivityRecord, locationClass
        import uuid

        if (response['option'] == answerOptions[0].option):
            player.messageQueue.append("You dive into your side hustle with full commitment! It's exhausting juggling everything, but the extra income and sense of accomplishment feel great.")
            player.c.energy -= 30
            player.c.money += 300
            player.c.happiness += 25

            # Create side hustle as a separate activity
            side_hustle = locationClass()
            side_hustle.id = uuid.uuid4().hex
            side_hustle.type = 'side_hustle'
            side_hustle.title = 'Side Business (Full-time)'
            side_hustle.description = 'Your own side business venture'

            # Create activity record for side hustle
            hustle_record = ActivityRecord(side_hustle.id, 'side_hustle', player.date)
            hustle_record.performance = 50
            hustle_record.focus = 'Work Hard'

            player.c.activities.append(side_hustle)
            player.c.activityRecords.append(hustle_record)

            # Full commitment impacts main job performance if they have one
            for record in player.c.activityRecords:
                if record.type == 'job' and hasattr(player.c, 'job') and record.id == player.c.job.id:
                    record.performance -= 10  # Harder to juggle both
                    if record.performance < 0:
                        record.performance = 0
                    break

        elif (response['option'] == answerOptions[1].option):
            player.messageQueue.append("You start your side hustle on a part-time basis. It's manageable, and the extra income is nice without overwhelming you.")
            player.c.energy -= 15
            player.c.money += 150
            player.c.happiness += 15

            # Create part-time side hustle
            side_hustle = locationClass()
            side_hustle.id = uuid.uuid4().hex
            side_hustle.type = 'side_hustle'
            side_hustle.title = 'Side Business (Part-time)'
            side_hustle.description = 'Your part-time side business venture'

            # Create activity record for side hustle
            hustle_record = ActivityRecord(side_hustle.id, 'side_hustle', player.date)
            hustle_record.performance = 50
            hustle_record.focus = 'Balanced'

            player.c.activities.append(side_hustle)
            player.c.activityRecords.append(hustle_record)

            # Part-time has minimal impact on main job
            for record in player.c.activityRecords:
                if record.type == 'job' and hasattr(player.c, 'job') and record.id == player.c.job.id:
                    record.performance -= 3  # Slight distraction
                    if record.performance < 0:
                        record.performance = 0
                    break

        elif (response['option'] == answerOptions[2].option):
            player.messageQueue.append("You decide it's too risky right now. Maybe another time when you have more bandwidth.")
            player.c.happiness -= 10


def networkingEvent(player, type='message', message=False, response=False):
    """Attend networking event after work"""
    fname = 'networkingEvent'
    check = fname not in player.askedQuestions and player.c.ageYears >= 22 and player.c.ageYears <= 65 and player.c.occupation == 'work' and getattr(player.c, 'job', False) and player.c.energy >= 5 and 1 >= random.random()*3500
    message = "There's a networking event after work tonight. Your colleagues are going. Attend?"
    answerOptions = [
        answerOption('Yes, network actively!', energyCost=15),
        answerOption('Show up briefly', energyCost=5),
        answerOption('Skip it')
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        # Find job ActivityRecord to update performance
        job_record = None
        for record in player.c.activityRecords:
            if record.type == 'job' and record.id == player.c.job.id:
                job_record = record
                break

        if (response['option'] == answerOptions[0].option):
            player.messageQueue.append("You attend the networking event and actively engage with people. You exchange business cards, make genuine connections, and even meet someone who might lead to future opportunities!")
            player.c.energy -= 15
            player.c.social += 25
            player.c.happiness += 15

            # Active networking significantly boosts job performance
            if job_record:
                job_record.performance += 12
                if job_record.performance > 100:
                    job_record.performance = 100

                # Track networking achievement
                networking_count = sum(1 for achievement in job_record.achievements if 'Networking' in achievement)
                if networking_count == 0:
                    job_record.achievements.append("Active Networker")
                elif networking_count == 5:
                    job_record.achievements.append("Professional Network Master")

        elif (response['option'] == answerOptions[1].option):
            player.messageQueue.append("You show up for an hour, have a few quick conversations, then head home. It's good to make an appearance without exhausting yourself.")
            player.c.energy -= 5
            player.c.social += 10
            player.c.happiness += 5

            # Showing up still helps a bit
            if job_record:
                job_record.performance += 5
                if job_record.performance > 100:
                    job_record.performance = 100

        elif (response['option'] == answerOptions[2].option):
            player.messageQueue.append("You decide to skip the networking event. You could use the rest, but you wonder if you missed out on important connections.")
            player.c.happiness -= 5

            # Skipping networking events can hurt career progression
            if job_record:
                job_record.performance -= 5
                if job_record.performance < 0:
                    job_record.performance = 0


def professionalCertification(player, type='message', message=False, response=False):
    """Get professional certification in your field"""
    fname = 'professionalCertification'
    check = fname not in player.askedQuestions and player.c.ageYears >= 22 and player.c.ageYears <= 65 and player.c.occupation == 'work' and getattr(player.c, 'job', False) and player.c.money >= 500 and player.c.energy >= 15 and 1 >= random.random()*7000
    message = "You're considering getting a professional certification to advance your career. It requires time and money to study and take the exam. Go for it?"
    answerOptions = [
        answerOption('Yes, study and certify!', moneyCost=500, energyCost=40),
        answerOption('Self-study without cert', energyCost=15),
        answerOption('Not worth it')
    ]

    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        # Find job ActivityRecord to update performance and achievements
        job_record = None
        for record in player.c.activityRecords:
            if record.type == 'job' and record.id == player.c.job.id:
                job_record = record
                break

        if (response['option'] == answerOptions[0].option):
            player.messageQueue.append("You commit to getting the certification! Months of studying pay off when you pass the exam. It looks great on your resume and opens new doors.")
            player.c.money -= 500
            player.c.energy -= 40
            player.c.intelligence += 30
            player.c.happiness += 20

            # Major performance boost and achievement for certification
            if job_record:
                job_record.performance += 20
                if job_record.performance > 100:
                    job_record.performance = 100

                # Add certification to achievements
                cert_name = f"Professional Certification in {player.c.job.title}"
                if cert_name not in job_record.achievements:
                    job_record.achievements.append(cert_name)

                # Track total certifications for achievement
                cert_count = sum(1 for achievement in job_record.achievements if 'Certification' in achievement)
                if cert_count >= 3:
                    multi_cert = "Multi-Certified Professional"
                    if multi_cert not in job_record.achievements:
                        job_record.achievements.append(multi_cert)

        elif (response['option'] == answerOptions[1].option):
            player.messageQueue.append("You decide to self-study without pursuing the official certification. You still learn a lot, even if you don't have the credential to show for it.")
            player.c.energy -= 15
            player.c.intelligence += 15
            player.c.happiness += 5

            # Smaller performance boost without official credential
            if job_record:
                job_record.performance += 8
                if job_record.performance > 100:
                    job_record.performance = 100

        elif (response['option'] == answerOptions[2].option):
            player.messageQueue.append("You decide the certification isn't worth the time and money investment right now. Maybe you'll reconsider later.")
            player.c.happiness -= 5

            # No performance impact for declining


__all__ = [
    'professionalConference',
    'mentorJunior',
    'sideHustle',
    'networkingEvent',
    'professionalCertification',
]
