"""
Hobbies & Personal Development Activity Events
Personal growth, hobbies, and self-improvement activities

Events:
- gardening: Starting a garden (ages 20-100) - Uses ActivityRecord to track plants grown
- meditation: Beginning a meditation practice (ages 14-100) - Uses Habit system for daily practice
- birdWatching: Taking up birdwatching (ages 30-100) - Uses ActivityRecord to track species spotted
- collectionHobby: Starting a collection hobby (ages 8-100) - Uses ActivityRecord to track collection
- readingChallenge: Challenging yourself to read more books (ages 10-100) - Uses ActivityRecord to track books read

Integration:
- Meditation uses HabitClass for daily practice tracking
- Collections, gardening, reading use ActivityRecord for progress tracking
- Achievement integration for milestones
- Follow-up events for hobby progress updates
"""

import random
import uuid
from events.base import messageFunction, questionFunction, answerOption
from health.health_manager import HabitClass
from core.models import ActivityRecord


def gardening(player, type='message', message=False, response=False):
    """Starting a garden - Creates ActivityRecord to track garden progress"""
    fname = 'gardening'
    check = fname not in player.askedQuestions and player.c.ageYears >= 20 and player.c.ageYears <= 100 and 1 >= random.random()*5000
    message = "You want to start a garden. Begin?"

    if type != 'answer':
        answerOptions = [
            answerOption("Yes, full vegetable garden!", "vegetable", energyCost=15, moneyCost=100),
            answerOption("Small herb garden", "herb", moneyCost=30),
            answerOption("Just houseplants", "houseplants", moneyCost=20),
            answerOption("Not interested", "no")
        ]
        return questionFunction(fname, message, player, check, answerOptions)

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

        if response['data'] == 'vegetable':
            player.c.happiness += 25
            player.c.energy -= 15
            player.c.money -= 100
            player.c.stress -= 15

            # Create gardening activity with ActivityRecord
            garden_id = f"gardening_{uuid.uuid4().hex[:8]}"
            garden_activity = type('Activity', (), {
                'id': garden_id,
                'type': 'hobby',
                'title': 'Vegetable Garden',
                'description': 'Growing vegetables at home'
            })()

            player.c.activities.append(garden_activity)
            garden_record = ActivityRecord(garden_id, 'hobby', player.date)
            garden_record.performance = 50  # Starting performance
            garden_record.focus = 'vegetable_garden'
            garden_record.achievements = []
            player.c.activityRecords.append(garden_record)

            # Create recurring gardening schedule (2x per week)
            player.c.schedules.append(scheduler(
                player.c,
                "Gardening",
                ["twice-week", "morning"],
                location="home" + player.c.id,
                duration=random.randint(10, 15)
            ))

            # Add follow-up event for first harvest
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="First Harvest",
                    message="Your vegetable garden is thriving! You harvest your first homegrown tomatoes, lettuce, and herbs. Nothing tastes quite like vegetables you grew yourself!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=60,
                    completionFunc=None
                )
            )

            player.messageQueue.append("You've started a full vegetable garden! It will require regular care, but the fresh produce will be worth it.")

        elif response['data'] == 'herb':
            player.c.happiness += 15
            player.c.money -= 30
            player.c.stress -= 10

            # Create simple herb garden activity
            herb_id = f"herb_garden_{uuid.uuid4().hex[:8]}"
            herb_activity = type('Activity', (), {
                'id': herb_id,
                'type': 'hobby',
                'title': 'Herb Garden',
                'description': 'Growing herbs on windowsill'
            })()

            player.c.activities.append(herb_activity)
            herb_record = ActivityRecord(herb_id, 'hobby', player.date)
            herb_record.performance = 60
            herb_record.focus = 'herb_garden'
            player.c.activityRecords.append(herb_record)

            player.messageQueue.append("You've planted a small herb garden on your windowsill. Fresh basil and rosemary at your fingertips!")

        elif response['data'] == 'houseplants':
            player.c.happiness += 10
            player.c.money -= 20
            player.c.stress -= 5
            player.messageQueue.append("You've brought home some beautiful houseplants. They brighten up your living space nicely.")

        else:  # not interested
            player.c.happiness -= 5
            player.messageQueue.append("You decide gardening isn't for you right now.")


