"""
Creative & Artistic Activity Events
Activities for creative expression and artistic pursuits (ages 8-100)

Events:
- learnPainting: Learning to paint
- writingJournal: Starting a daily journaling habit
- learnPhotography: Getting into photography
- theatreAudition: Auditioning for theater
- craftingHobby: Starting a crafting hobby
"""

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


def learnPainting(player, type='message', message=False, response=False):
    """Learning to paint"""
    from functions import scheduler, ExtraCurricular, ActivityRecord

    fname = 'learnPainting'

    # Check if player already has an art-related activity
    hasArtActivity = any(
        activity.title in ['Art Club', 'Painting Class']
        for activity in player.c.activities
        if hasattr(activity, 'title')
    )

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

    message = "You're interested in learning to paint. Take a class?"
    answerOptions = [
        answerOption('Yes, art classes!', data='classes', moneyCost=75),
        answerOption('Teach myself online', data='online'),
        answerOption('Buy supplies and experiment', data='experiment', moneyCost=30),
        answerOption('Maybe later', data='no')
    ]
    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['data'] == 'classes'):
            if player.c.money < 75:
                player.messageQueue.append("You don't have enough money for art classes right now.")
                return
            player.c.money -= 75
            # Create formal painting class activity
            paintingClass = ExtraCurricular(
                'Painting Class',
                'Balanced',
                'Learn painting techniques with an instructor',
                15
            )
            player.c.activities.append(paintingClass)
            player.c.activityRecords.append(
                ActivityRecord(paintingClass.id, paintingClass.type, player.date)
            )
            # Add weekly schedule
            player.c.schedules.append(
                scheduler(
                    player.c,
                    "Painting Class",
                    ["weekly", "afternoon"],
                    location="artstudio" + player.c.id,
                    duration=random.randint(60, 90)
                )
            )
            player.messageQueue.append("You enrolled in art classes! The instructor is patient and your skills are improving steadily.")
            player.c.creativity += 20
            player.c.happiness += 15
        elif (response['data'] == 'online'):
            # Add personal painting schedule (less formal)
            player.c.schedules.append(
                scheduler(
                    player.c,
                    "Painting Practice",
                    ["twice-week", "evening"],
                    location="home" + player.c.id,
                    duration=random.randint(30, 60)
                )
            )
            player.messageQueue.append("You found some great online tutorials and started practicing at home. It's fun learning at your own pace!")
            player.c.creativity += 10
            player.c.happiness += 10
        elif (response['data'] == 'experiment'):
            if player.c.money < 30:
                player.messageQueue.append("You don't have enough money for art supplies right now.")
                return
            player.c.money -= 30
            player.messageQueue.append("You bought paints, brushes, and canvases. Time to experiment and see what happens!")
            player.c.creativity += 15
            player.c.happiness += 5
        elif (response['data'] == 'no'):
            player.messageQueue.append("Maybe another time. You put the idea aside for now.")
            player.c.happiness -= 5


def writingJournal(player, type='message', message=False, response=False):
    """Starting a daily journaling habit"""
    from functions import scheduler

    fname = 'writingJournal'

    # Check if player already journals (different from Writing Club)
    hasJournalingSchedule = any(
        schedule.title == "Journal writing"
        for schedule in player.c.schedules
    )

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

    message = "You want to start writing in a journal. Begin?"
    answerOptions = [
        answerOption('Yes, write daily', data='daily'),
        answerOption('Write occasionally', data='occasional'),
        answerOption('No, too personal', data='no')
    ]
    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['data'] == 'daily'):
            player.messageQueue.append("You commit to writing every day. It becomes a peaceful ritual where you can process your thoughts and feelings.")
            player.c.happiness += 15
            player.c.intelligence += 10
            player.c.stress -= 15
            # Create a daily habit/schedule for journaling
            player.c.schedules.append(
                scheduler(
                    player.c,
                    "Journal writing",
                    ["daily", "evening"],
                    location="home" + player.c.id,
                    duration=random.randint(15, 30)
                )
            )
        elif (response['data'] == 'occasional'):
            player.messageQueue.append("You write in your journal when the mood strikes. It's nice to have an outlet for your thoughts.")
            player.c.happiness += 10
            player.c.stress -= 5
        elif (response['data'] == 'no'):
            player.messageQueue.append("You decide journaling isn't for you. It feels too vulnerable.")
            player.c.happiness -= 5


