from myfasthtml.controls.VisNetwork import VisNetwork
from myfasthtml.core.instances import SingleInstance, InstancesManager
from myfasthtml.core.network_utils import from_parent_child_list


class InstancesDebugger(SingleInstance):
  def __init__(self, parent, _id=None):
    super().__init__(parent, _id=_id)
  
  def render(self):
    instances = self._get_instances()
    nodes, edges = from_parent_child_list(
      instances,
      id_getter=lambda x: f"{InstancesManager.get_session_id(x.get_session())}-{x.get_id()}",
      label_getter=lambda x: x.get_prefix(),
      parent_getter=lambda x: x.get_parent().get_id() if x.get_parent() else None
    )
    for edge in edges:
      edge["color"] = "green"
      edge["arrows"] = {"to": {"enabled": False, "type": "circle"}}
    
    for node in nodes:
      node["shape"] = "box"
    
    vis_network = VisNetwork(self, nodes=nodes, edges=edges)
    # vis_network.add_to_options(physics={"wind": {"x": 0, "y": 1}})
    return vis_network
  
  def _get_instances(self):
    return list(InstancesManager.instances.values())
  
  def __ft__(self):
    return self.render()