def meditation(player, type='message', message=False, response=False):
    """Beginning a meditation practice - Uses Habit system for daily practice tracking"""
    fname = 'meditation'
    check = fname not in player.askedQuestions and player.c.ageYears >= 14 and player.c.ageYears <= 100 and 1 >= random.random()*5000
    message = "You want to start meditating daily. Begin a practice?"

    if type != 'answer':
        answerOptions = [
            answerOption("Yes, meditate daily!", "daily"),
            answerOption("Try occasionally", "occasional"),
            answerOption("Use meditation app", "app", moneyCost=10),
            answerOption("Not for me", "no")
        ]
        return questionFunction(fname, message, player, check, answerOptions)

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

        if response['data'] == 'daily':
            player.c.stress -= 30
            player.c.happiness += 20
            player.c.health += 5

            # Add meditation as a positive habit
            meditation_habit = HabitClass(
                name="meditation",
                description="You meditate daily, bringing peace and clarity to your mind.",
                habitType="positive"
            )

            # Check if habit doesn't already exist
            if not any(h.name == "meditation" for h in player.c.habits):
                player.c.habits.append(meditation_habit)

            # Create daily meditation schedule
            player.c.schedules.append(scheduler(
                player.c,
                "Daily meditation",
                ["daily", "morning"],
                location="home" + player.c.id,
                duration=random.randint(5, 10)
            ))

            # Add follow-up event for meditation milestone
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Meditation Milestone",
                    message="You've been meditating consistently for 30 days! You notice you're calmer, more focused, and better at managing stress. The practice has become an essential part of your routine.",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=30,
                    completionFunc=None
                )
            )

            player.messageQueue.append("You've committed to daily meditation. The practice brings you peace and clarity each morning.")

        elif response['data'] == 'occasional':
            player.c.stress -= 15
            player.c.happiness += 10
            player.messageQueue.append("You try meditating when you remember. Even occasional practice helps calm your mind.")

        elif response['data'] == 'app':
            player.c.money -= 10
            player.c.stress -= 25
            player.c.happiness += 15
            player.c.health += 5

            # Add meditation app habit (still positive but slightly different)
            app_habit = HabitClass(
                name="meditation_app",
                description="You use a meditation app for guided sessions.",
                habitType="positive"
            )

            if not any(h.name == "meditation_app" for h in player.c.habits):
                player.c.habits.append(app_habit)

            # Create daily meditation schedule
            player.c.schedules.append(scheduler(
                player.c,
                "Guided meditation",
                ["daily", "morning"],
                location="home" + player.c.id,
                duration=random.randint(10, 15)
            ))

            player.messageQueue.append("You've subscribed to a meditation app. The guided sessions make it easy to build a consistent practice.")

        else:  # not for me
            player.c.happiness -= 5
            player.messageQueue.append("You decide meditation isn't your thing.")