def learnPhotography(player, type='message', message=False, response=False):
    """Getting into photography"""
    from functions import scheduler, ExtraCurricular, ActivityRecord

    fname = 'learnPhotography'

    # Check if player already has a photography activity
    hasPhotographyActivity = any(
        activity.title in ['Photography Class', 'Photography Club']
        for activity in player.c.activities
        if hasattr(activity, 'title')
    )

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

    message = "You're interested in photography. Pursue it?"
    answerOptions = [
        answerOption('Buy a camera and take classes', data='classes', moneyCost=500),
        answerOption('Use phone camera and learn online', data='online'),
        answerOption('Just take casual photos', data='casual'),
        answerOption('Not interested', data='no')
    ]
    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['data'] == 'classes'):
            if player.c.money < 500:
                player.messageQueue.append("You don't have enough money for a camera and photography classes right now.")
                return
            player.c.money -= 500
            # Create formal photography class activity
            photographyClass = ExtraCurricular(
                'Photography Class',
                'Balanced',
                'Learn composition, lighting, and editing techniques',
                15
            )
            player.c.activities.append(photographyClass)
            player.c.activityRecords.append(
                ActivityRecord(photographyClass.id, photographyClass.type, player.date)
            )
            # Add weekly schedule
            player.c.schedules.append(
                scheduler(
                    player.c,
                    "Photography Class",
                    ["weekly", "evening"],
                    location="artstudio" + player.c.id,
                    duration=random.randint(90, 120)
                )
            )
            player.messageQueue.append("You invested in a nice camera and signed up for photography classes. Your instructor teaches you composition, lighting, and editing. You're seeing the world through a new lens!")
            player.c.creativity += 25
            player.c.happiness += 20
        elif (response['data'] == 'online'):
            # Add photography practice schedule
            player.c.schedules.append(
                scheduler(
                    player.c,
                    "Photography Practice",
                    ["twice-week", "afternoon"],
                    location="outside" + player.c.id,
                    duration=random.randint(60, 90)
                )
            )
            player.messageQueue.append("You started taking photos with your phone and learning techniques online. Modern phones are amazing cameras, and you're learning fast!")
            player.c.creativity += 15
            player.c.happiness += 15
        elif (response['data'] == 'casual'):
            player.messageQueue.append("You snap photos here and there when something catches your eye. Nothing serious, just for fun.")
            player.c.creativity += 5
            player.c.happiness += 5
        elif (response['data'] == 'no'):
            player.messageQueue.append("Photography isn't really your thing. You pass on the opportunity.")
            player.c.happiness -= 5


def theatreAudition(player, type='message', message=False, response=False):
    """Auditioning for theater"""
    from functions import scheduler, setExtracurricular, find_where

    fname = 'theatreAudition'

    # Check if player already has Musical Theater extracurricular
    hasTheaterActivity = any(
        activity.title in ['Musical Theater', 'Theater Club', 'Drama Club']
        for activity in player.c.activities
        if hasattr(activity, 'title')
    )

    check = (fname not in player.askedQuestions and
             player.c.ageYears >= 10 and
             player.c.ageYears <= 22 and
             player.c.occupation == 'student' and
             not hasTheaterActivity and
             1 >= random.random() * 900)

    message = "Your school/community theater is holding auditions. Try out?"
    answerOptions = [
        answerOption('Audition for lead role!', data='lead', energyCost=20),
        answerOption('Audition for any role', data='any'),
        answerOption('Help with crew/backstage', data='crew'),
        answerOption('Skip it', data='no')
    ]
    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['data'] == 'lead'):
            if player.c.energy < 20:
                player.messageQueue.append("You're too tired to give your best audition right now.")
                return
            player.c.energy -= 20
            # Try to find existing Musical Theater extracurricular
            musicalTheater = find_where(player.extraCurriculars, 'title', 'Musical Theater')
            if musicalTheater:
                # Add player to Musical Theater extracurricular
                setExtracurricular(player.c, musicalTheater, player.date)
                # Modify performance based on lead role audition
                for record in player.c.activityRecords:
                    if record.id == musicalTheater.id:
                        record.performance = 70  # Higher starting performance for lead audition
            player.messageQueue.append("You went all out for the lead role! You prepared a monologue and gave it your best shot. You got into the theater program!")
            player.c.social += 20
            player.c.creativity += 15
            player.c.happiness += 20
        elif (response['data'] == 'any'):
            # Try to find existing Musical Theater extracurricular
            musicalTheater = find_where(player.extraCurriculars, 'title', 'Musical Theater')
            if musicalTheater:
                setExtracurricular(player.c, musicalTheater, player.date)
            player.messageQueue.append("You auditioned and said you'd be happy with any role. The director appreciated your flexibility and enthusiasm! You got into the theater program!")
            player.c.social += 15
            player.c.creativity += 10
            player.c.happiness += 15
        elif (response['data'] == 'crew'):
            # Add a schedule for helping with theater crew (no extracurricular)
            player.c.schedules.append(
                scheduler(
                    player.c,
                    "Theater Crew",
                    ["twice-week", "afternoon"],
                    location="school" + player.c.id,
                    duration=random.randint(60, 90)
                )
            )
            player.messageQueue.append("You joined the crew working on sets, costumes, or lighting. It's fascinating to see the behind-the-scenes work that makes theater magic!")
            player.c.social += 10
            player.c.creativity += 5
            player.c.happiness += 10
        elif (response['data'] == 'no'):
            player.messageQueue.append("You decided theater isn't for you and skipped the auditions.")
            player.c.happiness -= 10


