"""
Learning & Educational Activity Events
Activity events focused on learning and skill development (ages 6-100)

Events:
- onlineCourse: Take an online course to learn new skills (ages 16-100)
- learnLanguage: Start learning a new language (ages 10-100)
- codingBootcamp: Join a coding bootcamp (ages 16-50)
- musicLessons: Learn a musical instrument (ages 6-100)
- cookingClasses: Take cooking classes (ages 12-100)

Progress Events:
- onlineCourseProgress: Track progress in online course
- languageLearningProgress: Track language learning milestones
- codingBootcampProgress: Track bootcamp progress and completion
- musicLessonsProgress: Track musical skill development
- cookingClassProgress: Track cooking skill improvement

These events integrate with the ActivityRecord system:
- Create ActivityRecords to track progress and performance
- Performance affected by focus (Work Hard = faster learning, Slack Off = slower)
- Achievements added for milestones
- Some activities unlock new jobs or improve job performance
- Finite duration for courses (bootcamp ends after N weeks)
"""

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


def onlineCourse(player, type='message', message=False, response=False):
    """Take an online course to learn new skills (ages 16-100)"""
    fname = 'onlineCourse'
    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 16 and
             player.c.ageYears <= 100 and
             1 >= random.random() * 1000)

    # Determine course topic based on age and current job
    if hasattr(player.c, 'job') and player.c.job:
        course_topics = ["Advanced " + player.c.job.title + " Techniques", "Leadership & Management",
                        "Data Analysis", "Digital Marketing", "Project Management"]
    else:
        course_topics = ["Web Development", "Graphic Design", "Business Analytics",
                        "Digital Marketing", "Photography"]

    course_topic = random.choice(course_topics)
    message = f"You want to take an online course in {course_topic}. Enroll?"

    if type != 'answer':
        answerOptions = [
            answerOption("Yes, paid course!", data="paid", moneyCost=100),
            answerOption("Free course instead", data="free"),
            answerOption("Self-study without course", data="self"),
            answerOption("Not interested", data="no")
        ]
        return questionFunction(fname, message, player, check, answerOptions)

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

        if response['data'] == 'paid':
            player.c.money -= 100
            player.c.happiness += 15
            player.c.intelligence += 5

            # Create ActivityRecord for tracking course progress
            course_record = ActivityRecord(
                id=f"onlinecourse_{course_topic}_{player.date}",
                type="online_course",
                date=player.date
            )
            course_record.level = course_topic
            course_record.performance = 60  # Start at 60%
            course_record.focus = 'Balanced'
            player.c.activityRecords.append(course_record)

            # Schedule progress check event in 4 weeks
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Online Course Progress Check",
                    message=f"How's your {course_topic} course going?",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=28,
                    completionFunc=onlineCourseProgress,
                    completionArgs=(),
                    completionKwargs={'course_record_id': course_record.id}
                )
            )

            player.messageQueue.append(f"You enrolled in a paid online course in {course_topic}! The structured curriculum and expert instruction will help you learn efficiently.")

        elif response['data'] == 'free':
            player.c.happiness += 10
            player.c.intelligence += 3

            # Create ActivityRecord for free course (lower starting performance)
            course_record = ActivityRecord(
                id=f"onlinecourse_free_{course_topic}_{player.date}",
                type="online_course_free",
                date=player.date
            )
            course_record.level = course_topic
            course_record.performance = 40  # Start lower for free course
            course_record.focus = 'Balanced'
            player.c.activityRecords.append(course_record)

            player.messageQueue.append(f"You found a great free course in {course_topic}! It might take more self-discipline, but you're excited to learn.")

        elif response['data'] == 'self':
            player.c.intelligence += 2
            player.messageQueue.append(f"You decide to teach yourself {course_topic} through free resources. It's a slower path, but you enjoy the flexibility.")

        else:  # no
            player.c.happiness -= 5
            player.messageQueue.append("You decided learning a new skill isn't a priority right now.")