def birdWatching(player, type='message', message=False, response=False):
    """Taking up birdwatching - Uses ActivityRecord to track species spotted"""
    fname = 'birdWatching'
    check = fname not in player.askedQuestions and player.c.ageYears >= 30 and player.c.ageYears <= 100 and 1 >= random.random()*5000
    message = "You're interested in birdwatching. Start?"

    if type != 'answer':
        answerOptions = [
            answerOption("Yes, buy binoculars!", "binoculars", moneyCost=100),
            answerOption("Use what I have", "basic"),
            answerOption("Join birdwatching group", "group", moneyCost=50),
            answerOption("Not interested", "no")
        ]
        return questionFunction(fname, message, player, check, answerOptions)

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

        if response['data'] == 'binoculars':
            player.c.money -= 100
            player.c.happiness += 20
            player.c.stress -= 15

            # Create birdwatching activity with ActivityRecord
            birding_id = f"birdwatching_{uuid.uuid4().hex[:8]}"
            birding_activity = type('Activity', (), {
                'id': birding_id,
                'type': 'hobby',
                'title': 'Birdwatching',
                'description': 'Observing and identifying bird species'
            })()

            player.c.activities.append(birding_activity)
            birding_record = ActivityRecord(birding_id, 'hobby', player.date)
            birding_record.performance = 10  # Species spotted counter starts at 10
            birding_record.focus = 'serious_birder'
            birding_record.achievements = []
            player.c.activityRecords.append(birding_record)

            # Create weekend birdwatching schedule
            player.c.schedules.append(scheduler(
                player.c,
                "Birdwatching",
                ["weekend", "morning"],
                location="park" + player.c.id,
                duration=random.randint(20, 40)
            ))

            # Add follow-up event for first rare sighting
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Rare Bird Sighting",
                    message="You spotted a rare bird species through your binoculars! You carefully note it in your bird journal. Your hobby is becoming quite rewarding!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=45,
                    completionFunc=None
                )
            )

            player.messageQueue.append("You've invested in quality binoculars! You can't wait to identify all the birds in your area.")

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

            # Create basic birdwatching activity
            birding_id = f"birdwatching_{uuid.uuid4().hex[:8]}"
            birding_activity = type('Activity', (), {
                'id': birding_id,
                'type': 'hobby',
                'title': 'Birdwatching',
                'description': 'Casual bird observation'
            })()

            player.c.activities.append(birding_activity)
            birding_record = ActivityRecord(birding_id, 'hobby', player.date)
            birding_record.performance = 5  # Fewer species spotted
            birding_record.focus = 'casual_birder'
            player.c.activityRecords.append(birding_record)

            player.messageQueue.append("You start birdwatching with what you have. It's peaceful watching nature from your backyard.")

        elif response['data'] == 'group':
            player.c.money -= 50
            player.c.happiness += 25
            player.c.social += 20
            player.c.stress -= 15

            # Create social birdwatching activity
            birding_id = f"birdwatching_{uuid.uuid4().hex[:8]}"
            birding_activity = type('Activity', (), {
                'id': birding_id,
                'type': 'hobby',
                'title': 'Birdwatching Club',
                'description': 'Birding with a local group'
            })()

            player.c.activities.append(birding_activity)
            birding_record = ActivityRecord(birding_id, 'hobby', player.date)
            birding_record.performance = 15  # Group helps you spot more species
            birding_record.focus = 'social_birder'
            birding_record.achievements = []
            player.c.activityRecords.append(birding_record)

            # Create group birdwatching schedule
            player.c.schedules.append(scheduler(
                player.c,
                "Birdwatching Club",
                ["weekly", "morning", "weekend"],
                location="park" + player.c.id,
                duration=random.randint(30, 60)
            ))

            player.messageQueue.append("You've joined a local birdwatching group! You make new friends who share your appreciation for nature.")

        else:  # not interested
            player.c.happiness -= 5
            player.messageQueue.append("You decide birdwatching isn't for you.")


