extends Node

# WebRTC Network Manager - For browser/WebAssembly builds
# Uses WebRTCMultiplayerPeer for P2P connections

signal connection_ready
signal connection_failed
signal session_created(session_data)
signal peer_connected_webrtc(peer_id)
signal peer_disconnected_webrtc(peer_id)

const STUN_SERVER = "stun:ruinborn.thefirstboss.com:3578"

var webrtc_peer: WebRTCMultiplayerPeer = null
var is_host: bool = false

func _ready():
	print("WebRTC: Using STUN server: ", STUN_SERVER)

func create_host() -> bool:
	print("WebRTC: Creating host")
	webrtc_peer = WebRTCMultiplayerPeer.new()
	
	# Godot 4.x API: initialize(peer_id, server_compat)
	# peer_id 1 for server, server_compat = true
	var error = webrtc_peer.initialize(1, true)
	if error != OK:
		push_error("WebRTC: Failed to initialize server: " + str(error))
		return false
	
	multiplayer.multiplayer_peer = webrtc_peer
	is_host = true
	
	# Connect signals
	webrtc_peer.peer_connected.connect(_on_peer_connected)
	webrtc_peer.peer_disconnected.connect(_on_peer_disconnected)
	
	print("WebRTC: Host initialized successfully")
	connection_ready.emit()
	return true

func create_client() -> bool:
	print("WebRTC: Creating client")
	webrtc_peer = WebRTCMultiplayerPeer.new()
	
	# Godot 4.x API: initialize(peer_id, server_compat)
	# peer_id 0 for auto-assign, server_compat = false for client
	var error = webrtc_peer.initialize(0, false)
	if error != OK:
		push_error("WebRTC: Failed to initialize client: " + str(error))
		return false
	
	multiplayer.multiplayer_peer = webrtc_peer
	is_host = false
	
	# Connect signals
	webrtc_peer.peer_connected.connect(_on_peer_connected)
	webrtc_peer.peer_disconnected.connect(_on_peer_disconnected)
	
	print("WebRTC: Client initialized successfully")
	connection_ready.emit()
	return true

func create_mesh(peer_id: int) -> bool:
	print("WebRTC: Creating mesh peer for ID ", peer_id)
	if not webrtc_peer:
		push_error("WebRTC: Peer not initialized")
		return false
	
	# Create peer connection with STUN server configured
	var peer_connection = WebRTCPeerConnection.new()
	
	# Configure STUN server for NAT traversal
	var config = {
		"iceServers": [
			{
				"urls": [STUN_SERVER]
			}
		]
	}
	
	var init_error = peer_connection.initialize(config)
	if init_error != OK:
		push_error("WebRTC: Failed to initialize peer connection: " + str(init_error))
		return false
	
	var error = webrtc_peer.add_peer(peer_connection, peer_id)
	
	if error != OK:
		push_error("WebRTC: Failed to add peer: " + str(error))
		return false
	
	print("WebRTC: Mesh peer created for ID ", peer_id, " with STUN server")
	return true

# Get the local session description (offer or answer) to share with remote peer
func get_local_session() -> String:
	if not webrtc_peer:
		return ""
	
	# Get all connection states and session descriptions
	var session_data = {}
	
	# For host, we need to create offers for each connected peer
	# For client, we need to create an answer
	
	# Note: WebRTCMultiplayerPeer handles this internally
	# We just need to get the peer connection for manual signaling
	
	# This is a simplified approach - for full WebRTC, you'd need to:
	# 1. Create RTCPeerConnection
	# 2. Create offer/answer
	# 3. Exchange ICE candidates
	
	# For now, return empty - we'll use a signaling server approach instead
	return ""

# Set the remote session description from another peer
func set_remote_session(session_data: String) -> bool:
	if not webrtc_peer:
		return false
	
	# Parse and apply remote session
	# This would involve SDP parsing and ICE candidate exchange
	
	return true

func _on_peer_connected(id: int):
	print("WebRTC: Peer connected: ", id)
	peer_connected_webrtc.emit(id)

func _on_peer_disconnected(id: int):
	print("WebRTC: Peer disconnected: ", id)
	peer_disconnected_webrtc.emit(id)

func close_connection():
	if webrtc_peer:
		webrtc_peer.close()
		webrtc_peer = null
	multiplayer.multiplayer_peer = null
	is_host = false
