"""
Unit tests for BaoLife character creation and management.

Tests character creation, validation, and basic operations.
"""
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))

# Enable test mode to use mock data for database calls
os.environ['BAOLIFE_TEST_MODE'] = 'true'

import pytest
from tests.fixtures.player_fixtures import create_newborn_player, create_adult_player


class TestCharacterCreation:
    """Tests for character creation functions."""

    def test_create_character_basic(self):
        """Test creating a basic character."""
        from functions import create_character

        player = create_adult_player()
        initial_count = len(player.r)

        new_char = create_character(player, sex='Male', age='similar',
                                    relationship='friend')

        assert len(player.r) == initial_count + 1
        assert new_char.sex == 'Male'
        assert 'friend' in new_char.relationships

    def test_create_character_with_pronoun(self):
        """Test that character pronoun matches sex."""
        from functions import personClass

        male = personClass()
        male.sex = 'Male'
        male.setPronoun()

        female = personClass()
        female.sex = 'Female'
        female.setPronoun()

        assert male.pronoun == 'He'
        assert female.pronoun == 'She'

    def test_create_classmates(self):
        """Test creating classmates."""
        from functions import create_classmates

        player = create_adult_player()
        player.r = []  # Clear relationships

        create_classmates(player)

        # Should have created 10 classmates + 1 teacher
        classmates = [r for r in player.r if 'classmate' in r.relationships]
        teachers = [r for r in player.r if 'teacher' in r.relationships]

        assert len(classmates) == 10
        assert len(teachers) == 1

    def test_create_coworkers(self):
        """Test creating coworkers."""
        from functions import create_coworkers

        player = create_adult_player()
        player.r = []  # Clear relationships

        # Create a dummy occupation
        from types import SimpleNamespace
        occupation = SimpleNamespace(title='Test Job')

        create_coworkers(player, occupation)

        # Should have created 5-8 coworkers + 1 boss
        coworkers = [r for r in player.r if 'coworker' in r.relationships]
        bosses = [r for r in player.r if 'boss' in r.relationships]

        assert 5 <= len(coworkers) <= 8
        assert len(bosses) == 1

    def test_character_age_similar(self):
        """Test creating character with similar age."""
        from functions import create_character

        player = create_adult_player(age_years=25)

        new_char = create_character(player, age='similar', relationship='friend')

        # Age should be within 1 year
        assert 24 <= new_char.ageYears <= 26


class TestPersonClass:
    """Tests for personClass."""

    def test_person_default_values(self):
        """Test that personClass has correct default values."""
        from functions import personClass

        person = personClass()

        assert person.status == "alive"
        assert person.energy == 100
        assert person.hunger == 0
        assert person.thirst == 0
        assert person.health == 1
        assert isinstance(person.relationships, list)

    def test_person_has_required_attributes(self):
        """Test that person has all required attributes."""
        from functions import personClass

        person = personClass()

        required_attrs = [
            'id', 'firstname', 'lastname', 'sex', 'pronoun',
            'ageYears', 'ageDays', 'energy', 'money', 'status'
        ]

        for attr in required_attrs:
            assert hasattr(person, attr), f"Missing attribute: {attr}"


class TestLocationManagement:
    """Tests for location management."""

    def test_parse_locations_basic(self):
        """Test parsing locations."""
        from functions import parseLocations, locationClass

        player = create_adult_player()

        # Add a location
        home = locationClass('home', 'house')
        player.l.append(home)

        # Set player at home
        player.c.location = 'home'

        player = parseLocations(player)

        # Player should be in the home location
        assert player.c.id in player.l[0].people

    def test_parse_locations_with_relationships(self):
        """Test that people at same location increase familiarity."""
        from functions import parseLocations, locationClass, personClass

        player = create_adult_player()

        # Add a location
        home = locationClass('home', 'house')
        player.l.append(home)

        # Add a friend
        friend = personClass()
        friend.location = 'home'
        friend.familiarity = 50
        player.r.append(friend)

        # Set player at home
        player.c.location = 'home'

        player = parseLocations(player)

        # Friend's familiarity should have increased
        assert player.r[0].familiarity == 60  # +10 from being together


class TestRelationshipManagement:
    """Tests for relationship management functions."""

    def test_update_relationship_type(self):
        """Test updating relationship type."""
        from functions import update_relationship, personClass

        player = create_adult_player()

        # Add a dating partner
        partner = personClass()
        partner.relationships = ['dating']
        partner.title = 'Partner'
        player.r.append(partner)

        # This test would need the actual update_relationship function to work correctly
        # For now, we'll just verify the function exists
        assert hasattr(player, 'r')
        assert len(player.r) > 0


class TestCharacterValidation:
    """Tests for character data validation."""

    def test_character_age_bounds(self):
        """Test that character ages are within valid bounds."""
        player = create_newborn_player()

        assert 0 <= player.c.ageYears <= 120
        assert player.c.ageDays >= 0

    def test_character_stat_bounds(self):
        """Test that character stats are within valid bounds."""
        player = create_adult_player()

        assert 0 <= player.c.energy <= 100
        assert 0 <= player.c.hunger <= 200  # Can exceed 100
        assert 0 <= player.c.happiness <= 100
        assert player.c.money >= 0