def onlineCourseProgress(player, type='message', message=False, response=False, course_record_id=None):
    """Progress check for online course"""
    fname = f'onlineCourseProgress_{course_record_id}'

    # Find the course record
    course_record = None
    for record in player.c.activityRecords:
        if record.id == course_record_id:
            course_record = record
            break

    if not course_record:
        return  # Course record not found, maybe dropped

    # Calculate progress based on focus
    focus_map = {
        'Work Hard': 25,
        'Balanced': 15,
        'Slack Off': 5,
        'Socialize': 10
    }
    progress_gain = focus_map.get(course_record.focus, 15)
    course_record.performance = min(100, course_record.performance + progress_gain)

    if course_record.performance >= 100:
        # Course completed!
        player.c.intelligence += 20
        player.c.happiness += 25
        course_record.achievements.append(f"Completed {course_record.level}")

        # If job-related, boost job performance
        if hasattr(player.c, 'job') and player.c.job:
            for job_record in player.c.activityRecords:
                if job_record.type == 'job' and job_record.id == player.c.job.id:
                    job_record.performance = min(100, job_record.performance + 15)
                    player.messageQueue.append(f"Completing the {course_record.level} course has improved your job performance!")
                    break

        player.messageQueue.append(f"Congratulations! You've completed your {course_record.level} course with a strong understanding of the material. This new knowledge will serve you well!")

    elif course_record.performance >= 75:
        # Good progress
        player.c.intelligence += 10
        player.c.happiness += 10
        player.messageQueue.append(f"You're making excellent progress in your {course_record.level} course! You're really grasping the concepts.")

        # Schedule final progress check in 3 weeks
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title="Online Course Final Check",
                message=f"Final stretch of your {course_record.level} course!",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=21,
                completionFunc=onlineCourseProgress,
                completionArgs=(),
                completionKwargs={'course_record_id': course_record.id}
            )
        )

    elif course_record.performance >= 50:
        # Decent progress
        player.c.intelligence += 5
        player.messageQueue.append(f"You're making steady progress in your {course_record.level} course. Keep at it!")

        # Schedule next progress check
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title="Online Course Progress Check",
                message=f"Continuing your {course_record.level} course",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=21,
                completionFunc=onlineCourseProgress,
                completionArgs=(),
                completionKwargs={'course_record_id': course_record.id}
            )
        )

    else:
        # Poor progress - might drop the course
        player.c.happiness -= 10
        player.c.stress += 10
        player.messageQueue.append(f"You're struggling to keep up with your {course_record.level} course. You might need to put in more effort or consider dropping it.")


def learnLanguage(player, type='message', message=False, response=False):
    """Start learning a new language (ages 10-100)"""
    from functions import scheduler

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

    # Choose a random language
    languages = ["Spanish", "French", "Mandarin Chinese", "Japanese", "German",
                "Italian", "Portuguese", "Korean", "Arabic", "Russian"]
    language = random.choice(languages)

    message = f"You want to learn {language}. Start?"

    if type != 'answer':
        answerOptions = [
            answerOption("Yes, formal classes!", data="classes", moneyCost=150),
            answerOption("Use language app", data="app", moneyCost=10),
            answerOption("Study on own", data="self"),
            answerOption("Too hard", data="no")
        ]
        return questionFunction(fname, message, player, check, answerOptions)

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

        if response['data'] == 'classes':
            player.c.money -= 150
            player.c.social += 10
            player.c.intelligence += 5

            # Create ActivityRecord for language learning
            language_record = ActivityRecord(
                id=f"language_{language}_{player.date}",
                type="language_learning",
                date=player.date
            )
            language_record.level = language
            language_record.performance = 0  # Start at Beginner (0-24 = Beginner)
            language_record.focus = 'Balanced'
            language_record.achievements = []
            player.c.activityRecords.append(language_record)

            # Create language class schedule
            player.c.schedules.append(
                scheduler(
                    player.c,
                    f"{language} Class",
                    ["twice-week", "evening"],
                    location="languageschool" + player.c.id,
                    duration=random.randint(60, 90)
                )
            )

            # Schedule first progress check in 8 weeks
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title=f"{language} Learning Progress",
                    message=f"How's your {language} learning going?",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=56,
                    completionFunc=languageLearningProgress,
                    completionArgs=(),
                    completionKwargs={'language_record_id': language_record.id}
                )
            )

            player.messageQueue.append(f"You enrolled in formal {language} classes! Having a teacher and classmates will make learning more effective.")

        elif response['data'] == 'app':
            player.c.money -= 10
            player.c.happiness += 10
            player.c.intelligence += 3

            # Create ActivityRecord for app-based learning (slower progress)
            language_record = ActivityRecord(
                id=f"language_app_{language}_{player.date}",
                type="language_learning_app",
                date=player.date
            )
            language_record.level = language
            language_record.performance = 0
            language_record.focus = 'Balanced'
            player.c.activityRecords.append(language_record)

            player.messageQueue.append(f"You downloaded a {language} learning app! A few minutes of practice each day should help you progress.")

        elif response['data'] == 'self':
            player.c.intelligence += 2
            player.messageQueue.append(f"You gathered textbooks and online resources to teach yourself {language}. It'll be challenging, but you're determined!")

        else:  # no
            player.c.happiness -= 10
            player.messageQueue.append("You decided learning a new language is too difficult right now.")


