#!/usr/bin/env python3
"""
The Gateway — A room that bridges to another Evennia world.

When a character enters this room, they can travel to another world.
Their state is exported, and they appear in the destination world.
"""
from evennia import DefaultRoom, DefaultExit

class GatewayRoom(DefaultRoom):
    """
    A room that bridges to another Evennia world.
    
    Properties:
        destination_url: URL of the remote Evennia world (e.g., http://vps:4001)
        destination_room: Name of the room in the destination world
        is_portal: True if this room is a portal room
    
    Usage:
        In game: /set destination_url = "http://143.198.27.163:4001"
        In game: /set destination_room = "Gatehouse"
    """
    
    def at_object_creation(self):
        super().at_object_creation()
        self.db.destination_url = ""
        self.db.destination_room = ""
        self.db.is_portal = True
        self.db.bridge_active = False
        self.db.last_sync = None
        self.db.visitors = []  # Characters currently visiting from other worlds
        self.db.sync_state = {}  # Last known state from remote world
    
    def at_object_receive(self, arrived_obj, source_location):
        """Called when something arrives in this room."""
        super().at_object_receive(arrived_obj, source_location)
        
        # Check if this is a visitor from another world
        if arrived_obj.db and arrived_obj.db.home_world:
            # Mark as visitor
            arrived_obj.db.is_visitor = True
            arrived_obj.db.visit_from = arrived_obj.db.home_world
            self.msg(f"{arrived_obj.key} arrives from another world, looking around with curious eyes.")
        else:
            # Local resident entering
            self.msg(f"{arrived_obj.key} enters the Gateway. The air hums with possibility.")
    
    def at_char_arrive(self, character):
        """Handle character arriving in the gateway."""
        if not character.db.home_world:
            character.db.home_world = self.db.home_world or "TimMy World"
            character.db.has_traveled = False
    
    def sync_with_remote(self):
        """Fetch state from the remote world."""
        # This will be implemented with HTTP requests
        # For now, just log the attempt
        if not self.db.destination_url:
            return {"error": "No destination configured"}
        
        # TODO: HTTP request to remote Evennia bridge endpoint
        # response = requests.get(f"{self.db.destination_url}/bridge/state")
        # self.db.sync_state = response.json()
        
        return {"status": "sync requested", "destination": self.db.destination_url}
    
    def export_character(self, character):
        """Export character data for transfer to another world."""
        return {
            "name": character.key,
            "db": character.db.get_all(),
            "location": self.key,
            "home_world": self.db.home_world,
        }
    
    def import_visitor(self, visitor_data):
        """Import a visitor from another world."""
        # This is called when a character arrives from another world
        # The character object should already exist in this world
        # We just update their state
        pass
    
    def get_portal_description(self):
        """Get a description that includes portal state."""
        desc = self.db.desc or "A shimmering gateway stands before you."
        
        if self.db.bridge_active:
            desc += "\nThe gateway pulses with energy. You can feel the connection to another world."
        else:
            desc += "\nThe gateway is dim. The connection to the other side is inactive."
        
        if self.db.destination_url:
            desc += f"\nDestination: {self.db.destination_url}"
        
        if self.db.visitors:
            visitors = ", ".join(v.key for v in self.db.visitors if hasattr(v, "key"))
            desc += f"\nVisitors from other worlds: {visitors}"
        
        return desc


class TravelExit(DefaultExit):
    """
    An exit that leads to another Evennia world.
    
    When used, the character travels between worlds.
    """
    
    def at_traverse(self, traver, source_location):
        """Called when a character uses this exit."""
        super().at_traverse(traver, source_location)
        
        # Get the destination gateway
        dest = self.destination
        if hasattr(dest, 'db') and dest.db.destination_url:
            # This is where the cross-world travel happens
            self.msg(f"You step through the gateway. The world around you shimmers...")
            traver.msg(f"You arrive in {dest.key} in another world.")
            traver.db.has_traveled = True
            
            # TODO: Actually transfer character to remote world
            # For now, just change location to destination
            traver.location = dest
