"""
Test to verify that set objects are properly serialized to JSON.

This test verifies the fix for the JSON serialization error:
AttributeError: 'set' object has no attribute '__dict__'
"""

import json
import sys
import os

# Add parent directory to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from server.websocket_messaging import ComplexHandler


class MockPlayer:
    """Mock player class with set attributes matching the real playerClass"""
    def __init__(self):
        self.id = "test123"
        self.events = {"event1", "event2", "event3"}  # set
        self.askedQuestions = {"question1", "question2"}  # set
        self.conversations = ["conv1", "conv2"]  # list
        self.name = "Test Player"
        self.energy = 100


def test_set_serialization():
    """Test that sets are properly converted to lists during serialization"""
    player = MockPlayer()

    # This should not raise an AttributeError anymore
    json_str = json.dumps(player.__dict__, default=ComplexHandler)

    # Parse the JSON back
    parsed = json.loads(json_str)

    # Verify that sets were converted to lists
    assert isinstance(parsed['events'], list)
    assert isinstance(parsed['askedQuestions'], list)
    assert isinstance(parsed['conversations'], list)

    # Verify data integrity
    assert set(parsed['events']) == {"event1", "event2", "event3"}
    assert set(parsed['askedQuestions']) == {"question1", "question2"}
    assert parsed['name'] == "Test Player"
    assert parsed['energy'] == 100


def test_nested_objects_with_sets():
    """Test serialization of nested objects that contain sets"""

    class NestedObject:
        def __init__(self):
            self.tags = {"tag1", "tag2"}
            self.name = "Nested"

    class ParentObject:
        def __init__(self):
            self.nested = NestedObject()
            self.own_set = {"a", "b", "c"}

    parent = ParentObject()

    # This should properly serialize nested objects with sets
    json_str = json.dumps(parent.__dict__, default=ComplexHandler)
    parsed = json.loads(json_str)

    # Verify nested set was converted
    assert isinstance(parsed['nested']['tags'], list)
    assert set(parsed['nested']['tags']) == {"tag1", "tag2"}

    # Verify parent set was converted
    assert isinstance(parsed['own_set'], list)
    assert set(parsed['own_set']) == {"a", "b", "c"}


def test_empty_set_serialization():
    """Test that empty sets serialize correctly"""

    class ObjectWithEmptySet:
        def __init__(self):
            self.empty_set = set()
            self.name = "Test"

    obj = ObjectWithEmptySet()
    json_str = json.dumps(obj.__dict__, default=ComplexHandler)
    parsed = json.loads(json_str)

    assert isinstance(parsed['empty_set'], list)
    assert len(parsed['empty_set']) == 0


if __name__ == "__main__":
    test_set_serialization()
    test_nested_objects_with_sets()
    test_empty_set_serialization()
    print("All tests passed!")