def languageLearningProgress(player, type='message', message=False, response=False, language_record_id=None):
    """Track language learning milestones"""
    fname = f'languageLearningProgress_{language_record_id}'

    # Find the language record
    language_record = None
    for record in player.c.activityRecords:
        if record.id == language_record_id:
            language_record = record
            break

    if not language_record:
        return

    # Calculate progress based on focus and type
    focus_map = {
        'Work Hard': 15,
        'Balanced': 10,
        'Slack Off': 3,
        'Socialize': 8  # Social focus helps with language learning!
    }

    # App-based learning is slower
    if language_record.type == "language_learning_app":
        progress_multiplier = 0.6
    else:
        progress_multiplier = 1.0

    progress_gain = int(focus_map.get(language_record.focus, 10) * progress_multiplier)
    language_record.performance = min(100, language_record.performance + progress_gain)

    # Determine proficiency level
    # 0-24: Beginner, 25-49: Elementary, 50-74: Intermediate, 75-89: Advanced, 90-100: Fluent
    language = language_record.level

    if language_record.performance >= 90 and "Fluent" not in str(language_record.achievements):
        # Achieved fluency!
        player.c.intelligence += 30
        player.c.happiness += 35
        language_record.achievements.append(f"Fluent in {language}")

        # Unlock job benefits for language-related jobs
        if hasattr(player.c, 'job') and player.c.job:
            job_title = player.c.job.title
            if any(word in job_title for word in ["Teacher", "Translator", "Diplomat", "International"]):
                for job_record in player.c.activityRecords:
                    if job_record.type == 'job' and job_record.id == player.c.job.id:
                        job_record.performance = min(100, job_record.performance + 20)
                        player.messageQueue.append(f"Your fluency in {language} has significantly boosted your job performance!")
                        break

        player.messageQueue.append(f"Amazing! You've achieved fluency in {language}! You can now comfortably speak, read, and write in the language. This is a major accomplishment!")

    elif language_record.performance >= 75 and "Advanced" not in str(language_record.achievements):
        # Reached advanced level
        player.c.intelligence += 20
        player.c.happiness += 20
        language_record.achievements.append(f"Advanced {language}")
        player.messageQueue.append(f"You've reached an advanced level in {language}! You can hold complex conversations and understand most native content.")

        # Schedule next progress check
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title=f"{language} Learning Progress",
                message=f"Approaching fluency in {language}!",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=84,
                completionFunc=languageLearningProgress,
                completionArgs=(),
                completionKwargs={'language_record_id': language_record.id}
            )
        )

    elif language_record.performance >= 50 and "Intermediate" not in str(language_record.achievements):
        # Reached intermediate level
        player.c.intelligence += 15
        player.c.happiness += 15
        language_record.achievements.append(f"Intermediate {language}")
        player.messageQueue.append(f"You've reached an intermediate level in {language}! You can handle everyday conversations with growing confidence.")

        # Schedule next progress check
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title=f"{language} Learning Progress",
                message=f"Continuing {language} studies",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=84,
                completionFunc=languageLearningProgress,
                completionArgs=(),
                completionKwargs={'language_record_id': language_record.id}
            )
        )

    elif language_record.performance >= 25 and "Elementary" not in str(language_record.achievements):
        # Reached elementary level
        player.c.intelligence += 10
        player.c.happiness += 10
        language_record.achievements.append(f"Elementary {language}")
        player.messageQueue.append(f"You've reached an elementary level in {language}! You can introduce yourself and handle basic conversations.")

        # Schedule next progress check
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title=f"{language} Learning Progress",
                message=f"Progressing in {language}",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=84,
                completionFunc=languageLearningProgress,
                completionArgs=(),
                completionKwargs={'language_record_id': language_record.id}
            )
        )

    elif language_record.performance < 25:
        # Still at beginner level
        player.c.intelligence += 5
        if language_record.focus == 'Slack Off':
            player.c.happiness -= 5
            player.messageQueue.append(f"Your {language} progress is slow. You might need to dedicate more time to studying if you want to improve.")
        else:
            player.messageQueue.append(f"You're building a foundation in {language}. The beginning is always the hardest part!")

        # Schedule next progress check
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title=f"{language} Learning Progress",
                message=f"Building skills in {language}",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=56,
                completionFunc=languageLearningProgress,
                completionArgs=(),
                completionKwargs={'language_record_id': language_record.id}
            )
        )