def craftingHobby(player, type='message', message=False, response=False):
    """Starting a crafting hobby"""
    from functions import scheduler

    fname = 'craftingHobby'

    # Check if player already has a crafting schedule
    hasCraftingSchedule = any(
        'Craft' in schedule.title or 'Knitting' in schedule.title or 'Woodworking' in schedule.title
        for schedule in player.c.schedules
    )

    # Age-appropriate craft type
    if player.c.ageYears < 14:
        craft_type = random.choice(["arts and crafts", "origami", "friendship bracelets"])
    elif player.c.ageYears < 30:
        craft_type = random.choice(["knitting", "painting miniatures", "jewelry making"])
    else:
        craft_type = random.choice(["knitting", "woodworking", "pottery", "quilting"])

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

    message = f"You want to start a crafting hobby ({craft_type}). Begin?"
    answerOptions = [
        answerOption('Yes, buy supplies!', data='supplies', moneyCost=50),
        answerOption('Start small with basics', data='basics', moneyCost=20),
        answerOption('Not interested', data='no')
    ]
    if (type != 'answer'):
        return questionFunction(fname, message, player, check, answerOptions)
    elif (type == 'answer'):
        if (response['data'] == 'supplies'):
            if player.c.money < 50:
                player.messageQueue.append("You don't have enough money for craft supplies right now.")
                return
            player.c.money -= 50
            # Create regular crafting schedule
            player.c.schedules.append(
                scheduler(
                    player.c,
                    f"{craft_type.title()} Hobby",
                    ["twice-week", "evening"],
                    location="home" + player.c.id,
                    duration=random.randint(60, 120)
                )
            )
            player.messageQueue.append(f"You went to the craft store and bought everything you needed for {craft_type}! Your first project is already underway. There's something deeply satisfying about making things with your own hands.")
            player.c.creativity += 15
            player.c.happiness += 20
            player.c.stress -= 10
        elif (response['data'] == 'basics'):
            if player.c.money < 20:
                player.messageQueue.append("You don't have enough money for basic craft supplies right now.")
                return
            player.c.money -= 20
            # Create occasional crafting schedule
            player.c.schedules.append(
                scheduler(
                    player.c,
                    f"{craft_type.title()} Hobby",
                    ["weekly", "evening"],
                    location="home" + player.c.id,
                    duration=random.randint(45, 60)
                )
            )
            player.messageQueue.append(f"You started with a beginner's kit and basic supplies for {craft_type}. It's a modest beginning, but you're enjoying learning a new skill!")
            player.c.creativity += 10
            player.c.happiness += 15
            player.c.stress -= 5
        elif (response['data'] == 'no'):
            player.messageQueue.append("Crafting doesn't appeal to you right now. You decide to skip it.")
            player.c.happiness -= 5


__all__ = [
    'learnPainting',
    'writingJournal',
    'learnPhotography',
    'theatreAudition',
    'craftingHobby',
]