def collectionHobby(player, type='message', message=False, response=False):
    """Starting a collection hobby - Uses ActivityRecord to track collection size and value"""
    fname = 'collectionHobby'
    check = fname not in player.askedQuestions and player.c.ageYears >= 8 and player.c.ageYears <= 100 and 1 >= random.random()*5000

    # Age-appropriate collection types
    if player.c.ageYears < 12:
        collection_type = random.choice(["rocks", "stickers", "trading cards"])
    elif player.c.ageYears < 18:
        collection_type = random.choice(["trading cards", "vinyl records", "vintage posters"])
    else:
        collection_type = random.choice(["coins", "stamps", "vintage items", "art prints", "vinyl records"])

    message = f"You want to start collecting {collection_type}. Begin?"

    if type != 'answer':
        # Store collection type in the question for later retrieval
        answerOptions = [
            answerOption("Yes, start collection!", "serious", moneyCost=50),
            answerOption("Casual collecting", "casual", moneyCost=20),
            answerOption("Join collector community", "community", moneyCost=75),
            answerOption("Not interested", "no")
        ]
        # Store collection_type in a way that can be retrieved in answer phase
        question_result = questionFunction(fname, message, player, check, answerOptions)
        if question_result and check:
            # Store collection type as a temporary attribute (will be used in answer phase)
            player.c.temp_collection_type = collection_type
        return question_result

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

        # Retrieve collection type (fallback to a default if not found)
        collection_type = getattr(player.c, 'temp_collection_type', 'collectibles')

        if response['data'] == 'serious':
            player.c.money -= 50
            player.c.happiness += 20
            player.c.prestige += 5

            # Create collection activity with ActivityRecord
            collection_id = f"collection_{uuid.uuid4().hex[:8]}"
            collection_activity = type('Activity', (), {
                'id': collection_id,
                'type': 'hobby',
                'title': f'{collection_type.title()} Collection',
                'description': f'Collecting {collection_type}'
            })()

            player.c.activities.append(collection_activity)
            collection_record = ActivityRecord(collection_id, 'hobby', player.date)
            collection_record.performance = 10  # Items in collection
            collection_record.focus = f'{collection_type}_serious'
            collection_record.achievements = []
            player.c.activityRecords.append(collection_record)

            # Add follow-up event for rare find
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Rare Collection Find",
                    message=f"You found an incredibly rare piece for your {collection_type} collection! It's worth significantly more than what you paid. Your collection is really coming together!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=90,
                    completionFunc=None
                )
            )

            player.messageQueue.append(f"You've started your {collection_type} collection! You love the thrill of finding rare pieces.")

        elif response['data'] == 'casual':
            player.c.money -= 20
            player.c.happiness += 15

            # Create casual collection activity
            collection_id = f"collection_{uuid.uuid4().hex[:8]}"
            collection_activity = type('Activity', (), {
                'id': collection_id,
                'type': 'hobby',
                'title': f'{collection_type.title()} Collection',
                'description': f'Casually collecting {collection_type}'
            })()

            player.c.activities.append(collection_activity)
            collection_record = ActivityRecord(collection_id, 'hobby', player.date)
            collection_record.performance = 5  # Smaller collection
            collection_record.focus = f'{collection_type}_casual'
            player.c.activityRecords.append(collection_record)

            player.messageQueue.append(f"You casually pick up {collection_type} when you find interesting ones. It's a fun, low-pressure hobby.")

        elif response['data'] == 'community':
            player.c.money -= 75
            player.c.happiness += 25
            player.c.social += 15
            player.c.prestige += 10

            # Create community-based collection activity
            collection_id = f"collection_{uuid.uuid4().hex[:8]}"
            collection_activity = type('Activity', (), {
                'id': collection_id,
                'type': 'hobby',
                'title': f'{collection_type.title()} Collector Community',
                'description': f'Collecting {collection_type} with a community'
            })()

            player.c.activities.append(collection_activity)
            collection_record = ActivityRecord(collection_id, 'hobby', player.date)
            collection_record.performance = 15  # Community helps expand collection
            collection_record.focus = f'{collection_type}_community'
            collection_record.achievements = []
            player.c.activityRecords.append(collection_record)

            # Add follow-up event for collection showcase
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Collection Showcase",
                    message=f"You showcased your {collection_type} collection at a community event! Fellow collectors were impressed with your curated pieces. You've made valuable connections!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=120,
                    completionFunc=None
                )
            )

            player.messageQueue.append(f"You've joined a collector community! You meet fellow enthusiasts and learn so much about {collection_type}.")

        else:  # not interested
            player.c.happiness -= 5
            player.messageQueue.append("You decide collecting isn't for you right now.")

        # Clean up temporary attribute
        if hasattr(player.c, 'temp_collection_type'):
            delattr(player.c, 'temp_collection_type')