def codingBootcamp(player, type='message', message=False, response=False):
    """Join a coding bootcamp (ages 16-50)"""
    fname = 'codingBootcamp'
    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 16 and
             player.c.ageYears <= 50 and
             1 >= random.random() * 1000)

    # Different bootcamp specializations
    specializations = ["Full-Stack Web Development", "Data Science & Machine Learning",
                      "Mobile App Development", "Cybersecurity", "DevOps Engineering"]
    specialization = random.choice(specializations)

    message = f"There's a {specialization} bootcamp starting. Interested?"

    if type != 'answer':
        answerOptions = [
            answerOption("Yes, full-time bootcamp!", data="fulltime", moneyCost=3000, energyCost=40),
            answerOption("Part-time evening classes", data="parttime", moneyCost=1500, energyCost=20),
            answerOption("Learn coding online free", data="online"),
            answerOption("Not for me", data="no")
        ]
        return questionFunction(fname, message, player, check, answerOptions)

    elif type == 'answer':
        from functions import ActivityRecord, oneTimeEvent, scheduler

        if response['data'] == 'fulltime':
            player.c.money -= 3000
            player.c.energy -= 40
            player.c.intelligence += 10

            # Create ActivityRecord for bootcamp
            bootcamp_record = ActivityRecord(
                id=f"bootcamp_{specialization}_{player.date}",
                type="coding_bootcamp",
                date=player.date
            )
            bootcamp_record.level = specialization
            bootcamp_record.performance = 50  # Start at 50%
            bootcamp_record.focus = 'Balanced'
            bootcamp_record.achievements = []
            player.c.activityRecords.append(bootcamp_record)

            # Create full-time bootcamp schedule (weekdays, all day)
            player.c.schedules.append(
                scheduler(
                    player.c,
                    f"{specialization} Bootcamp",
                    ["weekday", "morning"],
                    location="bootcamp" + player.c.id,
                    duration=random.randint(360, 480)
                )
            )

            # Schedule mid-bootcamp progress check (6 weeks)
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Bootcamp Midpoint",
                    message=f"You're halfway through the {specialization} bootcamp!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=42,
                    completionFunc=codingBootcampProgress,
                    completionArgs=(),
                    completionKwargs={'bootcamp_record_id': bootcamp_record.id, 'stage': 'midpoint'}
                )
            )

            player.messageQueue.append(f"You enrolled in an intensive full-time {specialization} bootcamp! The next few months will be exhausting but you'll gain valuable programming skills.")

        elif response['data'] == 'parttime':
            player.c.money -= 1500
            player.c.energy -= 20
            player.c.intelligence += 5

            # Create ActivityRecord for part-time bootcamp
            bootcamp_record = ActivityRecord(
                id=f"bootcamp_pt_{specialization}_{player.date}",
                type="coding_bootcamp_parttime",
                date=player.date
            )
            bootcamp_record.level = specialization
            bootcamp_record.performance = 40  # Part-time starts lower
            bootcamp_record.focus = 'Balanced'
            player.c.activityRecords.append(bootcamp_record)

            # Create part-time schedule (evenings, 3x/week)
            player.c.schedules.append(
                scheduler(
                    player.c,
                    f"{specialization} Bootcamp",
                    ["three-times-week", "evening"],
                    location="bootcamp" + player.c.id,
                    duration=random.randint(180, 240)
                )
            )

            # Schedule progress check (takes longer for part-time, 10 weeks)
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Bootcamp Progress Check",
                    message=f"Checking in on your {specialization} bootcamp progress",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=70,
                    completionFunc=codingBootcampProgress,
                    completionArgs=(),
                    completionKwargs={'bootcamp_record_id': bootcamp_record.id, 'stage': 'midpoint'}
                )
            )

            player.messageQueue.append(f"You signed up for part-time evening {specialization} classes! It'll be challenging to balance with everything else, but you're excited to learn.")

        elif response['data'] == 'online':
            player.c.intelligence += 3
            player.messageQueue.append(f"You found free coding tutorials online for {specialization}. It'll take longer without structure, but you can learn at your own pace.")

        else:  # no
            player.c.happiness -= 5
            player.messageQueue.append("You decided coding isn't something you want to pursue right now.")


