#!/usr/bin/env python3
"""
Bridge Daemon — Syncs state between Evennia worlds.

Polls remote worlds and syncs:
- Character presence
- World events
- State changes

Usage:
    python world/bridge_daemon.py --remote http://vps:4003 --poll 5
"""
import argparse
import json
import time
import urllib.request
import urllib.error
import os
import sys

class BridgeDaemon:
    """Daemon that syncs state between Evennia worlds."""
    
    def __init__(self, remote_url, poll_interval=5):
        self.remote_url = remote_url.rstrip('/')
        self.poll_interval = poll_interval
        self.local_state = {
            "characters": {},
            "events": [],
            "world_name": "Timmy World",
        }
        self.last_sync = None
        self.sync_count = 0
    
    def fetch_remote_state(self):
        """Fetch state from remote world."""
        try:
            req = urllib.request.Request(
                f"{self.remote_url}/bridge/state",
                timeout=10
            )
            with urllib.request.urlopen(req) as resp:
                return json.loads(resp.read())
        except (urllib.error.URLError, json.JSONDecodeError) as e:
            print(f"Error fetching remote state: {e}")
            return None
    
    def fetch_health(self):
        """Check if remote world is healthy."""
        try:
            req = urllib.request.Request(
                f"{self.remote_url}/bridge/health",
                timeout=10
            )
            with urllib.request.urlopen(req) as resp:
                return json.loads(resp.read())
        except Exception:
            return None
    
    def sync_to_remote(self):
        """Send local state to remote world."""
        data = json.dumps(self.local_state).encode()
        try:
            req = urllib.request.Request(
                f"{self.remote_url}/bridge/sync",
                data=data,
                headers={"Content-Type": "application/json"},
                method="POST",
                timeout=10
            )
            with urllib.request.urlopen(req) as resp:
                result = json.loads(resp.read())
                return result
        except Exception as e:
            print(f"Error syncing to remote: {e}")
            return None
    
    def run(self):
        """Run the bridge daemon."""
        print(f"Bridge daemon started")
        print(f"Remote: {self.remote_url}")
        print(f"Polling every {self.poll_interval} seconds")
        print()
        
        while True:
            try:
                # Check remote health
                health = self.fetch_health()
                if health:
                    print(f"Remote world: {health.get('world', '?')} — "
                          f"Characters: {health.get('characters', 0)}, "
                          f"Events: {health.get('events', 0)}, "
                          f"Active: {health.get('active', False)}")
                    
                    # Sync states
                    remote_state = self.fetch_remote_state()
                    if remote_state:
                        # Merge remote state into local
                        # (For now, just log it)
                        print(f"  Synced {len(remote_state.get('characters', {}))} characters, "
                              f"{len(remote_state.get('events', []))} events")
                    
                    # Send our state to remote
                    sync_result = self.sync_to_remote()
                    if sync_result:
                        print(f"  Sent {len(self.local_state['characters'])} characters to remote")
                        self.sync_count += 1
                    
                    self.last_sync = time.time()
                else:
                    print(f"Remote world unreachable")
                
                print()
                
            except Exception as e:
                print(f"Error in bridge loop: {e}")
            
            time.sleep(self.poll_interval)


def main():
    parser = argparse.ArgumentParser(description='Evennia Bridge Daemon')
    parser.add_argument('--remote', required=True, help='URL of remote bridge API')
    parser.add_argument('--poll', type=int, default=5, help='Poll interval in seconds')
    args = parser.parse_args()
    
    daemon = BridgeDaemon(args.remote, args.poll)
    daemon.run()


if __name__ == '__main__':
    main()