def readingChallenge(player, type='message', message=False, response=False):
    """Challenging yourself to read more books - Uses ActivityRecord to track books read"""
    fname = 'readingChallenge'
    check = fname not in player.askedQuestions and player.c.ageYears >= 10 and player.c.ageYears <= 100 and 1 >= random.random()*5000
    message = "Challenge yourself to read 50 books this year?"

    if type != 'answer':
        answerOptions = [
            answerOption("Yes, 50 books!", "fifty"),
            answerOption("More realistic: 20 books", "twenty"),
            answerOption("Just read for fun", "casual"),
            answerOption("Not a reader", "no")
        ]
        return questionFunction(fname, message, player, check, answerOptions)

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

        if response['data'] == 'fifty':
            player.c.intelligence += 30
            player.c.happiness += 20
            player.c.stress -= 10

            # Create reading challenge activity with ActivityRecord
            reading_id = f"reading_{uuid.uuid4().hex[:8]}"
            reading_activity = type('Activity', (), {
                'id': reading_id,
                'type': 'hobby',
                'title': 'Reading Challenge: 50 Books',
                'description': 'Reading 50 books this year'
            })()

            player.c.activities.append(reading_activity)
            reading_record = ActivityRecord(reading_id, 'hobby', player.date)
            reading_record.performance = 0  # Books read so far
            reading_record.focus = 'ambitious_reader'
            reading_record.achievements = []
            player.c.activityRecords.append(reading_record)

            # Add reading habit as a positive habit
            reading_habit = HabitClass(
                name="daily_reading",
                description="You read every day, working towards your ambitious reading goal.",
                habitType="positive"
            )

            if not any(h.name == "daily_reading" for h in player.c.habits):
                player.c.habits.append(reading_habit)

            # Create daily reading schedule
            player.c.schedules.append(scheduler(
                player.c,
                "Reading time",
                ["daily", "evening"],
                location="home" + player.c.id,
                duration=random.randint(30, 60)
            ))

            # Create multiple check-in events throughout the year
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Reading Challenge: Quarter Mark",
                    message="You've been reading consistently for 3 months! You're making great progress toward your 50-book goal. Keep it up!",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=90,
                    completionFunc=None
                )
            )

            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Reading Challenge: Halfway There",
                    message="You're halfway through the year! Your reading habit has become a cherished part of your daily routine. The books you've read have opened your mind to new ideas and perspectives.",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=180,
                    completionFunc=None
                )
            )

            player.messageQueue.append("You've committed to reading 50 books this year! An ambitious goal that will expand your mind.")

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

            # Create moderate reading challenge activity
            reading_id = f"reading_{uuid.uuid4().hex[:8]}"
            reading_activity = type('Activity', (), {
                'id': reading_id,
                'type': 'hobby',
                'title': 'Reading Challenge: 20 Books',
                'description': 'Reading 20 books this year'
            })()

            player.c.activities.append(reading_activity)
            reading_record = ActivityRecord(reading_id, 'hobby', player.date)
            reading_record.performance = 0  # Books read so far
            reading_record.focus = 'moderate_reader'
            reading_record.achievements = []
            player.c.activityRecords.append(reading_record)

            # Add reading habit
            reading_habit = HabitClass(
                name="regular_reading",
                description="You read regularly, enjoying books at a comfortable pace.",
                habitType="positive"
            )

            if not any(h.name == "regular_reading" for h in player.c.habits):
                player.c.habits.append(reading_habit)

            # Create reading schedule (few times per week)
            player.c.schedules.append(scheduler(
                player.c,
                "Reading time",
                ["thrice-week", "evening"],
                location="home" + player.c.id,
                duration=random.randint(20, 40)
            ))

            # Add check-in event
            player.c.oneTimeEvents.append(
                oneTimeEvent(
                    title="Reading Challenge Check-in",
                    message="You've been keeping up with your reading goal! The books you've read have enriched your life in unexpected ways.",
                    date=player.date,
                    dateType="daysFromNow",
                    dateModifier=120,
                    completionFunc=None
                )
            )

            player.messageQueue.append("You've set a goal to read 20 books this year. A realistic target that will still enrich your life.")

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

            # Create casual reading activity (no strict tracking)
            reading_id = f"reading_{uuid.uuid4().hex[:8]}"
            reading_activity = type('Activity', (), {
                'id': reading_id,
                'type': 'hobby',
                'title': 'Casual Reading',
                'description': 'Reading for pleasure without pressure'
            })()

            player.c.activities.append(reading_activity)
            reading_record = ActivityRecord(reading_id, 'hobby', player.date)
            reading_record.performance = 0
            reading_record.focus = 'casual_reader'
            player.c.activityRecords.append(reading_record)

            player.messageQueue.append("You decide to read casually without pressure. Sometimes the best reading happens when it's purely for enjoyment.")

        else:  # not a reader
            player.c.happiness -= 5
            player.messageQueue.append("Reading just isn't your thing.")


__all__ = [
    'gardening',
    'meditation',
    'birdWatching',
    'collectionHobby',
    'readingChallenge',
]