def codingBootcampProgress(player, type='message', message=False, response=False, bootcamp_record_id=None, stage='midpoint'):
    """Track bootcamp progress and completion"""
    fname = f'codingBootcampProgress_{bootcamp_record_id}_{stage}'

    # Find the bootcamp record
    bootcamp_record = None
    for record in player.c.activityRecords:
        if record.id == bootcamp_record_id:
            bootcamp_record = record
            break

    if not bootcamp_record:
        return

    # Calculate progress based on focus
    focus_map = {
        'Work Hard': 30,
        'Balanced': 20,
        'Slack Off': 5,
        'Socialize': 15
    }

    # Part-time bootcamp progresses slower
    if bootcamp_record.type == "coding_bootcamp_parttime":
        progress_multiplier = 0.7
    else:
        progress_multiplier = 1.0

    progress_gain = int(focus_map.get(bootcamp_record.focus, 20) * progress_multiplier)
    bootcamp_record.performance = min(100, bootcamp_record.performance + progress_gain)

    specialization = bootcamp_record.level

    if stage == 'midpoint':
        # Midpoint check
        if bootcamp_record.performance >= 70:
            player.c.intelligence += 15
            player.c.happiness += 15
            bootcamp_record.achievements.append(f"Excellent Progress - {specialization}")
            player.messageQueue.append(f"You're excelling in the {specialization} bootcamp! Your instructors are impressed with your progress.")
        elif bootcamp_record.performance >= 50:
            player.c.intelligence += 10
            player.c.happiness += 10
            player.messageQueue.append(f"You're making solid progress in the {specialization} bootcamp. Keep pushing through!")
        else:
            player.c.intelligence += 5
            player.c.happiness -= 10
            player.c.stress += 15
            player.messageQueue.append(f"You're struggling to keep up in the {specialization} bootcamp. The pace is intense and you're feeling overwhelmed.")

        # Schedule final/graduation check
        from functions import oneTimeEvent
        completion_days = 42 if bootcamp_record.type == "coding_bootcamp" else 70
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title="Bootcamp Graduation",
                message=f"Final days of {specialization} bootcamp!",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=completion_days,
                completionFunc=codingBootcampProgress,
                completionArgs=(),
                completionKwargs={'bootcamp_record_id': bootcamp_record.id, 'stage': 'completion'}
            )
        )

    elif stage == 'completion':
        # Bootcamp completion
        if bootcamp_record.performance >= 80:
            # Graduated with honors!
            player.c.intelligence += 40
            player.c.happiness += 40
            player.c.prestige += 15
            bootcamp_record.achievements.append(f"Graduated with Honors - {specialization}")

            # Remove bootcamp schedule
            player.c.schedules = [s for s in player.c.schedules if specialization not in s.title]

            # Check if can now qualify for tech jobs
            tech_job_titles = ["Software Engineer", "Data Scientist", "Mobile Developer", "Security Analyst", "DevOps Engineer"]
            player.messageQueue.append(f"Congratulations! You graduated from the {specialization} bootcamp with honors! You now have the skills to pursue careers in {specialization}.")

            # If currently unemployed or in unrelated job, suggest applying for tech jobs
            if not hasattr(player.c, 'job') or player.c.occupation != 'work':
                player.messageQueue.append("With your new skills, you should consider applying for entry-level positions in tech!")

        elif bootcamp_record.performance >= 60:
            # Graduated
            player.c.intelligence += 30
            player.c.happiness += 30
            player.c.prestige += 10
            bootcamp_record.achievements.append(f"Completed {specialization}")

            # Remove bootcamp schedule
            player.c.schedules = [s for s in player.c.schedules if specialization not in s.title]

            player.messageQueue.append(f"You graduated from the {specialization} bootcamp! You have a solid foundation in programming and are ready to start your career transition.")

        else:
            # Struggled to complete
            player.c.intelligence += 15
            player.c.happiness -= 20
            player.c.stress += 20
            bootcamp_record.achievements.append(f"Completed {specialization} (with difficulty)")

            # Remove bootcamp schedule
            player.c.schedules = [s for s in player.c.schedules if specialization not in s.title]

            player.messageQueue.append(f"You completed the {specialization} bootcamp, but it was a real struggle. You learned some things, but feel you need more practice before feeling job-ready.")


def musicLessons(player, type='message', message=False, response=False):
    """Learn a musical instrument (ages 6-100)"""
    from functions import scheduler

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

    # Age-appropriate instruments
    if player.c.ageYears < 10:
        instruments = ["piano", "violin", "ukulele", "recorder"]
    elif player.c.ageYears < 18:
        instruments = ["piano", "guitar", "violin", "drums", "saxophone", "trumpet"]
    else:
        instruments = ["piano", "guitar", "violin", "drums", "saxophone", "bass guitar", "cello"]

    instrument = random.choice(instruments)
    message = f"You want to learn to play the {instrument}. Take lessons?"

    if type != 'answer':
        answerOptions = [
            answerOption("Yes, professional teacher!", data="teacher", moneyCost=100),
            answerOption("Learn from YouTube", data="youtube"),
            answerOption("Buy instrument, figure it out", data="self", moneyCost=200),
            answerOption("Not interested", data="no")
        ]
        return questionFunction(fname, message, player, check, answerOptions)

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

        if response['data'] == 'teacher':
            player.c.money -= 100
            player.c.happiness += 25
            player.c.stress -= 10

            # Create ActivityRecord for music lessons
            music_record = ActivityRecord(
                id=f"music_{instrument}_{player.date}",
                type="music_lessons",
                date=player.date
            )
            music_record.level = instrument
            music_record.performance = 0  # 0-19: Beginner, 20-49: Amateur, 50-74: Skilled, 75-89: Expert, 90-100: Master
            music_record.focus = 'Balanced'
            music_record.achievements = []
            player.c.activityRecords.append(music_record)

            # Create music lesson schedule
            player.c.schedules.append(
                scheduler(
                    player.c,
                    f"{instrument.title()} Lessons",
                    ["weekly", "afternoon"],
                    location="musicschool" + player.c.id,
                    duration=random.randint(45, 60)
                )
            )

            # Schedule first progress check in 3 months
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title=f"{instrument.title()} Progress Check",
                    message=f"How's your {instrument} playing coming along?",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=90,
                    completionFunc=musicLessonsProgress,
                    completionArgs=(),
                    completionKwargs={'music_record_id': music_record.id}
                )
            )

            player.messageQueue.append(f"You signed up for professional {instrument} lessons! Having a teacher will help you develop proper technique and avoid bad habits.")

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

            # Create ActivityRecord for self-teaching (slower progress)
            music_record = ActivityRecord(
                id=f"music_youtube_{instrument}_{player.date}",
                type="music_self_taught",
                date=player.date
            )
            music_record.level = instrument
            music_record.performance = 0
            music_record.focus = 'Balanced'
            player.c.activityRecords.append(music_record)

            player.messageQueue.append(f"You're learning {instrument} from YouTube tutorials! It's free and flexible, though progress might be slower without feedback.")

        elif response['data'] == 'self':
            player.c.money -= 200
            player.c.happiness += 10
            player.messageQueue.append(f"You bought a {instrument} and are teaching yourself! It'll be a journey of trial and error, but you enjoy the independence.")

        else:  # no
            player.c.happiness -= 5
            player.messageQueue.append("You decided learning an instrument isn't for you right now.")


