#!/usr/bin/env python
"""
BaoLife Functions Module - Refactored Structure

This module serves as the main entry point and backward compatibility layer
for all game functions. The code has been refactored into logical modules:

- database/ - Database operations and save/load functions
- core/ - Core model classes (playerClass, personClass, etc.)
- character/ - Character creation, management, and appearance
- relationships/ - Relationship management and dating
- education/ - School, college, and extracurricular management
- jobs/ - Occupation and career management
- health/ - Health, habits, and weight management
- stats/ - Stats updates, moods, finances, and event checking
- shop/ - Store items and purchases
- utils/ - Helper functions and game speed validation

For backward compatibility, all functions are re-exported from this module.
"""

import logging
from dayEvents import *
from events import *

# Set up logger
logger = logging.getLogger(__name__)

# ============================================================
# Database Operations
# ============================================================
from database.db_operations import (
    connect_to_database,
    get_database_connection,
    insertGame,
    saveGame,
    saveGameAsync,
    loadGame,
    loadGameAsync,
    loadGames,
    saveConversationMessage,
    markConversationAsRead,
)

# ============================================================
# Core Model Classes
# ============================================================
from core.models import (
    locationClass,
    ActivityRecord,
    EducationRecord,
    dailyEvent,
    playerClass,
    personClass,
    oneTimeEvent,
    scheduleDays,
    scheduler,
    relationshipClass,
)

# ============================================================
# Game Speed Utilities
# ============================================================
from utils.game_speed import (
    validate_game_speed,
    get_speed_button_values,
    log_speed_change,
)

# ============================================================
# General Utilities and Helpers
# ============================================================
from utils.helpers import (
    getFromArray,
    randArray,
    find_by_id,
    find_where,
    findCharacters,
    find,
    find_where_test,
    rand,
    remove_text_before_first_colon,
    ordinal_suffix,
    getWeekDay,
    upcoming_saturday,
    get_season,
    generate_random_date,
    parseLocations,
    getOppositeSex,
    create_jwt_token,
    _unpickle_health_condition,
    _reduce_health_condition,
)

# ============================================================
# Character Management
# ============================================================
from character.character_manager import (
    setBirthday,
    getPersonDescription,
    getOpenAIDescription,
    set_avatar,
    get_lastname,
    get_firstname,
    get_partner,
    add_child,
    get_youngestChild,
    add_parents,
    add_older_siblings,
    add_grandparents,
    add_friend,
    get_random_classmate,
    get_random_friend,
    get_random_character,
    get_random_family,
    get_allFamily,
    create_character,
    create_classmates,
    create_coworkers,
    get_person,
    get_relationship,
    update_relationship,
    updateBio,
    setValues,
    characterSetup,
)

# ============================================================
# Character Appearance
# ============================================================
from character.appearance import (
    get_hair_color,
    get_hair_type,
    get_facial_hair,
    get_accessory,
    get_skin_color,
)

# ============================================================
# Relationship Management
# ============================================================
from relationships.relationship_manager import (
    updateAffinity,
    handleRelationships,
    getRelData,
    romance,
    getActiveRelationship,
    breakUp,
    partnerGift,
    dateNight,
    DateIdea,
    getDateIdeas,
)

# ============================================================
# Education Management
# ============================================================
from education.education_manager import (
    ElementarySchoolClass,
    HighSchoolClass,
    CollegeClass,
    CollegeMajorClass,
    FocusClass,
    ExtraCurricular,
    getSchools,
    getColleges,
    getMajors,
    getFocuses,
    randomFocus,
    update_focus,
    getFocus,
    getExtraCurriculars,
    randomExtraCurricular,
    setEducation,
    handleEducation,
    setExtracurricular,
    applyForExtracurricular,
    quitExtraCurricular,
)

# ============================================================
# Job/Occupation Management
# ============================================================
from jobs.job_manager import (
    JobLevel,
    OccupationClass,
    getOccupations,
    randomJob,
    setJob,
    handleJob,
    applyForJob,
    quitJob,
)

# ============================================================
# Health and Habits Management
# ============================================================
from health.health_manager import (
    HabitClass,
    HealthCondition,
    setHabits,
    quitHabit,
    stopQuitHabit,
    handleHabitChanges,
    getWeightType,
    handleWeight,
    handleHealth,
    handleDeath,
    handleHunger,
    mealEvent,
    updateDeathChance,
    getHealthConditions,
)

# ============================================================
# Stats and State Management
# ============================================================
from stats.stats_manager import (
    connect,
    checkDilemmas,
    checkEvents,
    checkDayEvents,
    checkTutorialEvents,
    scheduleComplete,
    updateAge,
    setLikesDislikes,
    handleUpdates,
    parseOneTimeEvents,
    handleMoods,
    handleFinances,
    getPeakEnergy,
)

# ============================================================
# Shop and Store Management
# ============================================================
from shop.shop_manager import (
    StoreItem,
    InAppPurchaseItem,
    getStoreItems,
    purchaseItem,
    getInAppPurchaseItems,
    purchaseInAppItem,
)

# ============================================================
# Intraday Activity Management
# ============================================================
from intradayActivity import (
    get_dailyPlan,
    getIntradayActivity,
)

# ============================================================
# Push Notifications and Messaging
# ============================================================
import httpx
import random

BUNDLE_ID = "lichun.lichunWebsocket"

async def send_push_notification(device_token, message):
    print("sending push notification for " + device_token + " with message " + message)
    headers = {
        'apns-expiration': '0',
        'apns-priority': '10',
        'apns-topic': BUNDLE_ID,
        'authorization': f'bearer {create_jwt_token()}'
    }
    payload_data = {
        'aps': {
            'alert': message,
            'sound': 'default',
        },
    }
    url = f'https://api.development.push.apple.com/3/device/{device_token}'
    async with httpx.AsyncClient(http2=True) as client:
        resp = await client.post(url, headers=headers, json=payload_data)
        print(resp.status_code, resp.content)
        return resp.status_code, resp.content


async def sendRandomCharacterMessage(player):
    if (random.randint(0,100) == 0):
        from conversationEvents import sendCharacterMessage
        from functions import get_random_character
        character = get_random_character(player)
        await sendCharacterMessage(player,character)
        print("attempting notification")
        await send_push_notification(player.deviceToken, f"New message from {character.firstname} {character.lastname}")

# ============================================================
# Logging and Initialization
# ============================================================

logger.info("Functions module loaded successfully with refactored structure")
logger.debug("All submodules imported: database, core, character, relationships, education, jobs, health, stats, shop, utils")

# Note: The original functions.py was 3116 lines. This refactored version
# is now ~270 lines and provides the same interface through organized submodules.
