#!/usr/bin/env python3
"""
Evennia Bridge API — HTTP endpoints for cross-world synchronization.

This API allows Evennia worlds on different machines to sync:
- Character presence (who is where)
- Messages (what was said)
- World events (fire, rain, growth)
- State changes

Usage:
    Start bridge server: python world/bridge_api.py
    It will listen on port 4003 (configurable)
"""
import json
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler
import time
import os

BRIDGE_PORT = int(os.environ.get('BRIDGE_PORT', 4003))
BRIDGE_HOST = os.environ.get('BRIDGE_HOST', '0.0.0.0')

# Shared state for bridge
bridge_state = {
    "world_name": "Timmy World",
    "characters": {},
    "events": [],
    "last_sync": None,
    "bridge_active": False,
}

class BridgeHandler(BaseHTTPRequestHandler):
    """HTTP handler for bridge API requests."""
    
    def do_GET(self):
        """Get bridge state."""
        if self.path == '/bridge/state':
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            response = json.dumps(bridge_state)
            self.wfile.write(response.encode())
        elif self.path == '/bridge/health':
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            response = json.dumps({
                "status": "ok",
                "world": bridge_state["world_name"],
                "characters": len(bridge_state["characters"]),
                "events": len(bridge_state["events"]),
                "active": bridge_state["bridge_active"],
            })
            self.wfile.write(response.encode())
        else:
            self.send_response(404)
            self.end_headers()
    
    def do_POST(self):
        """Post bridge events."""
        if self.path == '/bridge/sync':
            content_length = int(self.headers.get('Content-Length', 0))
            body = self.rfile.read(content_length)
            try:
                data = json.loads(body)
                # Process incoming sync data
                if 'characters' in data:
                    bridge_state['characters'].update(data['characters'])
                if 'events' in data:
                    bridge_state['events'].extend(data['events'])
                bridge_state['last_sync'] = time.time()
                bridge_state['bridge_active'] = True
                
                self.send_response(200)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                response = json.dumps({"status": "ok", "received": len(bridge_state['characters'])})
                self.wfile.write(response.encode())
            except json.JSONDecodeError:
                self.send_response(400)
                self.end_headers()
        else:
            self.send_response(404)
            self.end_headers()
    
    def log_message(self, format, *args):
        """Suppress default logging."""
        pass  # Bridge is silent


def start_bridge_server():
    """Start the bridge HTTP server in a background thread."""
    server = HTTPServer((BRIDGE_HOST, BRIDGE_PORT), BridgeHandler)
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    print(f"Bridge API server started on {BRIDGE_HOST}:{BRIDGE_PORT}")
    return server


if __name__ == '__main__':
    server = start_bridge_server()
    try:
        # Keep the main thread alive
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\nStopping bridge server...")
        server.shutdown()