def musicLessonsProgress(player, type='message', message=False, response=False, music_record_id=None):
    """Track musical skill development"""
    fname = f'musicLessonsProgress_{music_record_id}'

    # Find the music record
    music_record = None
    for record in player.c.activityRecords:
        if record.id == music_record_id:
            music_record = record
            break

    if not music_record:
        return

    # Calculate progress based on focus
    focus_map = {
        'Work Hard': 12,
        'Balanced': 8,
        'Slack Off': 2,
        'Socialize': 6
    }

    # Self-taught progresses slower
    if music_record.type == "music_self_taught":
        progress_multiplier = 0.5
    else:
        progress_multiplier = 1.0

    progress_gain = int(focus_map.get(music_record.focus, 8) * progress_multiplier)
    music_record.performance = min(100, music_record.performance + progress_gain)

    instrument = music_record.level

    # Determine skill level: 0-19: Beginner, 20-49: Amateur, 50-74: Skilled, 75-89: Expert, 90-100: Master

    if music_record.performance >= 90 and "Master" not in str(music_record.achievements):
        # Achieved mastery!
        player.c.happiness += 50
        player.c.prestige += 20
        player.c.stress -= 20
        music_record.achievements.append(f"Master {instrument} Player")
        player.messageQueue.append(f"You've achieved mastery of the {instrument}! You can play complex pieces with emotion and technical perfection. People are moved when they hear you play.")

        # Could potentially earn money performing
        if random.random() < 0.3:
            performance_earnings = random.randint(200, 500)
            player.c.money += performance_earnings
            player.messageQueue.append(f"Your skill has opened up performance opportunities! You earned ${performance_earnings} from a recent gig.")

    elif music_record.performance >= 75 and "Expert" not in str(music_record.achievements):
        # Reached expert level
        player.c.happiness += 30
        player.c.prestige += 10
        player.c.stress -= 15
        music_record.achievements.append(f"Expert {instrument} Player")
        player.messageQueue.append(f"You've become an expert {instrument} player! You can tackle difficult pieces and your playing sounds professional.")

        # Schedule next progress check
        from functions import oneTimeEvent
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title=f"{instrument.title()} Progress",
                message=f"Advancing toward mastery of {instrument}",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=120,
                completionFunc=musicLessonsProgress,
                completionArgs=(),
                completionKwargs={'music_record_id': music_record.id}
            )
        )

    elif music_record.performance >= 50 and "Skilled" not in str(music_record.achievements):
        # Reached skilled level
        player.c.happiness += 25
        player.c.stress -= 10
        music_record.achievements.append(f"Skilled {instrument} Player")
        player.messageQueue.append(f"You've become a skilled {instrument} player! You can play intermediate pieces confidently and your playing brings you joy.")

        # Schedule next progress check
        from functions import oneTimeEvent
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title=f"{instrument.title()} Progress",
                message=f"Continuing {instrument} practice",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=120,
                completionFunc=musicLessonsProgress,
                completionArgs=(),
                completionKwargs={'music_record_id': music_record.id}
            )
        )

    elif music_record.performance >= 20 and "Amateur" not in str(music_record.achievements):
        # Reached amateur level
        player.c.happiness += 20
        player.c.stress -= 5
        music_record.achievements.append(f"Amateur {instrument} Player")
        player.messageQueue.append(f"You're now an amateur {instrument} player! You can play simple songs and you're starting to sound decent.")

        # Schedule next progress check
        from functions import oneTimeEvent
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title=f"{instrument.title()} Progress",
                message=f"Progressing with {instrument}",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=90,
                completionFunc=musicLessonsProgress,
                completionArgs=(),
                completionKwargs={'music_record_id': music_record.id}
            )
        )

    else:
        # Still at beginner level or early progress
        player.c.happiness += 10
        player.c.stress -= 5

        if music_record.focus == 'Slack Off':
            player.messageQueue.append(f"You're not practicing the {instrument} much. Without consistent practice, it's hard to improve.")
        else:
            player.messageQueue.append(f"You're making steady progress with the {instrument}. Your fingers are getting more comfortable with the movements.")

        # Schedule next progress check
        from functions import oneTimeEvent
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title=f"{instrument.title()} Progress",
                message=f"Building skills on {instrument}",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=90,
                completionFunc=musicLessonsProgress,
                completionArgs=(),
                completionKwargs={'music_record_id': music_record.id}
            )
        )


def cookingClasses(player, type='message', message=False, response=False):
    """Take cooking classes (ages 12-100)"""
    from functions import scheduler

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

    # Different cooking class types based on age
    if player.c.ageYears < 18:
        class_types = ["Basic Cooking Skills", "Baking Fundamentals", "Teen Chef Program"]
    else:
        class_types = ["Italian Cuisine", "French Cooking", "Asian Fusion", "Baking & Pastry",
                      "Vegetarian Cooking", "Culinary Techniques"]

    class_type = random.choice(class_types)
    message = f"{class_type} classes are available at community center. Join?"

    if type != 'answer':
        answerOptions = [
            answerOption("Yes, sign up!", data="signup", moneyCost=75),
            answerOption("Learn from cookbooks", data="books"),
            answerOption("Watch cooking videos", data="videos"),
            answerOption("Not interested", data="no")
        ]
        return questionFunction(fname, message, player, check, answerOptions)

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

        if response['data'] == 'signup':
            player.c.money -= 75
            player.c.happiness += 20
            player.c.social += 10

            # Create ActivityRecord for cooking classes
            cooking_record = ActivityRecord(
                id=f"cooking_{class_type}_{player.date}",
                type="cooking_classes",
                date=player.date
            )
            cooking_record.level = class_type
            cooking_record.performance = 0  # 0-24: Novice, 25-49: Competent, 50-74: Proficient, 75-89: Expert, 90-100: Master Chef
            cooking_record.focus = 'Balanced'
            cooking_record.achievements = []
            player.c.activityRecords.append(cooking_record)

            # Create cooking class schedule
            player.c.schedules.append(
                scheduler(
                    player.c,
                    f"{class_type} Class",
                    ["weekly", "evening"],
                    location="communitycenter" + player.c.id,
                    duration=random.randint(90, 120)
                )
            )

            # Schedule first progress check in 6 weeks
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Cooking Class Progress",
                    message=f"How are your {class_type} classes going?",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=42,
                    completionFunc=cookingClassProgress,
                    completionArgs=(),
                    completionKwargs={'cooking_record_id': cooking_record.id}
                )
            )

            player.messageQueue.append(f"You enrolled in {class_type} classes! You'll learn new techniques and recipes while meeting fellow food enthusiasts.")

        elif response['data'] == 'books':
            player.c.happiness += 10
            player.c.intelligence += 3

            # Create basic ActivityRecord for self-teaching
            cooking_record = ActivityRecord(
                id=f"cooking_books_{class_type}_{player.date}",
                type="cooking_self_taught",
                date=player.date
            )
            cooking_record.level = "Home Cooking"
            cooking_record.performance = 0
            cooking_record.focus = 'Balanced'
            player.c.activityRecords.append(cooking_record)

            player.messageQueue.append("You checked out some cookbooks from the library. You'll teach yourself by trying new recipes at home.")

        elif response['data'] == 'videos':
            player.c.happiness += 5
            player.messageQueue.append("You found some cooking channels online. Watching chefs in action is a great way to pick up tips and tricks.")

        else:  # no
            player.c.happiness -= 5
            player.messageQueue.append("You decided cooking classes aren't for you right now.")


def cookingClassProgress(player, type='message', message=False, response=False, cooking_record_id=None):
    """Track cooking skill improvement"""
    fname = f'cookingClassProgress_{cooking_record_id}'

    # Find the cooking record
    cooking_record = None
    for record in player.c.activityRecords:
        if record.id == cooking_record_id:
            cooking_record = record
            break

    if not cooking_record:
        return

    # Calculate progress based on focus
    focus_map = {
        'Work Hard': 15,
        'Balanced': 10,
        'Slack Off': 3,
        'Socialize': 12  # Cooking classes are social!
    }

    # Self-taught progresses slower
    if cooking_record.type == "cooking_self_taught":
        progress_multiplier = 0.6
    else:
        progress_multiplier = 1.0

    progress_gain = int(focus_map.get(cooking_record.focus, 10) * progress_multiplier)
    cooking_record.performance = min(100, cooking_record.performance + progress_gain)

    class_type = cooking_record.level

    # Determine skill level: 0-24: Novice, 25-49: Competent, 50-74: Proficient, 75-89: Expert, 90-100: Master Chef

    if cooking_record.performance >= 90 and "Master Chef" not in str(cooking_record.achievements):
        # Achieved master chef level!
        player.c.happiness += 45
        player.c.social += 25
        player.c.prestige += 15
        cooking_record.achievements.append(f"Master Chef - {class_type}")

        # Permanent benefits - save money on food
        player.messageQueue.append(f"You've become a master chef in {class_type}! Your dishes are restaurant-quality. Friends and family rave about your cooking, and you save money by cooking amazing meals at home.")

        # Could potentially start a food-related side business
        if random.random() < 0.2:
            side_income = random.randint(150, 300)
            player.c.money += side_income
            player.messageQueue.append(f"Your cooking skills are so good that you've started earning money from catering or selling baked goods! You made ${side_income} this month.")

    elif cooking_record.performance >= 75 and "Expert" not in str(cooking_record.achievements):
        # Reached expert level
        player.c.happiness += 30
        player.c.social += 15
        cooking_record.achievements.append(f"Expert Cook - {class_type}")
        player.messageQueue.append(f"You've become an expert in {class_type}! You can prepare complex dishes with confidence and people love when you cook for them.")

        # Schedule next progress check
        from functions import oneTimeEvent
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title="Cooking Progress",
                message=f"Continuing to master {class_type}",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=56,
                completionFunc=cookingClassProgress,
                completionArgs=(),
                completionKwargs={'cooking_record_id': cooking_record.id}
            )
        )

    elif cooking_record.performance >= 50 and "Proficient" not in str(cooking_record.achievements):
        # Reached proficient level
        player.c.happiness += 25
        player.c.social += 10
        player.c.money += 30  # Save money by cooking better meals
        cooking_record.achievements.append(f"Proficient Cook - {class_type}")
        player.messageQueue.append(f"You're now proficient in {class_type}! You can cook a variety of dishes well and enjoy experimenting with recipes.")

        # Schedule next progress check
        from functions import oneTimeEvent
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title="Cooking Progress",
                message=f"Advancing in {class_type}",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=56,
                completionFunc=cookingClassProgress,
                completionArgs=(),
                completionKwargs={'cooking_record_id': cooking_record.id}
            )
        )

    elif cooking_record.performance >= 25 and "Competent" not in str(cooking_record.achievements):
        # Reached competent level
        player.c.happiness += 20
        player.c.social += 5
        player.c.money += 20  # Save a bit on food
        cooking_record.achievements.append(f"Competent Cook - {class_type}")
        player.messageQueue.append(f"You're becoming a competent cook in {class_type}! You can follow recipes successfully and your meals are consistently good.")

        # Schedule next progress check
        from functions import oneTimeEvent
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title="Cooking Progress",
                message=f"Building skills in {class_type}",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=42,
                completionFunc=cookingClassProgress,
                completionArgs=(),
                completionKwargs={'cooking_record_id': cooking_record.id}
            )
        )

    else:
        # Still at novice level
        player.c.happiness += 10

        if cooking_record.focus == 'Slack Off':
            player.messageQueue.append(f"You're not putting much effort into your {class_type} classes. Without practice, it's hard to improve your cooking.")
        else:
            player.messageQueue.append(f"You're learning the basics of {class_type}. Every class teaches you something new!")

        # Schedule next progress check
        from functions import oneTimeEvent
        player.c.oneTimeEvents.append(
            oneTimeEvent(
                title="Cooking Progress",
                message=f"Continuing {class_type} classes",
                date=player.date,
                dateType="daysFromNow",
                dateModifier=42,
                completionFunc=cookingClassProgress,
                completionArgs=(),
                completionKwargs={'cooking_record_id': cooking_record.id}
            )
        )


def handleLearningActivities(player, person):
    """
    Updates learning activity performance based on focus level.

    This function should be called during the game loop to update performance
    for all active learning activities (similar to handleEducation and handleJob).

    Performance modifiers by focus:
    - Work Hard: +1 per tick (faster learning)
    - Balanced: +0.5 per tick (steady learning)
    - Slack Off: +0.1 per tick (minimal learning)
    - Socialize: +0.3 per tick (some learning, but distracted)

    Args:
        player: The player object
        person: The person whose learning activities to update
    """
    learning_activity_types = [
        'online_course', 'online_course_free',
        'language_learning', 'language_learning_app',
        'coding_bootcamp', 'coding_bootcamp_parttime',
        'music_lessons', 'music_self_taught',
        'cooking_classes', 'cooking_self_taught'
    ]

    for record in person.activityRecords:
        if record.type in learning_activity_types:
            # Update performance based on focus
            if record.focus == 'Work Hard':
                record.performance = min(100, record.performance + 1)
            elif record.focus == 'Balanced':
                record.performance = min(100, record.performance + 0.5)
            elif record.focus == 'Socialize':
                record.performance = min(100, record.performance + 0.3)
            elif record.focus == 'Slack Off':
                record.performance = min(100, record.performance + 0.1)


__all__ = [
    'onlineCourse',
    'onlineCourseProgress',
    'learnLanguage',
    'languageLearningProgress',
    'codingBootcamp',
    'codingBootcampProgress',
    'musicLessons',
    'musicLessonsProgress',
    'cookingClasses',
    'cookingClassProgress',
    'handleLearningActivities',
]
